PostgreSQL Source Code  git master
parse_agg.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * parse_agg.c
4  * handle aggregates and window functions in parser
5  *
6  * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/parser/parse_agg.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include "catalog/pg_aggregate.h"
18 #include "catalog/pg_constraint.h"
19 #include "catalog/pg_type.h"
20 #include "nodes/makefuncs.h"
21 #include "nodes/nodeFuncs.h"
22 #include "optimizer/tlist.h"
23 #include "optimizer/var.h"
24 #include "parser/parse_agg.h"
25 #include "parser/parse_clause.h"
26 #include "parser/parse_coerce.h"
27 #include "parser/parse_expr.h"
28 #include "parser/parsetree.h"
29 #include "rewrite/rewriteManip.h"
30 #include "utils/builtins.h"
31 #include "utils/lsyscache.h"
32 
33 
34 typedef struct
35 {
41 
42 typedef struct
43 {
54 
55 static int check_agg_arguments(ParseState *pstate,
56  List *directargs,
57  List *args,
58  Expr *filter);
59 static bool check_agg_arguments_walker(Node *node,
61 static void check_ungrouped_columns(Node *node, ParseState *pstate, Query *qry,
62  List *groupClauses, List *groupClauseVars,
63  bool have_non_var_grouping,
64  List **func_grouped_rels);
65 static bool check_ungrouped_columns_walker(Node *node,
67 static void finalize_grouping_exprs(Node *node, ParseState *pstate, Query *qry,
68  List *groupClauses, PlannerInfo *root,
69  bool have_non_var_grouping);
70 static bool finalize_grouping_exprs_walker(Node *node,
72 static void check_agglevels_and_constraints(ParseState *pstate, Node *expr);
74 static Node *make_agg_arg(Oid argtype, Oid argcollation);
75 
76 
77 /*
78  * transformAggregateCall -
79  * Finish initial transformation of an aggregate call
80  *
81  * parse_func.c has recognized the function as an aggregate, and has set up
82  * all the fields of the Aggref except aggargtypes, aggdirectargs, args,
83  * aggorder, aggdistinct and agglevelsup. The passed-in args list has been
84  * through standard expression transformation and type coercion to match the
85  * agg's declared arg types, while the passed-in aggorder list hasn't been
86  * transformed at all.
87  *
88  * Here we separate the args list into direct and aggregated args, storing the
89  * former in agg->aggdirectargs and the latter in agg->args. The regular
90  * args, but not the direct args, are converted into a targetlist by inserting
91  * TargetEntry nodes. We then transform the aggorder and agg_distinct
92  * specifications to produce lists of SortGroupClause nodes for agg->aggorder
93  * and agg->aggdistinct. (For a regular aggregate, this might result in
94  * adding resjunk expressions to the targetlist; but for ordered-set
95  * aggregates the aggorder list will always be one-to-one with the aggregated
96  * args.)
97  *
98  * We must also determine which query level the aggregate actually belongs to,
99  * set agglevelsup accordingly, and mark p_hasAggs true in the corresponding
100  * pstate level.
101  */
102 void
104  List *args, List *aggorder, bool agg_distinct)
105 {
106  List *argtypes = NIL;
107  List *tlist = NIL;
108  List *torder = NIL;
109  List *tdistinct = NIL;
110  AttrNumber attno = 1;
111  int save_next_resno;
112  ListCell *lc;
113 
114  /*
115  * Before separating the args into direct and aggregated args, make a list
116  * of their data type OIDs for use later.
117  */
118  foreach(lc, args)
119  {
120  Expr *arg = (Expr *) lfirst(lc);
121 
122  argtypes = lappend_oid(argtypes, exprType((Node *) arg));
123  }
124  agg->aggargtypes = argtypes;
125 
126  if (AGGKIND_IS_ORDERED_SET(agg->aggkind))
127  {
128  /*
129  * For an ordered-set agg, the args list includes direct args and
130  * aggregated args; we must split them apart.
131  */
132  int numDirectArgs = list_length(args) - list_length(aggorder);
133  List *aargs;
134  ListCell *lc2;
135 
136  Assert(numDirectArgs >= 0);
137 
138  aargs = list_copy_tail(args, numDirectArgs);
139  agg->aggdirectargs = list_truncate(args, numDirectArgs);
140 
141  /*
142  * Build a tlist from the aggregated args, and make a sortlist entry
143  * for each one. Note that the expressions in the SortBy nodes are
144  * ignored (they are the raw versions of the transformed args); we are
145  * just looking at the sort information in the SortBy nodes.
146  */
147  forboth(lc, aargs, lc2, aggorder)
148  {
149  Expr *arg = (Expr *) lfirst(lc);
150  SortBy *sortby = (SortBy *) lfirst(lc2);
151  TargetEntry *tle;
152 
153  /* We don't bother to assign column names to the entries */
154  tle = makeTargetEntry(arg, attno++, NULL, false);
155  tlist = lappend(tlist, tle);
156 
157  torder = addTargetToSortList(pstate, tle,
158  torder, tlist, sortby);
159  }
160 
161  /* Never any DISTINCT in an ordered-set agg */
162  Assert(!agg_distinct);
163  }
164  else
165  {
166  /* Regular aggregate, so it has no direct args */
167  agg->aggdirectargs = NIL;
168 
169  /*
170  * Transform the plain list of Exprs into a targetlist.
171  */
172  foreach(lc, args)
173  {
174  Expr *arg = (Expr *) lfirst(lc);
175  TargetEntry *tle;
176 
177  /* We don't bother to assign column names to the entries */
178  tle = makeTargetEntry(arg, attno++, NULL, false);
179  tlist = lappend(tlist, tle);
180  }
181 
182  /*
183  * If we have an ORDER BY, transform it. This will add columns to the
184  * tlist if they appear in ORDER BY but weren't already in the arg
185  * list. They will be marked resjunk = true so we can tell them apart
186  * from regular aggregate arguments later.
187  *
188  * We need to mess with p_next_resno since it will be used to number
189  * any new targetlist entries.
190  */
191  save_next_resno = pstate->p_next_resno;
192  pstate->p_next_resno = attno;
193 
194  torder = transformSortClause(pstate,
195  aggorder,
196  &tlist,
198  true /* force SQL99 rules */ );
199 
200  /*
201  * If we have DISTINCT, transform that to produce a distinctList.
202  */
203  if (agg_distinct)
204  {
205  tdistinct = transformDistinctClause(pstate, &tlist, torder, true);
206 
207  /*
208  * Remove this check if executor support for hashed distinct for
209  * aggregates is ever added.
210  */
211  foreach(lc, tdistinct)
212  {
213  SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc);
214 
215  if (!OidIsValid(sortcl->sortop))
216  {
217  Node *expr = get_sortgroupclause_expr(sortcl, tlist);
218 
219  ereport(ERROR,
220  (errcode(ERRCODE_UNDEFINED_FUNCTION),
221  errmsg("could not identify an ordering operator for type %s",
222  format_type_be(exprType(expr))),
223  errdetail("Aggregates with DISTINCT must be able to sort their inputs."),
224  parser_errposition(pstate, exprLocation(expr))));
225  }
226  }
227  }
228 
229  pstate->p_next_resno = save_next_resno;
230  }
231 
232  /* Update the Aggref with the transformation results */
233  agg->args = tlist;
234  agg->aggorder = torder;
235  agg->aggdistinct = tdistinct;
236 
237  check_agglevels_and_constraints(pstate, (Node *) agg);
238 }
239 
240 /*
241  * transformGroupingFunc
242  * Transform a GROUPING expression
243  *
244  * GROUPING() behaves very like an aggregate. Processing of levels and nesting
245  * is done as for aggregates. We set p_hasAggs for these expressions too.
246  */
247 Node *
249 {
250  ListCell *lc;
251  List *args = p->args;
252  List *result_list = NIL;
254 
255  if (list_length(args) > 31)
256  ereport(ERROR,
257  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
258  errmsg("GROUPING must have fewer than 32 arguments"),
259  parser_errposition(pstate, p->location)));
260 
261  foreach(lc, args)
262  {
263  Node *current_result;
264 
265  current_result = transformExpr(pstate, (Node *) lfirst(lc), pstate->p_expr_kind);
266 
267  /* acceptability of expressions is checked later */
268 
269  result_list = lappend(result_list, current_result);
270  }
271 
272  result->args = result_list;
273  result->location = p->location;
274 
275  check_agglevels_and_constraints(pstate, (Node *) result);
276 
277  return (Node *) result;
278 }
279 
280 /*
281  * Aggregate functions and grouping operations (which are combined in the spec
282  * as <set function specification>) are very similar with regard to level and
283  * nesting restrictions (though we allow a lot more things than the spec does).
284  * Centralise those restrictions here.
285  */
286 static void
288 {
289  List *directargs = NIL;
290  List *args = NIL;
291  Expr *filter = NULL;
292  int min_varlevel;
293  int location = -1;
294  Index *p_levelsup;
295  const char *err;
296  bool errkind;
297  bool isAgg = IsA(expr, Aggref);
298 
299  if (isAgg)
300  {
301  Aggref *agg = (Aggref *) expr;
302 
303  directargs = agg->aggdirectargs;
304  args = agg->args;
305  filter = agg->aggfilter;
306  location = agg->location;
307  p_levelsup = &agg->agglevelsup;
308  }
309  else
310  {
311  GroupingFunc *grp = (GroupingFunc *) expr;
312 
313  args = grp->args;
314  location = grp->location;
315  p_levelsup = &grp->agglevelsup;
316  }
317 
318  /*
319  * Check the arguments to compute the aggregate's level and detect
320  * improper nesting.
321  */
322  min_varlevel = check_agg_arguments(pstate,
323  directargs,
324  args,
325  filter);
326 
327  *p_levelsup = min_varlevel;
328 
329  /* Mark the correct pstate level as having aggregates */
330  while (min_varlevel-- > 0)
331  pstate = pstate->parentParseState;
332  pstate->p_hasAggs = true;
333 
334  /*
335  * Check to see if the aggregate function is in an invalid place within
336  * its aggregation query.
337  *
338  * For brevity we support two schemes for reporting an error here: set
339  * "err" to a custom message, or set "errkind" true if the error context
340  * is sufficiently identified by what ParseExprKindName will return, *and*
341  * what it will return is just a SQL keyword. (Otherwise, use a custom
342  * message to avoid creating translation problems.)
343  */
344  err = NULL;
345  errkind = false;
346  switch (pstate->p_expr_kind)
347  {
348  case EXPR_KIND_NONE:
349  Assert(false); /* can't happen */
350  break;
351  case EXPR_KIND_OTHER:
352 
353  /*
354  * Accept aggregate/grouping here; caller must throw error if
355  * wanted
356  */
357  break;
358  case EXPR_KIND_JOIN_ON:
360  if (isAgg)
361  err = _("aggregate functions are not allowed in JOIN conditions");
362  else
363  err = _("grouping operations are not allowed in JOIN conditions");
364 
365  break;
367  /* Should only be possible in a LATERAL subquery */
368  Assert(pstate->p_lateral_active);
369 
370  /*
371  * Aggregate/grouping scope rules make it worth being explicit
372  * here
373  */
374  if (isAgg)
375  err = _("aggregate functions are not allowed in FROM clause of their own query level");
376  else
377  err = _("grouping operations are not allowed in FROM clause of their own query level");
378 
379  break;
381  if (isAgg)
382  err = _("aggregate functions are not allowed in functions in FROM");
383  else
384  err = _("grouping operations are not allowed in functions in FROM");
385 
386  break;
387  case EXPR_KIND_WHERE:
388  errkind = true;
389  break;
390  case EXPR_KIND_POLICY:
391  if (isAgg)
392  err = _("aggregate functions are not allowed in policy expressions");
393  else
394  err = _("grouping operations are not allowed in policy expressions");
395 
396  break;
397  case EXPR_KIND_HAVING:
398  /* okay */
399  break;
400  case EXPR_KIND_FILTER:
401  errkind = true;
402  break;
404  /* okay */
405  break;
407  /* okay */
408  break;
410  if (isAgg)
411  err = _("aggregate functions are not allowed in window RANGE");
412  else
413  err = _("grouping operations are not allowed in window RANGE");
414 
415  break;
417  if (isAgg)
418  err = _("aggregate functions are not allowed in window ROWS");
419  else
420  err = _("grouping operations are not allowed in window ROWS");
421 
422  break;
424  if (isAgg)
425  err = _("aggregate functions are not allowed in window GROUPS");
426  else
427  err = _("grouping operations are not allowed in window GROUPS");
428 
429  break;
431  /* okay */
432  break;
436  errkind = true;
437  break;
438  case EXPR_KIND_GROUP_BY:
439  errkind = true;
440  break;
441  case EXPR_KIND_ORDER_BY:
442  /* okay */
443  break;
445  /* okay */
446  break;
447  case EXPR_KIND_LIMIT:
448  case EXPR_KIND_OFFSET:
449  errkind = true;
450  break;
451  case EXPR_KIND_RETURNING:
452  errkind = true;
453  break;
454  case EXPR_KIND_VALUES:
456  errkind = true;
457  break;
460  if (isAgg)
461  err = _("aggregate functions are not allowed in check constraints");
462  else
463  err = _("grouping operations are not allowed in check constraints");
464 
465  break;
468 
469  if (isAgg)
470  err = _("aggregate functions are not allowed in DEFAULT expressions");
471  else
472  err = _("grouping operations are not allowed in DEFAULT expressions");
473 
474  break;
476  if (isAgg)
477  err = _("aggregate functions are not allowed in index expressions");
478  else
479  err = _("grouping operations are not allowed in index expressions");
480 
481  break;
483  if (isAgg)
484  err = _("aggregate functions are not allowed in index predicates");
485  else
486  err = _("grouping operations are not allowed in index predicates");
487 
488  break;
490  if (isAgg)
491  err = _("aggregate functions are not allowed in transform expressions");
492  else
493  err = _("grouping operations are not allowed in transform expressions");
494 
495  break;
497  if (isAgg)
498  err = _("aggregate functions are not allowed in EXECUTE parameters");
499  else
500  err = _("grouping operations are not allowed in EXECUTE parameters");
501 
502  break;
504  if (isAgg)
505  err = _("aggregate functions are not allowed in trigger WHEN conditions");
506  else
507  err = _("grouping operations are not allowed in trigger WHEN conditions");
508 
509  break;
511  if (isAgg)
512  err = _("aggregate functions are not allowed in partition key expressions");
513  else
514  err = _("grouping operations are not allowed in partition key expressions");
515 
516  break;
517 
519  if (isAgg)
520  err = _("aggregate functions are not allowed in CALL arguments");
521  else
522  err = _("grouping operations are not allowed in CALL arguments");
523 
524  break;
525 
526  /*
527  * There is intentionally no default: case here, so that the
528  * compiler will warn if we add a new ParseExprKind without
529  * extending this switch. If we do see an unrecognized value at
530  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
531  * which is sane anyway.
532  */
533  }
534 
535  if (err)
536  ereport(ERROR,
537  (errcode(ERRCODE_GROUPING_ERROR),
538  errmsg_internal("%s", err),
539  parser_errposition(pstate, location)));
540 
541  if (errkind)
542  {
543  if (isAgg)
544  /* translator: %s is name of a SQL construct, eg GROUP BY */
545  err = _("aggregate functions are not allowed in %s");
546  else
547  /* translator: %s is name of a SQL construct, eg GROUP BY */
548  err = _("grouping operations are not allowed in %s");
549 
550  ereport(ERROR,
551  (errcode(ERRCODE_GROUPING_ERROR),
552  errmsg_internal(err,
553  ParseExprKindName(pstate->p_expr_kind)),
554  parser_errposition(pstate, location)));
555  }
556 }
557 
558 /*
559  * check_agg_arguments
560  * Scan the arguments of an aggregate function to determine the
561  * aggregate's semantic level (zero is the current select's level,
562  * one is its parent, etc).
563  *
564  * The aggregate's level is the same as the level of the lowest-level variable
565  * or aggregate in its aggregated arguments (including any ORDER BY columns)
566  * or filter expression; or if it contains no variables at all, we presume it
567  * to be local.
568  *
569  * Vars/Aggs in direct arguments are *not* counted towards determining the
570  * agg's level, as those arguments aren't evaluated per-row but only
571  * per-group, and so in some sense aren't really agg arguments. However,
572  * this can mean that we decide an agg is upper-level even when its direct
573  * args contain lower-level Vars/Aggs, and that case has to be disallowed.
574  * (This is a little strange, but the SQL standard seems pretty definite that
575  * direct args are not to be considered when setting the agg's level.)
576  *
577  * We also take this opportunity to detect any aggregates or window functions
578  * nested within the arguments. We can throw error immediately if we find
579  * a window function. Aggregates are a bit trickier because it's only an
580  * error if the inner aggregate is of the same semantic level as the outer,
581  * which we can't know until we finish scanning the arguments.
582  */
583 static int
585  List *directargs,
586  List *args,
587  Expr *filter)
588 {
589  int agglevel;
591 
592  context.pstate = pstate;
593  context.min_varlevel = -1; /* signifies nothing found yet */
594  context.min_agglevel = -1;
595  context.sublevels_up = 0;
596 
597  (void) expression_tree_walker((Node *) args,
599  (void *) &context);
600 
601  (void) expression_tree_walker((Node *) filter,
603  (void *) &context);
604 
605  /*
606  * If we found no vars nor aggs at all, it's a level-zero aggregate;
607  * otherwise, its level is the minimum of vars or aggs.
608  */
609  if (context.min_varlevel < 0)
610  {
611  if (context.min_agglevel < 0)
612  agglevel = 0;
613  else
614  agglevel = context.min_agglevel;
615  }
616  else if (context.min_agglevel < 0)
617  agglevel = context.min_varlevel;
618  else
619  agglevel = Min(context.min_varlevel, context.min_agglevel);
620 
621  /*
622  * If there's a nested aggregate of the same semantic level, complain.
623  */
624  if (agglevel == context.min_agglevel)
625  {
626  int aggloc;
627 
628  aggloc = locate_agg_of_level((Node *) args, agglevel);
629  if (aggloc < 0)
630  aggloc = locate_agg_of_level((Node *) filter, agglevel);
631  ereport(ERROR,
632  (errcode(ERRCODE_GROUPING_ERROR),
633  errmsg("aggregate function calls cannot be nested"),
634  parser_errposition(pstate, aggloc)));
635  }
636 
637  /*
638  * Now check for vars/aggs in the direct arguments, and throw error if
639  * needed. Note that we allow a Var of the agg's semantic level, but not
640  * an Agg of that level. In principle such Aggs could probably be
641  * supported, but it would create an ordering dependency among the
642  * aggregates at execution time. Since the case appears neither to be
643  * required by spec nor particularly useful, we just treat it as a
644  * nested-aggregate situation.
645  */
646  if (directargs)
647  {
648  context.min_varlevel = -1;
649  context.min_agglevel = -1;
650  (void) expression_tree_walker((Node *) directargs,
652  (void *) &context);
653  if (context.min_varlevel >= 0 && context.min_varlevel < agglevel)
654  ereport(ERROR,
655  (errcode(ERRCODE_GROUPING_ERROR),
656  errmsg("outer-level aggregate cannot contain a lower-level variable in its direct arguments"),
657  parser_errposition(pstate,
658  locate_var_of_level((Node *) directargs,
659  context.min_varlevel))));
660  if (context.min_agglevel >= 0 && context.min_agglevel <= agglevel)
661  ereport(ERROR,
662  (errcode(ERRCODE_GROUPING_ERROR),
663  errmsg("aggregate function calls cannot be nested"),
664  parser_errposition(pstate,
665  locate_agg_of_level((Node *) directargs,
666  context.min_agglevel))));
667  }
668  return agglevel;
669 }
670 
671 static bool
674 {
675  if (node == NULL)
676  return false;
677  if (IsA(node, Var))
678  {
679  int varlevelsup = ((Var *) node)->varlevelsup;
680 
681  /* convert levelsup to frame of reference of original query */
682  varlevelsup -= context->sublevels_up;
683  /* ignore local vars of subqueries */
684  if (varlevelsup >= 0)
685  {
686  if (context->min_varlevel < 0 ||
687  context->min_varlevel > varlevelsup)
688  context->min_varlevel = varlevelsup;
689  }
690  return false;
691  }
692  if (IsA(node, Aggref))
693  {
694  int agglevelsup = ((Aggref *) node)->agglevelsup;
695 
696  /* convert levelsup to frame of reference of original query */
697  agglevelsup -= context->sublevels_up;
698  /* ignore local aggs of subqueries */
699  if (agglevelsup >= 0)
700  {
701  if (context->min_agglevel < 0 ||
702  context->min_agglevel > agglevelsup)
703  context->min_agglevel = agglevelsup;
704  }
705  /* no need to examine args of the inner aggregate */
706  return false;
707  }
708  if (IsA(node, GroupingFunc))
709  {
710  int agglevelsup = ((GroupingFunc *) node)->agglevelsup;
711 
712  /* convert levelsup to frame of reference of original query */
713  agglevelsup -= context->sublevels_up;
714  /* ignore local aggs of subqueries */
715  if (agglevelsup >= 0)
716  {
717  if (context->min_agglevel < 0 ||
718  context->min_agglevel > agglevelsup)
719  context->min_agglevel = agglevelsup;
720  }
721  /* Continue and descend into subtree */
722  }
723 
724  /*
725  * SRFs and window functions can be rejected immediately, unless we are
726  * within a sub-select within the aggregate's arguments; in that case
727  * they're OK.
728  */
729  if (context->sublevels_up == 0)
730  {
731  if ((IsA(node, FuncExpr) &&((FuncExpr *) node)->funcretset) ||
732  (IsA(node, OpExpr) &&((OpExpr *) node)->opretset))
733  ereport(ERROR,
734  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
735  errmsg("aggregate function calls cannot contain set-returning function calls"),
736  errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
737  parser_errposition(context->pstate, exprLocation(node))));
738  if (IsA(node, WindowFunc))
739  ereport(ERROR,
740  (errcode(ERRCODE_GROUPING_ERROR),
741  errmsg("aggregate function calls cannot contain window function calls"),
742  parser_errposition(context->pstate,
743  ((WindowFunc *) node)->location)));
744  }
745  if (IsA(node, Query))
746  {
747  /* Recurse into subselects */
748  bool result;
749 
750  context->sublevels_up++;
751  result = query_tree_walker((Query *) node,
753  (void *) context,
754  0);
755  context->sublevels_up--;
756  return result;
757  }
758 
759  return expression_tree_walker(node,
761  (void *) context);
762 }
763 
764 /*
765  * transformWindowFuncCall -
766  * Finish initial transformation of a window function call
767  *
768  * parse_func.c has recognized the function as a window function, and has set
769  * up all the fields of the WindowFunc except winref. Here we must (1) add
770  * the WindowDef to the pstate (if not a duplicate of one already present) and
771  * set winref to link to it; and (2) mark p_hasWindowFuncs true in the pstate.
772  * Unlike aggregates, only the most closely nested pstate level need be
773  * considered --- there are no "outer window functions" per SQL spec.
774  */
775 void
777  WindowDef *windef)
778 {
779  const char *err;
780  bool errkind;
781 
782  /*
783  * A window function call can't contain another one (but aggs are OK). XXX
784  * is this required by spec, or just an unimplemented feature?
785  *
786  * Note: we don't need to check the filter expression here, because the
787  * context checks done below and in transformAggregateCall would have
788  * already rejected any window funcs or aggs within the filter.
789  */
790  if (pstate->p_hasWindowFuncs &&
791  contain_windowfuncs((Node *) wfunc->args))
792  ereport(ERROR,
793  (errcode(ERRCODE_WINDOWING_ERROR),
794  errmsg("window function calls cannot be nested"),
795  parser_errposition(pstate,
796  locate_windowfunc((Node *) wfunc->args))));
797 
798  /*
799  * Check to see if the window function is in an invalid place within the
800  * query.
801  *
802  * For brevity we support two schemes for reporting an error here: set
803  * "err" to a custom message, or set "errkind" true if the error context
804  * is sufficiently identified by what ParseExprKindName will return, *and*
805  * what it will return is just a SQL keyword. (Otherwise, use a custom
806  * message to avoid creating translation problems.)
807  */
808  err = NULL;
809  errkind = false;
810  switch (pstate->p_expr_kind)
811  {
812  case EXPR_KIND_NONE:
813  Assert(false); /* can't happen */
814  break;
815  case EXPR_KIND_OTHER:
816  /* Accept window func here; caller must throw error if wanted */
817  break;
818  case EXPR_KIND_JOIN_ON:
820  err = _("window functions are not allowed in JOIN conditions");
821  break;
823  /* can't get here, but just in case, throw an error */
824  errkind = true;
825  break;
827  err = _("window functions are not allowed in functions in FROM");
828  break;
829  case EXPR_KIND_WHERE:
830  errkind = true;
831  break;
832  case EXPR_KIND_POLICY:
833  err = _("window functions are not allowed in policy expressions");
834  break;
835  case EXPR_KIND_HAVING:
836  errkind = true;
837  break;
838  case EXPR_KIND_FILTER:
839  errkind = true;
840  break;
846  err = _("window functions are not allowed in window definitions");
847  break;
849  /* okay */
850  break;
854  errkind = true;
855  break;
856  case EXPR_KIND_GROUP_BY:
857  errkind = true;
858  break;
859  case EXPR_KIND_ORDER_BY:
860  /* okay */
861  break;
863  /* okay */
864  break;
865  case EXPR_KIND_LIMIT:
866  case EXPR_KIND_OFFSET:
867  errkind = true;
868  break;
869  case EXPR_KIND_RETURNING:
870  errkind = true;
871  break;
872  case EXPR_KIND_VALUES:
874  errkind = true;
875  break;
878  err = _("window functions are not allowed in check constraints");
879  break;
882  err = _("window functions are not allowed in DEFAULT expressions");
883  break;
885  err = _("window functions are not allowed in index expressions");
886  break;
888  err = _("window functions are not allowed in index predicates");
889  break;
891  err = _("window functions are not allowed in transform expressions");
892  break;
894  err = _("window functions are not allowed in EXECUTE parameters");
895  break;
897  err = _("window functions are not allowed in trigger WHEN conditions");
898  break;
900  err = _("window functions are not allowed in partition key expressions");
901  break;
903  err = _("window functions are not allowed in CALL arguments");
904  break;
905 
906  /*
907  * There is intentionally no default: case here, so that the
908  * compiler will warn if we add a new ParseExprKind without
909  * extending this switch. If we do see an unrecognized value at
910  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
911  * which is sane anyway.
912  */
913  }
914  if (err)
915  ereport(ERROR,
916  (errcode(ERRCODE_WINDOWING_ERROR),
917  errmsg_internal("%s", err),
918  parser_errposition(pstate, wfunc->location)));
919  if (errkind)
920  ereport(ERROR,
921  (errcode(ERRCODE_WINDOWING_ERROR),
922  /* translator: %s is name of a SQL construct, eg GROUP BY */
923  errmsg("window functions are not allowed in %s",
924  ParseExprKindName(pstate->p_expr_kind)),
925  parser_errposition(pstate, wfunc->location)));
926 
927  /*
928  * If the OVER clause just specifies a window name, find that WINDOW
929  * clause (which had better be present). Otherwise, try to match all the
930  * properties of the OVER clause, and make a new entry in the p_windowdefs
931  * list if no luck.
932  */
933  if (windef->name)
934  {
935  Index winref = 0;
936  ListCell *lc;
937 
938  Assert(windef->refname == NULL &&
939  windef->partitionClause == NIL &&
940  windef->orderClause == NIL &&
942 
943  foreach(lc, pstate->p_windowdefs)
944  {
945  WindowDef *refwin = (WindowDef *) lfirst(lc);
946 
947  winref++;
948  if (refwin->name && strcmp(refwin->name, windef->name) == 0)
949  {
950  wfunc->winref = winref;
951  break;
952  }
953  }
954  if (lc == NULL) /* didn't find it? */
955  ereport(ERROR,
956  (errcode(ERRCODE_UNDEFINED_OBJECT),
957  errmsg("window \"%s\" does not exist", windef->name),
958  parser_errposition(pstate, windef->location)));
959  }
960  else
961  {
962  Index winref = 0;
963  ListCell *lc;
964 
965  foreach(lc, pstate->p_windowdefs)
966  {
967  WindowDef *refwin = (WindowDef *) lfirst(lc);
968 
969  winref++;
970  if (refwin->refname && windef->refname &&
971  strcmp(refwin->refname, windef->refname) == 0)
972  /* matched on refname */ ;
973  else if (!refwin->refname && !windef->refname)
974  /* matched, no refname */ ;
975  else
976  continue;
977  if (equal(refwin->partitionClause, windef->partitionClause) &&
978  equal(refwin->orderClause, windef->orderClause) &&
979  refwin->frameOptions == windef->frameOptions &&
980  equal(refwin->startOffset, windef->startOffset) &&
981  equal(refwin->endOffset, windef->endOffset))
982  {
983  /* found a duplicate window specification */
984  wfunc->winref = winref;
985  break;
986  }
987  }
988  if (lc == NULL) /* didn't find it? */
989  {
990  pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
991  wfunc->winref = list_length(pstate->p_windowdefs);
992  }
993  }
994 
995  pstate->p_hasWindowFuncs = true;
996 }
997 
998 /*
999  * parseCheckAggregates
1000  * Check for aggregates where they shouldn't be and improper grouping.
1001  * This function should be called after the target list and qualifications
1002  * are finalized.
1003  *
1004  * Misplaced aggregates are now mostly detected in transformAggregateCall,
1005  * but it seems more robust to check for aggregates in recursive queries
1006  * only after everything is finalized. In any case it's hard to detect
1007  * improper grouping on-the-fly, so we have to make another pass over the
1008  * query for that.
1009  */
1010 void
1012 {
1013  List *gset_common = NIL;
1014  List *groupClauses = NIL;
1015  List *groupClauseCommonVars = NIL;
1016  bool have_non_var_grouping;
1017  List *func_grouped_rels = NIL;
1018  ListCell *l;
1019  bool hasJoinRTEs;
1020  bool hasSelfRefRTEs;
1021  PlannerInfo *root = NULL;
1022  Node *clause;
1023 
1024  /* This should only be called if we found aggregates or grouping */
1025  Assert(pstate->p_hasAggs || qry->groupClause || qry->havingQual || qry->groupingSets);
1026 
1027  /*
1028  * If we have grouping sets, expand them and find the intersection of all
1029  * sets.
1030  */
1031  if (qry->groupingSets)
1032  {
1033  /*
1034  * The limit of 4096 is arbitrary and exists simply to avoid resource
1035  * issues from pathological constructs.
1036  */
1037  List *gsets = expand_grouping_sets(qry->groupingSets, 4096);
1038 
1039  if (!gsets)
1040  ereport(ERROR,
1041  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
1042  errmsg("too many grouping sets present (maximum 4096)"),
1043  parser_errposition(pstate,
1044  qry->groupClause
1045  ? exprLocation((Node *) qry->groupClause)
1046  : exprLocation((Node *) qry->groupingSets))));
1047 
1048  /*
1049  * The intersection will often be empty, so help things along by
1050  * seeding the intersect with the smallest set.
1051  */
1052  gset_common = linitial(gsets);
1053 
1054  if (gset_common)
1055  {
1056  for_each_cell(l, lnext(list_head(gsets)))
1057  {
1058  gset_common = list_intersection_int(gset_common, lfirst(l));
1059  if (!gset_common)
1060  break;
1061  }
1062  }
1063 
1064  /*
1065  * If there was only one grouping set in the expansion, AND if the
1066  * groupClause is non-empty (meaning that the grouping set is not
1067  * empty either), then we can ditch the grouping set and pretend we
1068  * just had a normal GROUP BY.
1069  */
1070  if (list_length(gsets) == 1 && qry->groupClause)
1071  qry->groupingSets = NIL;
1072  }
1073 
1074  /*
1075  * Scan the range table to see if there are JOIN or self-reference CTE
1076  * entries. We'll need this info below.
1077  */
1078  hasJoinRTEs = hasSelfRefRTEs = false;
1079  foreach(l, pstate->p_rtable)
1080  {
1081  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
1082 
1083  if (rte->rtekind == RTE_JOIN)
1084  hasJoinRTEs = true;
1085  else if (rte->rtekind == RTE_CTE && rte->self_reference)
1086  hasSelfRefRTEs = true;
1087  }
1088 
1089  /*
1090  * Build a list of the acceptable GROUP BY expressions for use by
1091  * check_ungrouped_columns().
1092  *
1093  * We get the TLE, not just the expr, because GROUPING wants to know the
1094  * sortgroupref.
1095  */
1096  foreach(l, qry->groupClause)
1097  {
1098  SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
1099  TargetEntry *expr;
1100 
1101  expr = get_sortgroupclause_tle(grpcl, qry->targetList);
1102  if (expr == NULL)
1103  continue; /* probably cannot happen */
1104 
1105  groupClauses = lcons(expr, groupClauses);
1106  }
1107 
1108  /*
1109  * If there are join alias vars involved, we have to flatten them to the
1110  * underlying vars, so that aliased and unaliased vars will be correctly
1111  * taken as equal. We can skip the expense of doing this if no rangetable
1112  * entries are RTE_JOIN kind. We use the planner's flatten_join_alias_vars
1113  * routine to do the flattening; it wants a PlannerInfo root node, which
1114  * fortunately can be mostly dummy.
1115  */
1116  if (hasJoinRTEs)
1117  {
1118  root = makeNode(PlannerInfo);
1119  root->parse = qry;
1121  root->hasJoinRTEs = true;
1122 
1123  groupClauses = (List *) flatten_join_alias_vars(root,
1124  (Node *) groupClauses);
1125  }
1126 
1127  /*
1128  * Detect whether any of the grouping expressions aren't simple Vars; if
1129  * they're all Vars then we don't have to work so hard in the recursive
1130  * scans. (Note we have to flatten aliases before this.)
1131  *
1132  * Track Vars that are included in all grouping sets separately in
1133  * groupClauseCommonVars, since these are the only ones we can use to
1134  * check for functional dependencies.
1135  */
1136  have_non_var_grouping = false;
1137  foreach(l, groupClauses)
1138  {
1139  TargetEntry *tle = lfirst(l);
1140 
1141  if (!IsA(tle->expr, Var))
1142  {
1143  have_non_var_grouping = true;
1144  }
1145  else if (!qry->groupingSets ||
1146  list_member_int(gset_common, tle->ressortgroupref))
1147  {
1148  groupClauseCommonVars = lappend(groupClauseCommonVars, tle->expr);
1149  }
1150  }
1151 
1152  /*
1153  * Check the targetlist and HAVING clause for ungrouped variables.
1154  *
1155  * Note: because we check resjunk tlist elements as well as regular ones,
1156  * this will also find ungrouped variables that came from ORDER BY and
1157  * WINDOW clauses. For that matter, it's also going to examine the
1158  * grouping expressions themselves --- but they'll all pass the test ...
1159  *
1160  * We also finalize GROUPING expressions, but for that we need to traverse
1161  * the original (unflattened) clause in order to modify nodes.
1162  */
1163  clause = (Node *) qry->targetList;
1164  finalize_grouping_exprs(clause, pstate, qry,
1165  groupClauses, root,
1166  have_non_var_grouping);
1167  if (hasJoinRTEs)
1168  clause = flatten_join_alias_vars(root, clause);
1169  check_ungrouped_columns(clause, pstate, qry,
1170  groupClauses, groupClauseCommonVars,
1171  have_non_var_grouping,
1172  &func_grouped_rels);
1173 
1174  clause = (Node *) qry->havingQual;
1175  finalize_grouping_exprs(clause, pstate, qry,
1176  groupClauses, root,
1177  have_non_var_grouping);
1178  if (hasJoinRTEs)
1179  clause = flatten_join_alias_vars(root, clause);
1180  check_ungrouped_columns(clause, pstate, qry,
1181  groupClauses, groupClauseCommonVars,
1182  have_non_var_grouping,
1183  &func_grouped_rels);
1184 
1185  /*
1186  * Per spec, aggregates can't appear in a recursive term.
1187  */
1188  if (pstate->p_hasAggs && hasSelfRefRTEs)
1189  ereport(ERROR,
1190  (errcode(ERRCODE_INVALID_RECURSION),
1191  errmsg("aggregate functions are not allowed in a recursive query's recursive term"),
1192  parser_errposition(pstate,
1193  locate_agg_of_level((Node *) qry, 0))));
1194 }
1195 
1196 /*
1197  * check_ungrouped_columns -
1198  * Scan the given expression tree for ungrouped variables (variables
1199  * that are not listed in the groupClauses list and are not within
1200  * the arguments of aggregate functions). Emit a suitable error message
1201  * if any are found.
1202  *
1203  * NOTE: we assume that the given clause has been transformed suitably for
1204  * parser output. This means we can use expression_tree_walker.
1205  *
1206  * NOTE: we recognize grouping expressions in the main query, but only
1207  * grouping Vars in subqueries. For example, this will be rejected,
1208  * although it could be allowed:
1209  * SELECT
1210  * (SELECT x FROM bar where y = (foo.a + foo.b))
1211  * FROM foo
1212  * GROUP BY a + b;
1213  * The difficulty is the need to account for different sublevels_up.
1214  * This appears to require a whole custom version of equal(), which is
1215  * way more pain than the feature seems worth.
1216  */
1217 static void
1219  List *groupClauses, List *groupClauseCommonVars,
1220  bool have_non_var_grouping,
1221  List **func_grouped_rels)
1222 {
1224 
1225  context.pstate = pstate;
1226  context.qry = qry;
1227  context.root = NULL;
1228  context.groupClauses = groupClauses;
1229  context.groupClauseCommonVars = groupClauseCommonVars;
1230  context.have_non_var_grouping = have_non_var_grouping;
1231  context.func_grouped_rels = func_grouped_rels;
1232  context.sublevels_up = 0;
1233  context.in_agg_direct_args = false;
1234  check_ungrouped_columns_walker(node, &context);
1235 }
1236 
1237 static bool
1240 {
1241  ListCell *gl;
1242 
1243  if (node == NULL)
1244  return false;
1245  if (IsA(node, Const) ||
1246  IsA(node, Param))
1247  return false; /* constants are always acceptable */
1248 
1249  if (IsA(node, Aggref))
1250  {
1251  Aggref *agg = (Aggref *) node;
1252 
1253  if ((int) agg->agglevelsup == context->sublevels_up)
1254  {
1255  /*
1256  * If we find an aggregate call of the original level, do not
1257  * recurse into its normal arguments, ORDER BY arguments, or
1258  * filter; ungrouped vars there are not an error. But we should
1259  * check direct arguments as though they weren't in an aggregate.
1260  * We set a special flag in the context to help produce a useful
1261  * error message for ungrouped vars in direct arguments.
1262  */
1263  bool result;
1264 
1265  Assert(!context->in_agg_direct_args);
1266  context->in_agg_direct_args = true;
1268  context);
1269  context->in_agg_direct_args = false;
1270  return result;
1271  }
1272 
1273  /*
1274  * We can skip recursing into aggregates of higher levels altogether,
1275  * since they could not possibly contain Vars of concern to us (see
1276  * transformAggregateCall). We do need to look at aggregates of lower
1277  * levels, however.
1278  */
1279  if ((int) agg->agglevelsup > context->sublevels_up)
1280  return false;
1281  }
1282 
1283  if (IsA(node, GroupingFunc))
1284  {
1285  GroupingFunc *grp = (GroupingFunc *) node;
1286 
1287  /* handled GroupingFunc separately, no need to recheck at this level */
1288 
1289  if ((int) grp->agglevelsup >= context->sublevels_up)
1290  return false;
1291  }
1292 
1293  /*
1294  * If we have any GROUP BY items that are not simple Vars, check to see if
1295  * subexpression as a whole matches any GROUP BY item. We need to do this
1296  * at every recursion level so that we recognize GROUPed-BY expressions
1297  * before reaching variables within them. But this only works at the outer
1298  * query level, as noted above.
1299  */
1300  if (context->have_non_var_grouping && context->sublevels_up == 0)
1301  {
1302  foreach(gl, context->groupClauses)
1303  {
1304  TargetEntry *tle = lfirst(gl);
1305 
1306  if (equal(node, tle->expr))
1307  return false; /* acceptable, do not descend more */
1308  }
1309  }
1310 
1311  /*
1312  * If we have an ungrouped Var of the original query level, we have a
1313  * failure. Vars below the original query level are not a problem, and
1314  * neither are Vars from above it. (If such Vars are ungrouped as far as
1315  * their own query level is concerned, that's someone else's problem...)
1316  */
1317  if (IsA(node, Var))
1318  {
1319  Var *var = (Var *) node;
1320  RangeTblEntry *rte;
1321  char *attname;
1322 
1323  if (var->varlevelsup != context->sublevels_up)
1324  return false; /* it's not local to my query, ignore */
1325 
1326  /*
1327  * Check for a match, if we didn't do it above.
1328  */
1329  if (!context->have_non_var_grouping || context->sublevels_up != 0)
1330  {
1331  foreach(gl, context->groupClauses)
1332  {
1333  Var *gvar = (Var *) ((TargetEntry *) lfirst(gl))->expr;
1334 
1335  if (IsA(gvar, Var) &&
1336  gvar->varno == var->varno &&
1337  gvar->varattno == var->varattno &&
1338  gvar->varlevelsup == 0)
1339  return false; /* acceptable, we're okay */
1340  }
1341  }
1342 
1343  /*
1344  * Check whether the Var is known functionally dependent on the GROUP
1345  * BY columns. If so, we can allow the Var to be used, because the
1346  * grouping is really a no-op for this table. However, this deduction
1347  * depends on one or more constraints of the table, so we have to add
1348  * those constraints to the query's constraintDeps list, because it's
1349  * not semantically valid anymore if the constraint(s) get dropped.
1350  * (Therefore, this check must be the last-ditch effort before raising
1351  * error: we don't want to add dependencies unnecessarily.)
1352  *
1353  * Because this is a pretty expensive check, and will have the same
1354  * outcome for all columns of a table, we remember which RTEs we've
1355  * already proven functional dependency for in the func_grouped_rels
1356  * list. This test also prevents us from adding duplicate entries to
1357  * the constraintDeps list.
1358  */
1359  if (list_member_int(*context->func_grouped_rels, var->varno))
1360  return false; /* previously proven acceptable */
1361 
1362  Assert(var->varno > 0 &&
1363  (int) var->varno <= list_length(context->pstate->p_rtable));
1364  rte = rt_fetch(var->varno, context->pstate->p_rtable);
1365  if (rte->rtekind == RTE_RELATION)
1366  {
1368  var->varno,
1369  0,
1370  context->groupClauseCommonVars,
1371  &context->qry->constraintDeps))
1372  {
1373  *context->func_grouped_rels =
1374  lappend_int(*context->func_grouped_rels, var->varno);
1375  return false; /* acceptable */
1376  }
1377  }
1378 
1379  /* Found an ungrouped local variable; generate error message */
1380  attname = get_rte_attribute_name(rte, var->varattno);
1381  if (context->sublevels_up == 0)
1382  ereport(ERROR,
1383  (errcode(ERRCODE_GROUPING_ERROR),
1384  errmsg("column \"%s.%s\" must appear in the GROUP BY clause or be used in an aggregate function",
1385  rte->eref->aliasname, attname),
1386  context->in_agg_direct_args ?
1387  errdetail("Direct arguments of an ordered-set aggregate must use only grouped columns.") : 0,
1388  parser_errposition(context->pstate, var->location)));
1389  else
1390  ereport(ERROR,
1391  (errcode(ERRCODE_GROUPING_ERROR),
1392  errmsg("subquery uses ungrouped column \"%s.%s\" from outer query",
1393  rte->eref->aliasname, attname),
1394  parser_errposition(context->pstate, var->location)));
1395  }
1396 
1397  if (IsA(node, Query))
1398  {
1399  /* Recurse into subselects */
1400  bool result;
1401 
1402  context->sublevels_up++;
1403  result = query_tree_walker((Query *) node,
1405  (void *) context,
1406  0);
1407  context->sublevels_up--;
1408  return result;
1409  }
1411  (void *) context);
1412 }
1413 
1414 /*
1415  * finalize_grouping_exprs -
1416  * Scan the given expression tree for GROUPING() and related calls,
1417  * and validate and process their arguments.
1418  *
1419  * This is split out from check_ungrouped_columns above because it needs
1420  * to modify the nodes (which it does in-place, not via a mutator) while
1421  * check_ungrouped_columns may see only a copy of the original thanks to
1422  * flattening of join alias vars. So here, we flatten each individual
1423  * GROUPING argument as we see it before comparing it.
1424  */
1425 static void
1427  List *groupClauses, PlannerInfo *root,
1428  bool have_non_var_grouping)
1429 {
1431 
1432  context.pstate = pstate;
1433  context.qry = qry;
1434  context.root = root;
1435  context.groupClauses = groupClauses;
1436  context.groupClauseCommonVars = NIL;
1437  context.have_non_var_grouping = have_non_var_grouping;
1438  context.func_grouped_rels = NULL;
1439  context.sublevels_up = 0;
1440  context.in_agg_direct_args = false;
1441  finalize_grouping_exprs_walker(node, &context);
1442 }
1443 
1444 static bool
1447 {
1448  ListCell *gl;
1449 
1450  if (node == NULL)
1451  return false;
1452  if (IsA(node, Const) ||
1453  IsA(node, Param))
1454  return false; /* constants are always acceptable */
1455 
1456  if (IsA(node, Aggref))
1457  {
1458  Aggref *agg = (Aggref *) node;
1459 
1460  if ((int) agg->agglevelsup == context->sublevels_up)
1461  {
1462  /*
1463  * If we find an aggregate call of the original level, do not
1464  * recurse into its normal arguments, ORDER BY arguments, or
1465  * filter; GROUPING exprs of this level are not allowed there. But
1466  * check direct arguments as though they weren't in an aggregate.
1467  */
1468  bool result;
1469 
1470  Assert(!context->in_agg_direct_args);
1471  context->in_agg_direct_args = true;
1473  context);
1474  context->in_agg_direct_args = false;
1475  return result;
1476  }
1477 
1478  /*
1479  * We can skip recursing into aggregates of higher levels altogether,
1480  * since they could not possibly contain exprs of concern to us (see
1481  * transformAggregateCall). We do need to look at aggregates of lower
1482  * levels, however.
1483  */
1484  if ((int) agg->agglevelsup > context->sublevels_up)
1485  return false;
1486  }
1487 
1488  if (IsA(node, GroupingFunc))
1489  {
1490  GroupingFunc *grp = (GroupingFunc *) node;
1491 
1492  /*
1493  * We only need to check GroupingFunc nodes at the exact level to
1494  * which they belong, since they cannot mix levels in arguments.
1495  */
1496 
1497  if ((int) grp->agglevelsup == context->sublevels_up)
1498  {
1499  ListCell *lc;
1500  List *ref_list = NIL;
1501 
1502  foreach(lc, grp->args)
1503  {
1504  Node *expr = lfirst(lc);
1505  Index ref = 0;
1506 
1507  if (context->root)
1508  expr = flatten_join_alias_vars(context->root, expr);
1509 
1510  /*
1511  * Each expression must match a grouping entry at the current
1512  * query level. Unlike the general expression case, we don't
1513  * allow functional dependencies or outer references.
1514  */
1515 
1516  if (IsA(expr, Var))
1517  {
1518  Var *var = (Var *) expr;
1519 
1520  if (var->varlevelsup == context->sublevels_up)
1521  {
1522  foreach(gl, context->groupClauses)
1523  {
1524  TargetEntry *tle = lfirst(gl);
1525  Var *gvar = (Var *) tle->expr;
1526 
1527  if (IsA(gvar, Var) &&
1528  gvar->varno == var->varno &&
1529  gvar->varattno == var->varattno &&
1530  gvar->varlevelsup == 0)
1531  {
1532  ref = tle->ressortgroupref;
1533  break;
1534  }
1535  }
1536  }
1537  }
1538  else if (context->have_non_var_grouping &&
1539  context->sublevels_up == 0)
1540  {
1541  foreach(gl, context->groupClauses)
1542  {
1543  TargetEntry *tle = lfirst(gl);
1544 
1545  if (equal(expr, tle->expr))
1546  {
1547  ref = tle->ressortgroupref;
1548  break;
1549  }
1550  }
1551  }
1552 
1553  if (ref == 0)
1554  ereport(ERROR,
1555  (errcode(ERRCODE_GROUPING_ERROR),
1556  errmsg("arguments to GROUPING must be grouping expressions of the associated query level"),
1557  parser_errposition(context->pstate,
1558  exprLocation(expr))));
1559 
1560  ref_list = lappend_int(ref_list, ref);
1561  }
1562 
1563  grp->refs = ref_list;
1564  }
1565 
1566  if ((int) grp->agglevelsup > context->sublevels_up)
1567  return false;
1568  }
1569 
1570  if (IsA(node, Query))
1571  {
1572  /* Recurse into subselects */
1573  bool result;
1574 
1575  context->sublevels_up++;
1576  result = query_tree_walker((Query *) node,
1578  (void *) context,
1579  0);
1580  context->sublevels_up--;
1581  return result;
1582  }
1584  (void *) context);
1585 }
1586 
1587 
1588 /*
1589  * Given a GroupingSet node, expand it and return a list of lists.
1590  *
1591  * For EMPTY nodes, return a list of one empty list.
1592  *
1593  * For SIMPLE nodes, return a list of one list, which is the node content.
1594  *
1595  * For CUBE and ROLLUP nodes, return a list of the expansions.
1596  *
1597  * For SET nodes, recursively expand contained CUBE and ROLLUP.
1598  */
1599 static List *
1601 {
1602  List *result = NIL;
1603 
1604  switch (gs->kind)
1605  {
1606  case GROUPING_SET_EMPTY:
1607  result = list_make1(NIL);
1608  break;
1609 
1610  case GROUPING_SET_SIMPLE:
1611  result = list_make1(gs->content);
1612  break;
1613 
1614  case GROUPING_SET_ROLLUP:
1615  {
1616  List *rollup_val = gs->content;
1617  ListCell *lc;
1618  int curgroup_size = list_length(gs->content);
1619 
1620  while (curgroup_size > 0)
1621  {
1622  List *current_result = NIL;
1623  int i = curgroup_size;
1624 
1625  foreach(lc, rollup_val)
1626  {
1627  GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
1628 
1629  Assert(gs_current->kind == GROUPING_SET_SIMPLE);
1630 
1631  current_result
1632  = list_concat(current_result,
1633  list_copy(gs_current->content));
1634 
1635  /* If we are done with making the current group, break */
1636  if (--i == 0)
1637  break;
1638  }
1639 
1640  result = lappend(result, current_result);
1641  --curgroup_size;
1642  }
1643 
1644  result = lappend(result, NIL);
1645  }
1646  break;
1647 
1648  case GROUPING_SET_CUBE:
1649  {
1650  List *cube_list = gs->content;
1651  int number_bits = list_length(cube_list);
1652  uint32 num_sets;
1653  uint32 i;
1654 
1655  /* parser should cap this much lower */
1656  Assert(number_bits < 31);
1657 
1658  num_sets = (1U << number_bits);
1659 
1660  for (i = 0; i < num_sets; i++)
1661  {
1662  List *current_result = NIL;
1663  ListCell *lc;
1664  uint32 mask = 1U;
1665 
1666  foreach(lc, cube_list)
1667  {
1668  GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
1669 
1670  Assert(gs_current->kind == GROUPING_SET_SIMPLE);
1671 
1672  if (mask & i)
1673  {
1674  current_result
1675  = list_concat(current_result,
1676  list_copy(gs_current->content));
1677  }
1678 
1679  mask <<= 1;
1680  }
1681 
1682  result = lappend(result, current_result);
1683  }
1684  }
1685  break;
1686 
1687  case GROUPING_SET_SETS:
1688  {
1689  ListCell *lc;
1690 
1691  foreach(lc, gs->content)
1692  {
1693  List *current_result = expand_groupingset_node(lfirst(lc));
1694 
1695  result = list_concat(result, current_result);
1696  }
1697  }
1698  break;
1699  }
1700 
1701  return result;
1702 }
1703 
1704 static int
1705 cmp_list_len_asc(const void *a, const void *b)
1706 {
1707  int la = list_length(*(List *const *) a);
1708  int lb = list_length(*(List *const *) b);
1709 
1710  return (la > lb) ? 1 : (la == lb) ? 0 : -1;
1711 }
1712 
1713 /*
1714  * Expand a groupingSets clause to a flat list of grouping sets.
1715  * The returned list is sorted by length, shortest sets first.
1716  *
1717  * This is mainly for the planner, but we use it here too to do
1718  * some consistency checks.
1719  */
1720 List *
1721 expand_grouping_sets(List *groupingSets, int limit)
1722 {
1723  List *expanded_groups = NIL;
1724  List *result = NIL;
1725  double numsets = 1;
1726  ListCell *lc;
1727 
1728  if (groupingSets == NIL)
1729  return NIL;
1730 
1731  foreach(lc, groupingSets)
1732  {
1733  List *current_result = NIL;
1734  GroupingSet *gs = lfirst(lc);
1735 
1736  current_result = expand_groupingset_node(gs);
1737 
1738  Assert(current_result != NIL);
1739 
1740  numsets *= list_length(current_result);
1741 
1742  if (limit >= 0 && numsets > limit)
1743  return NIL;
1744 
1745  expanded_groups = lappend(expanded_groups, current_result);
1746  }
1747 
1748  /*
1749  * Do cartesian product between sublists of expanded_groups. While at it,
1750  * remove any duplicate elements from individual grouping sets (we must
1751  * NOT change the number of sets though)
1752  */
1753 
1754  foreach(lc, (List *) linitial(expanded_groups))
1755  {
1756  result = lappend(result, list_union_int(NIL, (List *) lfirst(lc)));
1757  }
1758 
1759  for_each_cell(lc, lnext(list_head(expanded_groups)))
1760  {
1761  List *p = lfirst(lc);
1762  List *new_result = NIL;
1763  ListCell *lc2;
1764 
1765  foreach(lc2, result)
1766  {
1767  List *q = lfirst(lc2);
1768  ListCell *lc3;
1769 
1770  foreach(lc3, p)
1771  {
1772  new_result = lappend(new_result,
1773  list_union_int(q, (List *) lfirst(lc3)));
1774  }
1775  }
1776  result = new_result;
1777  }
1778 
1779  if (list_length(result) > 1)
1780  {
1781  int result_len = list_length(result);
1782  List **buf = palloc(sizeof(List *) * result_len);
1783  List **ptr = buf;
1784 
1785  foreach(lc, result)
1786  {
1787  *ptr++ = lfirst(lc);
1788  }
1789 
1790  qsort(buf, result_len, sizeof(List *), cmp_list_len_asc);
1791 
1792  result = NIL;
1793  ptr = buf;
1794 
1795  while (result_len-- > 0)
1796  result = lappend(result, *ptr++);
1797 
1798  pfree(buf);
1799  }
1800 
1801  return result;
1802 }
1803 
1804 /*
1805  * get_aggregate_argtypes
1806  * Identify the specific datatypes passed to an aggregate call.
1807  *
1808  * Given an Aggref, extract the actual datatypes of the input arguments.
1809  * The input datatypes are reported in a way that matches up with the
1810  * aggregate's declaration, ie, any ORDER BY columns attached to a plain
1811  * aggregate are ignored, but we report both direct and aggregated args of
1812  * an ordered-set aggregate.
1813  *
1814  * Datatypes are returned into inputTypes[], which must reference an array
1815  * of length FUNC_MAX_ARGS.
1816  *
1817  * The function result is the number of actual arguments.
1818  */
1819 int
1820 get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
1821 {
1822  int numArguments = 0;
1823  ListCell *lc;
1824 
1826 
1827  foreach(lc, aggref->aggargtypes)
1828  {
1829  inputTypes[numArguments++] = lfirst_oid(lc);
1830  }
1831 
1832  return numArguments;
1833 }
1834 
1835 /*
1836  * resolve_aggregate_transtype
1837  * Identify the transition state value's datatype for an aggregate call.
1838  *
1839  * This function resolves a polymorphic aggregate's state datatype.
1840  * It must be passed the aggtranstype from the aggregate's catalog entry,
1841  * as well as the actual argument types extracted by get_aggregate_argtypes.
1842  * (We could fetch pg_aggregate.aggtranstype internally, but all existing
1843  * callers already have the value at hand, so we make them pass it.)
1844  */
1845 Oid
1847  Oid aggtranstype,
1848  Oid *inputTypes,
1849  int numArguments)
1850 {
1851  /* resolve actual type of transition state, if polymorphic */
1852  if (IsPolymorphicType(aggtranstype))
1853  {
1854  /* have to fetch the agg's declared input types... */
1855  Oid *declaredArgTypes;
1856  int agg_nargs;
1857 
1858  (void) get_func_signature(aggfuncid, &declaredArgTypes, &agg_nargs);
1859 
1860  /*
1861  * VARIADIC ANY aggs could have more actual than declared args, but
1862  * such extra args can't affect polymorphic type resolution.
1863  */
1864  Assert(agg_nargs <= numArguments);
1865 
1866  aggtranstype = enforce_generic_type_consistency(inputTypes,
1867  declaredArgTypes,
1868  agg_nargs,
1869  aggtranstype,
1870  false);
1871  pfree(declaredArgTypes);
1872  }
1873  return aggtranstype;
1874 }
1875 
1876 /*
1877  * Create an expression tree for the transition function of an aggregate.
1878  * This is needed so that polymorphic functions can be used within an
1879  * aggregate --- without the expression tree, such functions would not know
1880  * the datatypes they are supposed to use. (The trees will never actually
1881  * be executed, however, so we can skimp a bit on correctness.)
1882  *
1883  * agg_input_types and agg_state_type identifies the input types of the
1884  * aggregate. These should be resolved to actual types (ie, none should
1885  * ever be ANYELEMENT etc).
1886  * agg_input_collation is the aggregate function's input collation.
1887  *
1888  * For an ordered-set aggregate, remember that agg_input_types describes
1889  * the direct arguments followed by the aggregated arguments.
1890  *
1891  * transfn_oid and invtransfn_oid identify the funcs to be called; the
1892  * latter may be InvalidOid, however if invtransfn_oid is set then
1893  * transfn_oid must also be set.
1894  *
1895  * Pointers to the constructed trees are returned into *transfnexpr,
1896  * *invtransfnexpr. If there is no invtransfn, the respective pointer is set
1897  * to NULL. Since use of the invtransfn is optional, NULL may be passed for
1898  * invtransfnexpr.
1899  */
1900 void
1902  int agg_num_inputs,
1903  int agg_num_direct_inputs,
1904  bool agg_variadic,
1905  Oid agg_state_type,
1906  Oid agg_input_collation,
1907  Oid transfn_oid,
1908  Oid invtransfn_oid,
1909  Expr **transfnexpr,
1910  Expr **invtransfnexpr)
1911 {
1912  List *args;
1913  FuncExpr *fexpr;
1914  int i;
1915 
1916  /*
1917  * Build arg list to use in the transfn FuncExpr node.
1918  */
1919  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
1920 
1921  for (i = agg_num_direct_inputs; i < agg_num_inputs; i++)
1922  {
1923  args = lappend(args,
1924  make_agg_arg(agg_input_types[i], agg_input_collation));
1925  }
1926 
1927  fexpr = makeFuncExpr(transfn_oid,
1928  agg_state_type,
1929  args,
1930  InvalidOid,
1931  agg_input_collation,
1933  fexpr->funcvariadic = agg_variadic;
1934  *transfnexpr = (Expr *) fexpr;
1935 
1936  /*
1937  * Build invtransfn expression if requested, with same args as transfn
1938  */
1939  if (invtransfnexpr != NULL)
1940  {
1941  if (OidIsValid(invtransfn_oid))
1942  {
1943  fexpr = makeFuncExpr(invtransfn_oid,
1944  agg_state_type,
1945  args,
1946  InvalidOid,
1947  agg_input_collation,
1949  fexpr->funcvariadic = agg_variadic;
1950  *invtransfnexpr = (Expr *) fexpr;
1951  }
1952  else
1953  *invtransfnexpr = NULL;
1954  }
1955 }
1956 
1957 /*
1958  * Like build_aggregate_transfn_expr, but creates an expression tree for the
1959  * combine function of an aggregate, rather than the transition function.
1960  */
1961 void
1963  Oid agg_input_collation,
1964  Oid combinefn_oid,
1965  Expr **combinefnexpr)
1966 {
1967  Node *argp;
1968  List *args;
1969  FuncExpr *fexpr;
1970 
1971  /* combinefn takes two arguments of the aggregate state type */
1972  argp = make_agg_arg(agg_state_type, agg_input_collation);
1973 
1974  args = list_make2(argp, argp);
1975 
1976  fexpr = makeFuncExpr(combinefn_oid,
1977  agg_state_type,
1978  args,
1979  InvalidOid,
1980  agg_input_collation,
1982  /* combinefn is currently never treated as variadic */
1983  *combinefnexpr = (Expr *) fexpr;
1984 }
1985 
1986 /*
1987  * Like build_aggregate_transfn_expr, but creates an expression tree for the
1988  * serialization function of an aggregate.
1989  */
1990 void
1992  Expr **serialfnexpr)
1993 {
1994  List *args;
1995  FuncExpr *fexpr;
1996 
1997  /* serialfn always takes INTERNAL and returns BYTEA */
1998  args = list_make1(make_agg_arg(INTERNALOID, InvalidOid));
1999 
2000  fexpr = makeFuncExpr(serialfn_oid,
2001  BYTEAOID,
2002  args,
2003  InvalidOid,
2004  InvalidOid,
2006  *serialfnexpr = (Expr *) fexpr;
2007 }
2008 
2009 /*
2010  * Like build_aggregate_transfn_expr, but creates an expression tree for the
2011  * deserialization function of an aggregate.
2012  */
2013 void
2015  Expr **deserialfnexpr)
2016 {
2017  List *args;
2018  FuncExpr *fexpr;
2019 
2020  /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2021  args = list_make2(make_agg_arg(BYTEAOID, InvalidOid),
2022  make_agg_arg(INTERNALOID, InvalidOid));
2023 
2024  fexpr = makeFuncExpr(deserialfn_oid,
2025  INTERNALOID,
2026  args,
2027  InvalidOid,
2028  InvalidOid,
2030  *deserialfnexpr = (Expr *) fexpr;
2031 }
2032 
2033 /*
2034  * Like build_aggregate_transfn_expr, but creates an expression tree for the
2035  * final function of an aggregate, rather than the transition function.
2036  */
2037 void
2039  int num_finalfn_inputs,
2040  Oid agg_state_type,
2041  Oid agg_result_type,
2042  Oid agg_input_collation,
2043  Oid finalfn_oid,
2044  Expr **finalfnexpr)
2045 {
2046  List *args;
2047  int i;
2048 
2049  /*
2050  * Build expr tree for final function
2051  */
2052  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2053 
2054  /* finalfn may take additional args, which match agg's input types */
2055  for (i = 0; i < num_finalfn_inputs - 1; i++)
2056  {
2057  args = lappend(args,
2058  make_agg_arg(agg_input_types[i], agg_input_collation));
2059  }
2060 
2061  *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2062  agg_result_type,
2063  args,
2064  InvalidOid,
2065  agg_input_collation,
2067  /* finalfn is currently never treated as variadic */
2068 }
2069 
2070 /*
2071  * Convenience function to build dummy argument expressions for aggregates.
2072  *
2073  * We really only care that an aggregate support function can discover its
2074  * actual argument types at runtime using get_fn_expr_argtype(), so it's okay
2075  * to use Param nodes that don't correspond to any real Param.
2076  */
2077 static Node *
2078 make_agg_arg(Oid argtype, Oid argcollation)
2079 {
2080  Param *argp = makeNode(Param);
2081 
2082  argp->paramkind = PARAM_EXEC;
2083  argp->paramid = -1;
2084  argp->paramtype = argtype;
2085  argp->paramtypmod = -1;
2086  argp->paramcollid = argcollation;
2087  argp->location = -1;
2088  return (Node *) argp;
2089 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
List * aggdistinct
Definition: primnodes.h:304
bool check_functional_grouping(Oid relid, Index varno, Index varlevelsup, List *grouping_columns, List **constraintDeps)
List * partitionClause
Definition: parsenodes.h:490
static int cmp_list_len_asc(const void *a, const void *b)
Definition: parse_agg.c:1705
#define NIL
Definition: pg_list.h:69
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2078
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2256
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
Query * parse
Definition: relation.h:169
static bool check_ungrouped_columns_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1238
Index varlevelsup
Definition: primnodes.h:174
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:370
int errhint(const char *fmt,...)
Definition: elog.c:987
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:532
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
bool hasJoinRTEs
Definition: relation.h:315
List * args
Definition: primnodes.h:342
List * content
Definition: parsenodes.h:1277
List * refs
Definition: primnodes.h:344
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
List * args
Definition: primnodes.h:360
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2986
List * list_intersection_int(const List *list1, const List *list2)
Definition: list.c:826
int frameOptions
Definition: parsenodes.h:492
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
List * constraintDeps
Definition: parsenodes.h:168
char * name
Definition: parsenodes.h:488
#define Min(x, y)
Definition: c.h:857
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
List * list_truncate(List *list, int new_size)
Definition: list.c:350
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition: lsyscache.c:1485
List * groupingSets
Definition: parsenodes.h:150
ParamKind paramkind
Definition: primnodes.h:245
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:382
List * list_copy(const List *oldlist)
Definition: list.c:1160
Definition: nodes.h:517
int errcode(int sqlerrcode)
Definition: elog.c:575
List * args
Definition: primnodes.h:302
AttrNumber varattno
Definition: primnodes.h:169
bool p_hasAggs
Definition: parse_node.h:200
char * format_type_be(Oid type_oid)
Definition: format_type.c:328
List * list_concat(List *list1, List *list2)
Definition: list.c:321
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
void build_aggregate_deserialfn_expr(Oid deserialfn_oid, Expr **deserialfnexpr)
Definition: parse_agg.c:2014
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition: parse_agg.c:287
void build_aggregate_finalfn_expr(Oid *agg_input_types, int num_finalfn_inputs, Oid agg_state_type, Oid agg_result_type, Oid agg_input_collation, Oid finalfn_oid, Expr **finalfnexpr)
Definition: parse_agg.c:2038
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1203
unsigned int Oid
Definition: postgres_ext.h:31
Index winref
Definition: primnodes.h:362
Definition: primnodes.h:164
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:605
void parseCheckAggregates(ParseState *pstate, Query *qry)
Definition: parse_agg.c:1011
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3402
List * targetList
Definition: parsenodes.h:140
bool p_hasWindowFuncs
Definition: parse_node.h:201
GroupingSetKind kind
Definition: parsenodes.h:1276
#define FUNC_MAX_ARGS
#define list_make1(x1)
Definition: pg_list.h:139
List * aggargtypes
Definition: primnodes.h:300
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:437
Node * startOffset
Definition: parsenodes.h:493
void pfree(void *pointer)
Definition: mcxt.c:1031
static void check_ungrouped_columns(Node *node, ParseState *pstate, Query *qry, List *groupClauses, List *groupClauseVars, bool have_non_var_grouping, List **func_grouped_rels)
Definition: parse_agg.c:1218
#define linitial(l)
Definition: pg_list.h:111
static List * expand_groupingset_node(GroupingSet *gs)
Definition: parse_agg.c:1600
#define ERROR
Definition: elog.h:43
NameData attname
Definition: pg_attribute.h:40
static bool finalize_grouping_exprs_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1445
Oid paramcollid
Definition: primnodes.h:249
int location
Definition: primnodes.h:250
int location
Definition: parsenodes.h:495
List * p_windowdefs
Definition: parse_node.h:187
Oid enforce_generic_type_consistency(Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
Node * endOffset
Definition: parsenodes.h:494
int location
Definition: primnodes.h:312
static void finalize_grouping_exprs(Node *node, ParseState *pstate, Query *qry, List *groupClauses, PlannerInfo *root, bool have_non_var_grouping)
Definition: parse_agg.c:1426
bool list_member_int(const List *list, int datum)
Definition: list.c:485
int location
Definition: primnodes.h:179
static char * buf
Definition: pg_test_fsync.c:67
List * aggorder
Definition: primnodes.h:303
int errdetail(const char *fmt,...)
Definition: elog.c:873
Index agglevelsup
Definition: primnodes.h:310
int p_next_resno
Definition: parse_node.h:189
List * list_union_int(const List *list1, const List *list2)
Definition: list.c:744
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
unsigned int uint32
Definition: c.h:325
List * aggdirectargs
Definition: primnodes.h:301
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
void build_aggregate_combinefn_expr(Oid agg_state_type, Oid agg_input_collation, Oid combinefn_oid, Expr **combinefnexpr)
Definition: parse_agg.c:1962
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:237
List * lappend_int(List *list, int datum)
Definition: list.c:146
List * lappend(List *list, void *datum)
Definition: list.c:128
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:131
Index varno
Definition: primnodes.h:167
void transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc, WindowDef *windef)
Definition: parse_agg.c:776
struct ParseState * parentParseState
Definition: parse_node.h:172
List * orderClause
Definition: parsenodes.h:491
Node * flatten_join_alias_vars(PlannerInfo *root, Node *node)
Definition: var.c:670
Index agglevelsup
Definition: primnodes.h:346
bool self_reference
Definition: parsenodes.h:1034
Node * transformGroupingFunc(ParseState *pstate, GroupingFunc *p)
Definition: parse_agg.c:248
unsigned int Index
Definition: c.h:442
ParseExprKind p_expr_kind
Definition: parse_node.h:188
#define InvalidOid
Definition: postgres_ext.h:36
bool p_lateral_active
Definition: parse_node.h:180
char * get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
int32 paramtypmod
Definition: primnodes.h:248
List * lcons(void *datum, List *list)
Definition: list.c:259
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
#define makeNode(_type_)
Definition: nodes.h:565
int location
Definition: primnodes.h:365
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
char * aliasname
Definition: primnodes.h:43
void build_aggregate_serialfn_expr(Oid serialfn_oid, Expr **serialfnexpr)
Definition: parse_agg.c:1991
Expr * expr
Definition: primnodes.h:1376
int paramid
Definition: primnodes.h:246
void build_aggregate_transfn_expr(Oid *agg_input_types, int agg_num_inputs, int agg_num_direct_inputs, bool agg_variadic, Oid agg_state_type, Oid agg_input_collation, Oid transfn_oid, Oid invtransfn_oid, Expr **transfnexpr, Expr **invtransfnexpr)
Definition: parse_agg.c:1901
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Expr * aggfilter
Definition: primnodes.h:305
#define for_each_cell(cell, initcell)
Definition: pg_list.h:169
List * expand_grouping_sets(List *groupingSets, int limit)
Definition: parse_agg.c:1721
RTEKind rtekind
Definition: parsenodes.h:962
List * groupClause
Definition: parsenodes.h:148
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
Index ressortgroupref
Definition: primnodes.h:1379
void * arg
char aggkind
Definition: primnodes.h:309
MemoryContext planner_cxt
Definition: relation.h:302
Alias * eref
Definition: parsenodes.h:1066
#define qsort(a, b, c, d)
Definition: port.h:421
static int check_agg_arguments(ParseState *pstate, List *directargs, List *args, Expr *filter)
Definition: parse_agg.c:584
char * refname
Definition: parsenodes.h:489
List * transformDistinctClause(ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
Node * havingQual
Definition: parsenodes.h:152
int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
Definition: parse_agg.c:1820
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
#define _(x)
Definition: elog.c:84
static bool check_agg_arguments_walker(Node *node, check_agg_arguments_context *context)
Definition: parse_agg.c:672
Oid paramtype
Definition: primnodes.h:247
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197
bool funcvariadic
Definition: primnodes.h:453
#define lfirst_oid(lc)
Definition: pg_list.h:108
Oid resolve_aggregate_transtype(Oid aggfuncid, Oid aggtranstype, Oid *inputTypes, int numArguments)
Definition: parse_agg.c:1846
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:519
void transformAggregateCall(ParseState *pstate, Aggref *agg, List *args, List *aggorder, bool agg_distinct)
Definition: parse_agg.c:103
List * p_rtable
Definition: parse_node.h:174