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-2021, 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  NULL,
316  &allParameterTypes,
317  &parameterModes,
318  &parameterNames,
319  NULL,
320  &parameterDefaults,
321  &variadicArgType,
322  &requiredResultType);
323  /* Parameter defaults are not currently allowed by the grammar */
324  Assert(parameterDefaults == NIL);
325  /* There shouldn't have been any OUT parameters, either */
326  Assert(requiredResultType == InvalidOid);
327  }
328 
329  /*
330  * look up the aggregate's transtype.
331  *
332  * transtype can't be a pseudo-type, since we need to be able to store
333  * values of the transtype. However, we can allow polymorphic transtype
334  * in some cases (AggregateCreate will check). Also, we allow "internal"
335  * for functions that want to pass pointers to private data structures;
336  * but allow that only to superusers, since you could crash the system (or
337  * worse) by connecting up incompatible internal-using functions in an
338  * aggregate.
339  */
340  transTypeId = typenameTypeId(NULL, transType);
341  transTypeType = get_typtype(transTypeId);
342  if (transTypeType == TYPTYPE_PSEUDO &&
343  !IsPolymorphicType(transTypeId))
344  {
345  if (transTypeId == INTERNALOID && superuser())
346  /* okay */ ;
347  else
348  ereport(ERROR,
349  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
350  errmsg("aggregate transition data type cannot be %s",
351  format_type_be(transTypeId))));
352  }
353 
354  if (serialfuncName && deserialfuncName)
355  {
356  /*
357  * Serialization is only needed/allowed for transtype INTERNAL.
358  */
359  if (transTypeId != INTERNALOID)
360  ereport(ERROR,
361  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
362  errmsg("serialization functions may be specified only when the aggregate transition data type is %s",
363  format_type_be(INTERNALOID))));
364  }
365  else if (serialfuncName || deserialfuncName)
366  {
367  /*
368  * Cannot specify one function without the other.
369  */
370  ereport(ERROR,
371  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
372  errmsg("must specify both or neither of serialization and deserialization functions")));
373  }
374 
375  /*
376  * If a moving-aggregate transtype is specified, look that up. Same
377  * restrictions as for transtype.
378  */
379  if (mtransType)
380  {
381  mtransTypeId = typenameTypeId(NULL, mtransType);
382  mtransTypeType = get_typtype(mtransTypeId);
383  if (mtransTypeType == TYPTYPE_PSEUDO &&
384  !IsPolymorphicType(mtransTypeId))
385  {
386  if (mtransTypeId == INTERNALOID && superuser())
387  /* okay */ ;
388  else
389  ereport(ERROR,
390  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
391  errmsg("aggregate transition data type cannot be %s",
392  format_type_be(mtransTypeId))));
393  }
394  }
395 
396  /*
397  * If we have an initval, and it's not for a pseudotype (particularly a
398  * polymorphic type), make sure it's acceptable to the type's input
399  * function. We will store the initval as text, because the input
400  * function isn't necessarily immutable (consider "now" for timestamp),
401  * and we want to use the runtime not creation-time interpretation of the
402  * value. However, if it's an incorrect value it seems much more
403  * user-friendly to complain at CREATE AGGREGATE time.
404  */
405  if (initval && transTypeType != TYPTYPE_PSEUDO)
406  {
407  Oid typinput,
408  typioparam;
409 
410  getTypeInputInfo(transTypeId, &typinput, &typioparam);
411  (void) OidInputFunctionCall(typinput, initval, typioparam, -1);
412  }
413 
414  /*
415  * Likewise for moving-aggregate initval.
416  */
417  if (minitval && mtransTypeType != TYPTYPE_PSEUDO)
418  {
419  Oid typinput,
420  typioparam;
421 
422  getTypeInputInfo(mtransTypeId, &typinput, &typioparam);
423  (void) OidInputFunctionCall(typinput, minitval, typioparam, -1);
424  }
425 
426  if (parallel)
427  {
428  if (strcmp(parallel, "safe") == 0)
429  proparallel = PROPARALLEL_SAFE;
430  else if (strcmp(parallel, "restricted") == 0)
431  proparallel = PROPARALLEL_RESTRICTED;
432  else if (strcmp(parallel, "unsafe") == 0)
433  proparallel = PROPARALLEL_UNSAFE;
434  else
435  ereport(ERROR,
436  (errcode(ERRCODE_SYNTAX_ERROR),
437  errmsg("parameter \"parallel\" must be SAFE, RESTRICTED, or UNSAFE")));
438  }
439 
440  /*
441  * Most of the argument-checking is done inside of AggregateCreate
442  */
443  return AggregateCreate(aggName, /* aggregate name */
444  aggNamespace, /* namespace */
445  replace,
446  aggKind,
447  numArgs,
448  numDirectArgs,
449  parameterTypes,
450  PointerGetDatum(allParameterTypes),
451  PointerGetDatum(parameterModes),
452  PointerGetDatum(parameterNames),
453  parameterDefaults,
454  variadicArgType,
455  transfuncName, /* step function name */
456  finalfuncName, /* final function name */
457  combinefuncName, /* combine function name */
458  serialfuncName, /* serial function name */
459  deserialfuncName, /* deserial function name */
460  mtransfuncName, /* fwd trans function name */
461  minvtransfuncName, /* inv trans function name */
462  mfinalfuncName, /* final function name */
463  finalfuncExtraArgs,
464  mfinalfuncExtraArgs,
465  finalfuncModify,
466  mfinalfuncModify,
467  sortoperatorName, /* sort operator name */
468  transTypeId, /* transition data type */
469  transSpace, /* transition space */
470  mtransTypeId, /* transition data type */
471  mtransSpace, /* transition space */
472  initval, /* initial condition */
473  minitval, /* initial condition */
474  proparallel); /* parallel safe? */
475 }
476 
477 /*
478  * Convert the string form of [m]finalfunc_modify to the catalog representation
479  */
480 static char
482 {
483  char *val = defGetString(defel);
484 
485  if (strcmp(val, "read_only") == 0)
486  return AGGMODIFY_READ_ONLY;
487  if (strcmp(val, "shareable") == 0)
488  return AGGMODIFY_SHAREABLE;
489  if (strcmp(val, "read_write") == 0)
490  return AGGMODIFY_READ_WRITE;
491  ereport(ERROR,
492  (errcode(ERRCODE_SYNTAX_ERROR),
493  errmsg("parameter \"%s\" must be READ_ONLY, SHAREABLE, or READ_WRITE",
494  defel->defname)));
495  return 0; /* keep compiler quiet */
496 }
#define NIL
Definition: pg_list.h:65
Definition: c.h:660
Oid GetUserId(void)
Definition: miscinit.c:478
Oid QualifiedNameGetCreationNamespace(List *names, char **objname_p)
Definition: namespace.c:3040
#define PointerGetDatum(X)
Definition: postgres.h:600
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:698
bool superuser(void)
Definition: superuser.c:46
char get_typtype(Oid typid)
Definition: lsyscache.c:2576
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:4756
#define lsecond(l)
Definition: pg_list.h:179
signed int int32
Definition: c.h:429
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
bool defGetBoolean(DefElem *def)
Definition: define.c:111
TypeName * defGetTypeName(DefElem *def)
Definition: define.c:255
#define ERROR
Definition: elog.h:46
#define ACL_CREATE
Definition: parsenodes.h:92
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:3316
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2821
#define WARNING
Definition: elog.h:40
AclResult
Definition: acl.h:177
void interpret_function_parameter_list(ParseState *pstate, List *parameters, Oid languageOid, ObjectType objtype, oidvector **parameterTypes, List **parameterTypes_list, ArrayType **allParameterTypes, ArrayType **parameterModes, ArrayType **parameterNames, List **inParameterNames_list, List **parameterDefaults, Oid *variadicArgType, Oid *requiredResultType)
Definition: functioncmds.c:188
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
oidvector * buildoidvector(const Oid *oids, int n)
Definition: oid.c:167
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:515
#define intVal(v)
Definition: value.h:52
int errmsg(const char *fmt,...)
Definition: elog.c:909
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:746
Definition: pg_list.h:50
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1644
long val
Definition: informix.c:664
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:291