PostgreSQL Source Code  git master
aggregatecmds.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * aggregatecmds.c
4  *
5  * Routines for aggregate-manipulation commands
6  *
7  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *
11  * IDENTIFICATION
12  * src/backend/commands/aggregatecmds.c
13  *
14  * DESCRIPTION
15  * The "DefineFoo" routines take the parse tree and pick out the
16  * appropriate arguments/flags, passing the results to the
17  * corresponding "FooDefine" routines (in src/catalog) that do
18  * the actual catalog-munging. These routines also verify permission
19  * of the user to execute the command.
20  *
21  *-------------------------------------------------------------------------
22  */
23 #include "postgres.h"
24 
25 #include "access/htup_details.h"
26 #include "catalog/dependency.h"
27 #include "catalog/pg_aggregate.h"
28 #include "catalog/pg_proc.h"
29 #include "catalog/pg_type.h"
30 #include "commands/alter.h"
31 #include "commands/defrem.h"
32 #include "miscadmin.h"
33 #include "parser/parse_func.h"
34 #include "parser/parse_type.h"
35 #include "utils/acl.h"
36 #include "utils/builtins.h"
37 #include "utils/lsyscache.h"
38 #include "utils/syscache.h"
39 
40 
41 static char extractModify(DefElem *defel);
42 
43 
44 /*
45  * DefineAggregate
46  *
47  * "oldstyle" signals the old (pre-8.2) style where the aggregate input type
48  * is specified by a BASETYPE element in the parameters. Otherwise,
49  * "args" is a pair, whose first element is a list of FunctionParameter structs
50  * defining the agg's arguments (both direct and aggregated), and whose second
51  * element is an Integer node with the number of direct args, or -1 if this
52  * isn't an ordered-set aggregate.
53  * "parameters" is a list of DefElem representing the agg's definition clauses.
54  */
57  List *name,
58  List *args,
59  bool oldstyle,
60  List *parameters,
61  bool replace)
62 {
63  char *aggName;
64  Oid aggNamespace;
65  AclResult aclresult;
66  char aggKind = AGGKIND_NORMAL;
67  List *transfuncName = NIL;
68  List *finalfuncName = NIL;
69  List *combinefuncName = NIL;
70  List *serialfuncName = NIL;
71  List *deserialfuncName = NIL;
72  List *mtransfuncName = NIL;
73  List *minvtransfuncName = NIL;
74  List *mfinalfuncName = NIL;
75  bool finalfuncExtraArgs = false;
76  bool mfinalfuncExtraArgs = false;
77  char finalfuncModify = 0;
78  char mfinalfuncModify = 0;
79  List *sortoperatorName = NIL;
80  TypeName *baseType = NULL;
81  TypeName *transType = NULL;
82  TypeName *mtransType = NULL;
83  int32 transSpace = 0;
84  int32 mtransSpace = 0;
85  char *initval = NULL;
86  char *minitval = NULL;
87  char *parallel = NULL;
88  int numArgs;
89  int numDirectArgs = 0;
90  oidvector *parameterTypes;
91  ArrayType *allParameterTypes;
92  ArrayType *parameterModes;
93  ArrayType *parameterNames;
94  List *parameterDefaults;
95  Oid variadicArgType;
96  Oid transTypeId;
97  Oid mtransTypeId = InvalidOid;
98  char transTypeType;
99  char mtransTypeType = 0;
100  char proparallel = PROPARALLEL_UNSAFE;
101  ListCell *pl;
102 
103  /* Convert list of names to a name and namespace */
104  aggNamespace = QualifiedNameGetCreationNamespace(name, &aggName);
105 
106  /* Check we have creation rights in target namespace */
107  aclresult = pg_namespace_aclcheck(aggNamespace, GetUserId(), ACL_CREATE);
108  if (aclresult != ACLCHECK_OK)
109  aclcheck_error(aclresult, OBJECT_SCHEMA,
110  get_namespace_name(aggNamespace));
111 
112  /* Deconstruct the output of the aggr_args grammar production */
113  if (!oldstyle)
114  {
115  Assert(list_length(args) == 2);
116  numDirectArgs = intVal(lsecond(args));
117  if (numDirectArgs >= 0)
118  aggKind = AGGKIND_ORDERED_SET;
119  else
120  numDirectArgs = 0;
121  args = linitial_node(List, args);
122  }
123 
124  /* Examine aggregate's definition clauses */
125  foreach(pl, parameters)
126  {
127  DefElem *defel = lfirst_node(DefElem, pl);
128 
129  /*
130  * sfunc1, stype1, and initcond1 are accepted as obsolete spellings
131  * for sfunc, stype, initcond.
132  */
133  if (strcmp(defel->defname, "sfunc") == 0)
134  transfuncName = defGetQualifiedName(defel);
135  else if (strcmp(defel->defname, "sfunc1") == 0)
136  transfuncName = defGetQualifiedName(defel);
137  else if (strcmp(defel->defname, "finalfunc") == 0)
138  finalfuncName = defGetQualifiedName(defel);
139  else if (strcmp(defel->defname, "combinefunc") == 0)
140  combinefuncName = defGetQualifiedName(defel);
141  else if (strcmp(defel->defname, "serialfunc") == 0)
142  serialfuncName = defGetQualifiedName(defel);
143  else if (strcmp(defel->defname, "deserialfunc") == 0)
144  deserialfuncName = defGetQualifiedName(defel);
145  else if (strcmp(defel->defname, "msfunc") == 0)
146  mtransfuncName = defGetQualifiedName(defel);
147  else if (strcmp(defel->defname, "minvfunc") == 0)
148  minvtransfuncName = defGetQualifiedName(defel);
149  else if (strcmp(defel->defname, "mfinalfunc") == 0)
150  mfinalfuncName = defGetQualifiedName(defel);
151  else if (strcmp(defel->defname, "finalfunc_extra") == 0)
152  finalfuncExtraArgs = defGetBoolean(defel);
153  else if (strcmp(defel->defname, "mfinalfunc_extra") == 0)
154  mfinalfuncExtraArgs = defGetBoolean(defel);
155  else if (strcmp(defel->defname, "finalfunc_modify") == 0)
156  finalfuncModify = extractModify(defel);
157  else if (strcmp(defel->defname, "mfinalfunc_modify") == 0)
158  mfinalfuncModify = extractModify(defel);
159  else if (strcmp(defel->defname, "sortop") == 0)
160  sortoperatorName = defGetQualifiedName(defel);
161  else if (strcmp(defel->defname, "basetype") == 0)
162  baseType = defGetTypeName(defel);
163  else if (strcmp(defel->defname, "hypothetical") == 0)
164  {
165  if (defGetBoolean(defel))
166  {
167  if (aggKind == AGGKIND_NORMAL)
168  ereport(ERROR,
169  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
170  errmsg("only ordered-set aggregates can be hypothetical")));
171  aggKind = AGGKIND_HYPOTHETICAL;
172  }
173  }
174  else if (strcmp(defel->defname, "stype") == 0)
175  transType = defGetTypeName(defel);
176  else if (strcmp(defel->defname, "stype1") == 0)
177  transType = defGetTypeName(defel);
178  else if (strcmp(defel->defname, "sspace") == 0)
179  transSpace = defGetInt32(defel);
180  else if (strcmp(defel->defname, "mstype") == 0)
181  mtransType = defGetTypeName(defel);
182  else if (strcmp(defel->defname, "msspace") == 0)
183  mtransSpace = defGetInt32(defel);
184  else if (strcmp(defel->defname, "initcond") == 0)
185  initval = defGetString(defel);
186  else if (strcmp(defel->defname, "initcond1") == 0)
187  initval = defGetString(defel);
188  else if (strcmp(defel->defname, "minitcond") == 0)
189  minitval = defGetString(defel);
190  else if (strcmp(defel->defname, "parallel") == 0)
191  parallel = defGetString(defel);
192  else
194  (errcode(ERRCODE_SYNTAX_ERROR),
195  errmsg("aggregate attribute \"%s\" not recognized",
196  defel->defname)));
197  }
198 
199  /*
200  * make sure we have our required definitions
201  */
202  if (transType == NULL)
203  ereport(ERROR,
204  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
205  errmsg("aggregate stype must be specified")));
206  if (transfuncName == NIL)
207  ereport(ERROR,
208  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
209  errmsg("aggregate sfunc must be specified")));
210 
211  /*
212  * if mtransType is given, mtransfuncName and minvtransfuncName must be as
213  * well; if not, then none of the moving-aggregate options should have
214  * been given.
215  */
216  if (mtransType != NULL)
217  {
218  if (mtransfuncName == NIL)
219  ereport(ERROR,
220  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
221  errmsg("aggregate msfunc must be specified when mstype is specified")));
222  if (minvtransfuncName == NIL)
223  ereport(ERROR,
224  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
225  errmsg("aggregate minvfunc must be specified when mstype is specified")));
226  }
227  else
228  {
229  if (mtransfuncName != NIL)
230  ereport(ERROR,
231  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
232  errmsg("aggregate msfunc must not be specified without mstype")));
233  if (minvtransfuncName != NIL)
234  ereport(ERROR,
235  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
236  errmsg("aggregate minvfunc must not be specified without mstype")));
237  if (mfinalfuncName != NIL)
238  ereport(ERROR,
239  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
240  errmsg("aggregate mfinalfunc must not be specified without mstype")));
241  if (mtransSpace != 0)
242  ereport(ERROR,
243  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
244  errmsg("aggregate msspace must not be specified without mstype")));
245  if (minitval != NULL)
246  ereport(ERROR,
247  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
248  errmsg("aggregate minitcond must not be specified without mstype")));
249  }
250 
251  /*
252  * Default values for modify flags can only be determined once we know the
253  * aggKind.
254  */
255  if (finalfuncModify == 0)
256  finalfuncModify = (aggKind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
257  if (mfinalfuncModify == 0)
258  mfinalfuncModify = (aggKind == AGGKIND_NORMAL) ? AGGMODIFY_READ_ONLY : AGGMODIFY_READ_WRITE;
259 
260  /*
261  * look up the aggregate's input datatype(s).
262  */
263  if (oldstyle)
264  {
265  /*
266  * Old style: use basetype parameter. This supports aggregates of
267  * zero or one input, with input type ANY meaning zero inputs.
268  *
269  * Historically we allowed the command to look like basetype = 'ANY'
270  * so we must do a case-insensitive comparison for the name ANY. Ugh.
271  */
272  Oid aggArgTypes[1];
273 
274  if (baseType == NULL)
275  ereport(ERROR,
276  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
277  errmsg("aggregate input type must be specified")));
278 
279  if (pg_strcasecmp(TypeNameToString(baseType), "ANY") == 0)
280  {
281  numArgs = 0;
282  aggArgTypes[0] = InvalidOid;
283  }
284  else
285  {
286  numArgs = 1;
287  aggArgTypes[0] = typenameTypeId(NULL, baseType);
288  }
289  parameterTypes = buildoidvector(aggArgTypes, numArgs);
290  allParameterTypes = NULL;
291  parameterModes = NULL;
292  parameterNames = NULL;
293  parameterDefaults = NIL;
294  variadicArgType = InvalidOid;
295  }
296  else
297  {
298  /*
299  * New style: args is a list of FunctionParameters (possibly zero of
300  * 'em). We share functioncmds.c's code for processing them.
301  */
302  Oid requiredResultType;
303 
304  if (baseType != NULL)
305  ereport(ERROR,
306  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
307  errmsg("basetype is redundant with aggregate input type specification")));
308 
309  numArgs = list_length(args);
311  args,
312  InvalidOid,
314  &parameterTypes,
315  &allParameterTypes,
316  &parameterModes,
317  &parameterNames,
318  &parameterDefaults,
319  &variadicArgType,
320  &requiredResultType);
321  /* Parameter defaults are not currently allowed by the grammar */
322  Assert(parameterDefaults == NIL);
323  /* There shouldn't have been any OUT parameters, either */
324  Assert(requiredResultType == InvalidOid);
325  }
326 
327  /*
328  * look up the aggregate's transtype.
329  *
330  * transtype can't be a pseudo-type, since we need to be able to store
331  * values of the transtype. However, we can allow polymorphic transtype
332  * in some cases (AggregateCreate will check). Also, we allow "internal"
333  * for functions that want to pass pointers to private data structures;
334  * but allow that only to superusers, since you could crash the system (or
335  * worse) by connecting up incompatible internal-using functions in an
336  * aggregate.
337  */
338  transTypeId = typenameTypeId(NULL, transType);
339  transTypeType = get_typtype(transTypeId);
340  if (transTypeType == TYPTYPE_PSEUDO &&
341  !IsPolymorphicType(transTypeId))
342  {
343  if (transTypeId == INTERNALOID && superuser())
344  /* okay */ ;
345  else
346  ereport(ERROR,
347  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
348  errmsg("aggregate transition data type cannot be %s",
349  format_type_be(transTypeId))));
350  }
351 
352  if (serialfuncName && deserialfuncName)
353  {
354  /*
355  * Serialization is only needed/allowed for transtype INTERNAL.
356  */
357  if (transTypeId != INTERNALOID)
358  ereport(ERROR,
359  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
360  errmsg("serialization functions may be specified only when the aggregate transition data type is %s",
361  format_type_be(INTERNALOID))));
362  }
363  else if (serialfuncName || deserialfuncName)
364  {
365  /*
366  * Cannot specify one function without the other.
367  */
368  ereport(ERROR,
369  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
370  errmsg("must specify both or neither of serialization and deserialization functions")));
371  }
372 
373  /*
374  * If a moving-aggregate transtype is specified, look that up. Same
375  * restrictions as for transtype.
376  */
377  if (mtransType)
378  {
379  mtransTypeId = typenameTypeId(NULL, mtransType);
380  mtransTypeType = get_typtype(mtransTypeId);
381  if (mtransTypeType == TYPTYPE_PSEUDO &&
382  !IsPolymorphicType(mtransTypeId))
383  {
384  if (mtransTypeId == INTERNALOID && superuser())
385  /* okay */ ;
386  else
387  ereport(ERROR,
388  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
389  errmsg("aggregate transition data type cannot be %s",
390  format_type_be(mtransTypeId))));
391  }
392  }
393 
394  /*
395  * If we have an initval, and it's not for a pseudotype (particularly a
396  * polymorphic type), make sure it's acceptable to the type's input
397  * function. We will store the initval as text, because the input
398  * function isn't necessarily immutable (consider "now" for timestamp),
399  * and we want to use the runtime not creation-time interpretation of the
400  * value. However, if it's an incorrect value it seems much more
401  * user-friendly to complain at CREATE AGGREGATE time.
402  */
403  if (initval && transTypeType != TYPTYPE_PSEUDO)
404  {
405  Oid typinput,
406  typioparam;
407 
408  getTypeInputInfo(transTypeId, &typinput, &typioparam);
409  (void) OidInputFunctionCall(typinput, initval, typioparam, -1);
410  }
411 
412  /*
413  * Likewise for moving-aggregate initval.
414  */
415  if (minitval && mtransTypeType != TYPTYPE_PSEUDO)
416  {
417  Oid typinput,
418  typioparam;
419 
420  getTypeInputInfo(mtransTypeId, &typinput, &typioparam);
421  (void) OidInputFunctionCall(typinput, minitval, typioparam, -1);
422  }
423 
424  if (parallel)
425  {
426  if (strcmp(parallel, "safe") == 0)
427  proparallel = PROPARALLEL_SAFE;
428  else if (strcmp(parallel, "restricted") == 0)
429  proparallel = PROPARALLEL_RESTRICTED;
430  else if (strcmp(parallel, "unsafe") == 0)
431  proparallel = PROPARALLEL_UNSAFE;
432  else
433  ereport(ERROR,
434  (errcode(ERRCODE_SYNTAX_ERROR),
435  errmsg("parameter \"parallel\" must be SAFE, RESTRICTED, or UNSAFE")));
436  }
437 
438  /*
439  * Most of the argument-checking is done inside of AggregateCreate
440  */
441  return AggregateCreate(aggName, /* aggregate name */
442  aggNamespace, /* namespace */
443  replace,
444  aggKind,
445  numArgs,
446  numDirectArgs,
447  parameterTypes,
448  PointerGetDatum(allParameterTypes),
449  PointerGetDatum(parameterModes),
450  PointerGetDatum(parameterNames),
451  parameterDefaults,
452  variadicArgType,
453  transfuncName, /* step function name */
454  finalfuncName, /* final function name */
455  combinefuncName, /* combine function name */
456  serialfuncName, /* serial function name */
457  deserialfuncName, /* deserial function name */
458  mtransfuncName, /* fwd trans function name */
459  minvtransfuncName, /* inv trans function name */
460  mfinalfuncName, /* final function name */
461  finalfuncExtraArgs,
462  mfinalfuncExtraArgs,
463  finalfuncModify,
464  mfinalfuncModify,
465  sortoperatorName, /* sort operator name */
466  transTypeId, /* transition data type */
467  transSpace, /* transition space */
468  mtransTypeId, /* transition data type */
469  mtransSpace, /* transition space */
470  initval, /* initial condition */
471  minitval, /* initial condition */
472  proparallel); /* parallel safe? */
473 }
474 
475 /*
476  * Convert the string form of [m]finalfunc_modify to the catalog representation
477  */
478 static char
480 {
481  char *val = defGetString(defel);
482 
483  if (strcmp(val, "read_only") == 0)
484  return AGGMODIFY_READ_ONLY;
485  if (strcmp(val, "shareable") == 0)
486  return AGGMODIFY_SHAREABLE;
487  if (strcmp(val, "read_write") == 0)
488  return AGGMODIFY_READ_WRITE;
489  ereport(ERROR,
490  (errcode(ERRCODE_SYNTAX_ERROR),
491  errmsg("parameter \"%s\" must be READ_ONLY, SHAREABLE, or READ_WRITE",
492  defel->defname)));
493  return 0; /* keep compiler quiet */
494 }
#define NIL
Definition: pg_list.h:65
Definition: c.h:656
Oid GetUserId(void)
Definition: miscinit.c:476
Oid QualifiedNameGetCreationNamespace(List *names, char **objname_p)
Definition: namespace.c:2994
#define PointerGetDatum(X)
Definition: postgres.h:556
char * TypeNameToString(const TypeName *typeName)
Definition: parse_type.c:476
ObjectAddress DefineAggregate(ParseState *pstate, List *name, List *args, bool oldstyle, List *parameters, bool replace)
Definition: aggregatecmds.c:56
int32 defGetInt32(DefElem *def)
Definition: define.c:166
int errcode(int sqlerrcode)
Definition: elog.c:691
bool superuser(void)
Definition: superuser.c:46
char get_typtype(Oid typid)
Definition: lsyscache.c:2522
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
unsigned int Oid
Definition: postgres_ext.h:31
#define linitial_node(type, l)
Definition: pg_list.h:177
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4625
#define lsecond(l)
Definition: pg_list.h:179
signed int int32
Definition: c.h:417
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
bool defGetBoolean(DefElem *def)
Definition: define.c:111
TypeName * defGetTypeName(DefElem *def)
Definition: define.c:255
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:84
char * defGetString(DefElem *def)
Definition: define.c:49
static char extractModify(DefElem *defel)
#define lfirst_node(type, lc)
Definition: pg_list.h:172
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3196
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2756
#define WARNING
Definition: elog.h:40
AclResult
Definition: acl.h:177
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:800
oidvector * buildoidvector(const Oid *oids, int n)
Definition: oid.c:167
void interpret_function_parameter_list(ParseState *pstate, List *parameters, Oid languageOid, ObjectType objtype, oidvector **parameterTypes, ArrayType **allParameterTypes, ArrayType **parameterModes, ArrayType **parameterNames, List **parameterDefaults, Oid *variadicArgType, Oid *requiredResultType)
Definition: functioncmds.c:184
List * defGetQualifiedName(DefElem *def)
Definition: define.c:223
static int list_length(const List *l)
Definition: pg_list.h:149
const char * name
Definition: encode.c:561
#define intVal(v)
Definition: value.h:52
int errmsg(const char *fmt,...)
Definition: elog.c:902
ObjectAddress AggregateCreate(const char *aggName, Oid aggNamespace, bool replace, char aggKind, int numArgs, int numDirectArgs, oidvector *parameterTypes, Datum allParameterTypes, Datum parameterModes, Datum parameterNames, List *parameterDefaults, Oid variadicArgType, List *aggtransfnName, List *aggfinalfnName, List *aggcombinefnName, List *aggserialfnName, List *aggdeserialfnName, List *aggmtransfnName, List *aggminvtransfnName, List *aggmfinalfnName, bool finalfnExtraArgs, bool mfinalfnExtraArgs, char finalfnModify, char mfinalfnModify, List *aggsortopName, Oid aggTransType, int32 aggTransSpace, Oid aggmTransType, int32 aggmTransSpace, const char *agginitval, const char *aggminitval, char proparallel)
Definition: pg_aggregate.c:46
char * defname
Definition: parsenodes.h:733
Definition: pg_list.h:50
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1648
long val
Definition: informix.c:664
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291