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-2023, 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 "access/htup_details.h"
18 #include "catalog/pg_aggregate.h"
19 #include "catalog/pg_constraint.h"
20 #include "catalog/pg_type.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.h"
23 #include "optimizer/optimizer.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 #include "utils/syscache.h"
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 *groupClauseCommonVars,
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, bool hasJoinRTEs,
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;
439  if (isAgg)
440  err = _("aggregate functions are not allowed in MERGE WHEN conditions");
441  else
442  err = _("grouping operations are not allowed in MERGE WHEN conditions");
443 
444  break;
445  case EXPR_KIND_GROUP_BY:
446  errkind = true;
447  break;
448  case EXPR_KIND_ORDER_BY:
449  /* okay */
450  break;
452  /* okay */
453  break;
454  case EXPR_KIND_LIMIT:
455  case EXPR_KIND_OFFSET:
456  errkind = true;
457  break;
458  case EXPR_KIND_RETURNING:
459  errkind = true;
460  break;
461  case EXPR_KIND_VALUES:
463  errkind = true;
464  break;
467  if (isAgg)
468  err = _("aggregate functions are not allowed in check constraints");
469  else
470  err = _("grouping operations are not allowed in check constraints");
471 
472  break;
475 
476  if (isAgg)
477  err = _("aggregate functions are not allowed in DEFAULT expressions");
478  else
479  err = _("grouping operations are not allowed in DEFAULT expressions");
480 
481  break;
483  if (isAgg)
484  err = _("aggregate functions are not allowed in index expressions");
485  else
486  err = _("grouping operations are not allowed in index expressions");
487 
488  break;
490  if (isAgg)
491  err = _("aggregate functions are not allowed in index predicates");
492  else
493  err = _("grouping operations are not allowed in index predicates");
494 
495  break;
497  if (isAgg)
498  err = _("aggregate functions are not allowed in statistics expressions");
499  else
500  err = _("grouping operations are not allowed in statistics expressions");
501 
502  break;
504  if (isAgg)
505  err = _("aggregate functions are not allowed in transform expressions");
506  else
507  err = _("grouping operations are not allowed in transform expressions");
508 
509  break;
511  if (isAgg)
512  err = _("aggregate functions are not allowed in EXECUTE parameters");
513  else
514  err = _("grouping operations are not allowed in EXECUTE parameters");
515 
516  break;
518  if (isAgg)
519  err = _("aggregate functions are not allowed in trigger WHEN conditions");
520  else
521  err = _("grouping operations are not allowed in trigger WHEN conditions");
522 
523  break;
525  if (isAgg)
526  err = _("aggregate functions are not allowed in partition bound");
527  else
528  err = _("grouping operations are not allowed in partition bound");
529 
530  break;
532  if (isAgg)
533  err = _("aggregate functions are not allowed in partition key expressions");
534  else
535  err = _("grouping operations are not allowed in partition key expressions");
536 
537  break;
539 
540  if (isAgg)
541  err = _("aggregate functions are not allowed in column generation expressions");
542  else
543  err = _("grouping operations are not allowed in column generation expressions");
544 
545  break;
546 
548  if (isAgg)
549  err = _("aggregate functions are not allowed in CALL arguments");
550  else
551  err = _("grouping operations are not allowed in CALL arguments");
552 
553  break;
554 
556  if (isAgg)
557  err = _("aggregate functions are not allowed in COPY FROM WHERE conditions");
558  else
559  err = _("grouping operations are not allowed in COPY FROM WHERE conditions");
560 
561  break;
562 
564  errkind = true;
565  break;
566 
567  /*
568  * There is intentionally no default: case here, so that the
569  * compiler will warn if we add a new ParseExprKind without
570  * extending this switch. If we do see an unrecognized value at
571  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
572  * which is sane anyway.
573  */
574  }
575 
576  if (err)
577  ereport(ERROR,
578  (errcode(ERRCODE_GROUPING_ERROR),
579  errmsg_internal("%s", err),
580  parser_errposition(pstate, location)));
581 
582  if (errkind)
583  {
584  if (isAgg)
585  /* translator: %s is name of a SQL construct, eg GROUP BY */
586  err = _("aggregate functions are not allowed in %s");
587  else
588  /* translator: %s is name of a SQL construct, eg GROUP BY */
589  err = _("grouping operations are not allowed in %s");
590 
591  ereport(ERROR,
592  (errcode(ERRCODE_GROUPING_ERROR),
594  ParseExprKindName(pstate->p_expr_kind)),
595  parser_errposition(pstate, location)));
596  }
597 }
598 
599 /*
600  * check_agg_arguments
601  * Scan the arguments of an aggregate function to determine the
602  * aggregate's semantic level (zero is the current select's level,
603  * one is its parent, etc).
604  *
605  * The aggregate's level is the same as the level of the lowest-level variable
606  * or aggregate in its aggregated arguments (including any ORDER BY columns)
607  * or filter expression; or if it contains no variables at all, we presume it
608  * to be local.
609  *
610  * Vars/Aggs in direct arguments are *not* counted towards determining the
611  * agg's level, as those arguments aren't evaluated per-row but only
612  * per-group, and so in some sense aren't really agg arguments. However,
613  * this can mean that we decide an agg is upper-level even when its direct
614  * args contain lower-level Vars/Aggs, and that case has to be disallowed.
615  * (This is a little strange, but the SQL standard seems pretty definite that
616  * direct args are not to be considered when setting the agg's level.)
617  *
618  * We also take this opportunity to detect any aggregates or window functions
619  * nested within the arguments. We can throw error immediately if we find
620  * a window function. Aggregates are a bit trickier because it's only an
621  * error if the inner aggregate is of the same semantic level as the outer,
622  * which we can't know until we finish scanning the arguments.
623  */
624 static int
626  List *directargs,
627  List *args,
628  Expr *filter)
629 {
630  int agglevel;
632 
633  context.pstate = pstate;
634  context.min_varlevel = -1; /* signifies nothing found yet */
635  context.min_agglevel = -1;
636  context.sublevels_up = 0;
637 
638  (void) check_agg_arguments_walker((Node *) args, &context);
639  (void) check_agg_arguments_walker((Node *) filter, &context);
640 
641  /*
642  * If we found no vars nor aggs at all, it's a level-zero aggregate;
643  * otherwise, its level is the minimum of vars or aggs.
644  */
645  if (context.min_varlevel < 0)
646  {
647  if (context.min_agglevel < 0)
648  agglevel = 0;
649  else
650  agglevel = context.min_agglevel;
651  }
652  else if (context.min_agglevel < 0)
653  agglevel = context.min_varlevel;
654  else
655  agglevel = Min(context.min_varlevel, context.min_agglevel);
656 
657  /*
658  * If there's a nested aggregate of the same semantic level, complain.
659  */
660  if (agglevel == context.min_agglevel)
661  {
662  int aggloc;
663 
664  aggloc = locate_agg_of_level((Node *) args, agglevel);
665  if (aggloc < 0)
666  aggloc = locate_agg_of_level((Node *) filter, agglevel);
667  ereport(ERROR,
668  (errcode(ERRCODE_GROUPING_ERROR),
669  errmsg("aggregate function calls cannot be nested"),
670  parser_errposition(pstate, aggloc)));
671  }
672 
673  /*
674  * Now check for vars/aggs in the direct arguments, and throw error if
675  * needed. Note that we allow a Var of the agg's semantic level, but not
676  * an Agg of that level. In principle such Aggs could probably be
677  * supported, but it would create an ordering dependency among the
678  * aggregates at execution time. Since the case appears neither to be
679  * required by spec nor particularly useful, we just treat it as a
680  * nested-aggregate situation.
681  */
682  if (directargs)
683  {
684  context.min_varlevel = -1;
685  context.min_agglevel = -1;
686  (void) check_agg_arguments_walker((Node *) directargs, &context);
687  if (context.min_varlevel >= 0 && context.min_varlevel < agglevel)
688  ereport(ERROR,
689  (errcode(ERRCODE_GROUPING_ERROR),
690  errmsg("outer-level aggregate cannot contain a lower-level variable in its direct arguments"),
691  parser_errposition(pstate,
692  locate_var_of_level((Node *) directargs,
693  context.min_varlevel))));
694  if (context.min_agglevel >= 0 && context.min_agglevel <= agglevel)
695  ereport(ERROR,
696  (errcode(ERRCODE_GROUPING_ERROR),
697  errmsg("aggregate function calls cannot be nested"),
698  parser_errposition(pstate,
699  locate_agg_of_level((Node *) directargs,
700  context.min_agglevel))));
701  }
702  return agglevel;
703 }
704 
705 static bool
708 {
709  if (node == NULL)
710  return false;
711  if (IsA(node, Var))
712  {
713  int varlevelsup = ((Var *) node)->varlevelsup;
714 
715  /* convert levelsup to frame of reference of original query */
716  varlevelsup -= context->sublevels_up;
717  /* ignore local vars of subqueries */
718  if (varlevelsup >= 0)
719  {
720  if (context->min_varlevel < 0 ||
721  context->min_varlevel > varlevelsup)
722  context->min_varlevel = varlevelsup;
723  }
724  return false;
725  }
726  if (IsA(node, Aggref))
727  {
728  int agglevelsup = ((Aggref *) node)->agglevelsup;
729 
730  /* convert levelsup to frame of reference of original query */
731  agglevelsup -= context->sublevels_up;
732  /* ignore local aggs of subqueries */
733  if (agglevelsup >= 0)
734  {
735  if (context->min_agglevel < 0 ||
736  context->min_agglevel > agglevelsup)
737  context->min_agglevel = agglevelsup;
738  }
739  /* Continue and descend into subtree */
740  }
741  if (IsA(node, GroupingFunc))
742  {
743  int agglevelsup = ((GroupingFunc *) node)->agglevelsup;
744 
745  /* convert levelsup to frame of reference of original query */
746  agglevelsup -= context->sublevels_up;
747  /* ignore local aggs of subqueries */
748  if (agglevelsup >= 0)
749  {
750  if (context->min_agglevel < 0 ||
751  context->min_agglevel > agglevelsup)
752  context->min_agglevel = agglevelsup;
753  }
754  /* Continue and descend into subtree */
755  }
756 
757  /*
758  * SRFs and window functions can be rejected immediately, unless we are
759  * within a sub-select within the aggregate's arguments; in that case
760  * they're OK.
761  */
762  if (context->sublevels_up == 0)
763  {
764  if ((IsA(node, FuncExpr) && ((FuncExpr *) node)->funcretset) ||
765  (IsA(node, OpExpr) && ((OpExpr *) node)->opretset))
766  ereport(ERROR,
767  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
768  errmsg("aggregate function calls cannot contain set-returning function calls"),
769  errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
770  parser_errposition(context->pstate, exprLocation(node))));
771  if (IsA(node, WindowFunc))
772  ereport(ERROR,
773  (errcode(ERRCODE_GROUPING_ERROR),
774  errmsg("aggregate function calls cannot contain window function calls"),
775  parser_errposition(context->pstate,
776  ((WindowFunc *) node)->location)));
777  }
778  if (IsA(node, Query))
779  {
780  /* Recurse into subselects */
781  bool result;
782 
783  context->sublevels_up++;
784  result = query_tree_walker((Query *) node,
786  (void *) context,
787  0);
788  context->sublevels_up--;
789  return result;
790  }
791 
792  return expression_tree_walker(node,
794  (void *) context);
795 }
796 
797 /*
798  * transformWindowFuncCall -
799  * Finish initial transformation of a window function call
800  *
801  * parse_func.c has recognized the function as a window function, and has set
802  * up all the fields of the WindowFunc except winref. Here we must (1) add
803  * the WindowDef to the pstate (if not a duplicate of one already present) and
804  * set winref to link to it; and (2) mark p_hasWindowFuncs true in the pstate.
805  * Unlike aggregates, only the most closely nested pstate level need be
806  * considered --- there are no "outer window functions" per SQL spec.
807  */
808 void
810  WindowDef *windef)
811 {
812  const char *err;
813  bool errkind;
814 
815  /*
816  * A window function call can't contain another one (but aggs are OK). XXX
817  * is this required by spec, or just an unimplemented feature?
818  *
819  * Note: we don't need to check the filter expression here, because the
820  * context checks done below and in transformAggregateCall would have
821  * already rejected any window funcs or aggs within the filter.
822  */
823  if (pstate->p_hasWindowFuncs &&
824  contain_windowfuncs((Node *) wfunc->args))
825  ereport(ERROR,
826  (errcode(ERRCODE_WINDOWING_ERROR),
827  errmsg("window function calls cannot be nested"),
828  parser_errposition(pstate,
829  locate_windowfunc((Node *) wfunc->args))));
830 
831  /*
832  * Check to see if the window function is in an invalid place within the
833  * query.
834  *
835  * For brevity we support two schemes for reporting an error here: set
836  * "err" to a custom message, or set "errkind" true if the error context
837  * is sufficiently identified by what ParseExprKindName will return, *and*
838  * what it will return is just a SQL keyword. (Otherwise, use a custom
839  * message to avoid creating translation problems.)
840  */
841  err = NULL;
842  errkind = false;
843  switch (pstate->p_expr_kind)
844  {
845  case EXPR_KIND_NONE:
846  Assert(false); /* can't happen */
847  break;
848  case EXPR_KIND_OTHER:
849  /* Accept window func here; caller must throw error if wanted */
850  break;
851  case EXPR_KIND_JOIN_ON:
853  err = _("window functions are not allowed in JOIN conditions");
854  break;
856  /* can't get here, but just in case, throw an error */
857  errkind = true;
858  break;
860  err = _("window functions are not allowed in functions in FROM");
861  break;
862  case EXPR_KIND_WHERE:
863  errkind = true;
864  break;
865  case EXPR_KIND_POLICY:
866  err = _("window functions are not allowed in policy expressions");
867  break;
868  case EXPR_KIND_HAVING:
869  errkind = true;
870  break;
871  case EXPR_KIND_FILTER:
872  errkind = true;
873  break;
879  err = _("window functions are not allowed in window definitions");
880  break;
882  /* okay */
883  break;
887  errkind = true;
888  break;
890  err = _("window functions are not allowed in MERGE WHEN conditions");
891  break;
892  case EXPR_KIND_GROUP_BY:
893  errkind = true;
894  break;
895  case EXPR_KIND_ORDER_BY:
896  /* okay */
897  break;
899  /* okay */
900  break;
901  case EXPR_KIND_LIMIT:
902  case EXPR_KIND_OFFSET:
903  errkind = true;
904  break;
905  case EXPR_KIND_RETURNING:
906  errkind = true;
907  break;
908  case EXPR_KIND_VALUES:
910  errkind = true;
911  break;
914  err = _("window functions are not allowed in check constraints");
915  break;
918  err = _("window functions are not allowed in DEFAULT expressions");
919  break;
921  err = _("window functions are not allowed in index expressions");
922  break;
924  err = _("window functions are not allowed in statistics expressions");
925  break;
927  err = _("window functions are not allowed in index predicates");
928  break;
930  err = _("window functions are not allowed in transform expressions");
931  break;
933  err = _("window functions are not allowed in EXECUTE parameters");
934  break;
936  err = _("window functions are not allowed in trigger WHEN conditions");
937  break;
939  err = _("window functions are not allowed in partition bound");
940  break;
942  err = _("window functions are not allowed in partition key expressions");
943  break;
945  err = _("window functions are not allowed in CALL arguments");
946  break;
948  err = _("window functions are not allowed in COPY FROM WHERE conditions");
949  break;
951  err = _("window functions are not allowed in column generation expressions");
952  break;
954  errkind = true;
955  break;
956 
957  /*
958  * There is intentionally no default: case here, so that the
959  * compiler will warn if we add a new ParseExprKind without
960  * extending this switch. If we do see an unrecognized value at
961  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
962  * which is sane anyway.
963  */
964  }
965  if (err)
966  ereport(ERROR,
967  (errcode(ERRCODE_WINDOWING_ERROR),
968  errmsg_internal("%s", err),
969  parser_errposition(pstate, wfunc->location)));
970  if (errkind)
971  ereport(ERROR,
972  (errcode(ERRCODE_WINDOWING_ERROR),
973  /* translator: %s is name of a SQL construct, eg GROUP BY */
974  errmsg("window functions are not allowed in %s",
975  ParseExprKindName(pstate->p_expr_kind)),
976  parser_errposition(pstate, wfunc->location)));
977 
978  /*
979  * If the OVER clause just specifies a window name, find that WINDOW
980  * clause (which had better be present). Otherwise, try to match all the
981  * properties of the OVER clause, and make a new entry in the p_windowdefs
982  * list if no luck.
983  */
984  if (windef->name)
985  {
986  Index winref = 0;
987  ListCell *lc;
988 
989  Assert(windef->refname == NULL &&
990  windef->partitionClause == NIL &&
991  windef->orderClause == NIL &&
993 
994  foreach(lc, pstate->p_windowdefs)
995  {
996  WindowDef *refwin = (WindowDef *) lfirst(lc);
997 
998  winref++;
999  if (refwin->name && strcmp(refwin->name, windef->name) == 0)
1000  {
1001  wfunc->winref = winref;
1002  break;
1003  }
1004  }
1005  if (lc == NULL) /* didn't find it? */
1006  ereport(ERROR,
1007  (errcode(ERRCODE_UNDEFINED_OBJECT),
1008  errmsg("window \"%s\" does not exist", windef->name),
1009  parser_errposition(pstate, windef->location)));
1010  }
1011  else
1012  {
1013  Index winref = 0;
1014  ListCell *lc;
1015 
1016  foreach(lc, pstate->p_windowdefs)
1017  {
1018  WindowDef *refwin = (WindowDef *) lfirst(lc);
1019 
1020  winref++;
1021  if (refwin->refname && windef->refname &&
1022  strcmp(refwin->refname, windef->refname) == 0)
1023  /* matched on refname */ ;
1024  else if (!refwin->refname && !windef->refname)
1025  /* matched, no refname */ ;
1026  else
1027  continue;
1028 
1029  /*
1030  * Also see similar de-duplication code in optimize_window_clauses
1031  */
1032  if (equal(refwin->partitionClause, windef->partitionClause) &&
1033  equal(refwin->orderClause, windef->orderClause) &&
1034  refwin->frameOptions == windef->frameOptions &&
1035  equal(refwin->startOffset, windef->startOffset) &&
1036  equal(refwin->endOffset, windef->endOffset))
1037  {
1038  /* found a duplicate window specification */
1039  wfunc->winref = winref;
1040  break;
1041  }
1042  }
1043  if (lc == NULL) /* didn't find it? */
1044  {
1045  pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
1046  wfunc->winref = list_length(pstate->p_windowdefs);
1047  }
1048  }
1049 
1050  pstate->p_hasWindowFuncs = true;
1051 }
1052 
1053 /*
1054  * parseCheckAggregates
1055  * Check for aggregates where they shouldn't be and improper grouping.
1056  * This function should be called after the target list and qualifications
1057  * are finalized.
1058  *
1059  * Misplaced aggregates are now mostly detected in transformAggregateCall,
1060  * but it seems more robust to check for aggregates in recursive queries
1061  * only after everything is finalized. In any case it's hard to detect
1062  * improper grouping on-the-fly, so we have to make another pass over the
1063  * query for that.
1064  */
1065 void
1067 {
1068  List *gset_common = NIL;
1069  List *groupClauses = NIL;
1070  List *groupClauseCommonVars = NIL;
1071  bool have_non_var_grouping;
1072  List *func_grouped_rels = NIL;
1073  ListCell *l;
1074  bool hasJoinRTEs;
1075  bool hasSelfRefRTEs;
1076  Node *clause;
1077 
1078  /* This should only be called if we found aggregates or grouping */
1079  Assert(pstate->p_hasAggs || qry->groupClause || qry->havingQual || qry->groupingSets);
1080 
1081  /*
1082  * If we have grouping sets, expand them and find the intersection of all
1083  * sets.
1084  */
1085  if (qry->groupingSets)
1086  {
1087  /*
1088  * The limit of 4096 is arbitrary and exists simply to avoid resource
1089  * issues from pathological constructs.
1090  */
1091  List *gsets = expand_grouping_sets(qry->groupingSets, qry->groupDistinct, 4096);
1092 
1093  if (!gsets)
1094  ereport(ERROR,
1095  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
1096  errmsg("too many grouping sets present (maximum 4096)"),
1097  parser_errposition(pstate,
1098  qry->groupClause
1099  ? exprLocation((Node *) qry->groupClause)
1100  : exprLocation((Node *) qry->groupingSets))));
1101 
1102  /*
1103  * The intersection will often be empty, so help things along by
1104  * seeding the intersect with the smallest set.
1105  */
1106  gset_common = linitial(gsets);
1107 
1108  if (gset_common)
1109  {
1110  for_each_from(l, gsets, 1)
1111  {
1112  gset_common = list_intersection_int(gset_common, lfirst(l));
1113  if (!gset_common)
1114  break;
1115  }
1116  }
1117 
1118  /*
1119  * If there was only one grouping set in the expansion, AND if the
1120  * groupClause is non-empty (meaning that the grouping set is not
1121  * empty either), then we can ditch the grouping set and pretend we
1122  * just had a normal GROUP BY.
1123  */
1124  if (list_length(gsets) == 1 && qry->groupClause)
1125  qry->groupingSets = NIL;
1126  }
1127 
1128  /*
1129  * Scan the range table to see if there are JOIN or self-reference CTE
1130  * entries. We'll need this info below.
1131  */
1132  hasJoinRTEs = hasSelfRefRTEs = false;
1133  foreach(l, pstate->p_rtable)
1134  {
1135  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
1136 
1137  if (rte->rtekind == RTE_JOIN)
1138  hasJoinRTEs = true;
1139  else if (rte->rtekind == RTE_CTE && rte->self_reference)
1140  hasSelfRefRTEs = true;
1141  }
1142 
1143  /*
1144  * Build a list of the acceptable GROUP BY expressions for use by
1145  * check_ungrouped_columns().
1146  *
1147  * We get the TLE, not just the expr, because GROUPING wants to know the
1148  * sortgroupref.
1149  */
1150  foreach(l, qry->groupClause)
1151  {
1152  SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
1153  TargetEntry *expr;
1154 
1155  expr = get_sortgroupclause_tle(grpcl, qry->targetList);
1156  if (expr == NULL)
1157  continue; /* probably cannot happen */
1158 
1159  groupClauses = lappend(groupClauses, expr);
1160  }
1161 
1162  /*
1163  * If there are join alias vars involved, we have to flatten them to the
1164  * underlying vars, so that aliased and unaliased vars will be correctly
1165  * taken as equal. We can skip the expense of doing this if no rangetable
1166  * entries are RTE_JOIN kind.
1167  */
1168  if (hasJoinRTEs)
1169  groupClauses = (List *) flatten_join_alias_vars(NULL, qry,
1170  (Node *) groupClauses);
1171 
1172  /*
1173  * Detect whether any of the grouping expressions aren't simple Vars; if
1174  * they're all Vars then we don't have to work so hard in the recursive
1175  * scans. (Note we have to flatten aliases before this.)
1176  *
1177  * Track Vars that are included in all grouping sets separately in
1178  * groupClauseCommonVars, since these are the only ones we can use to
1179  * check for functional dependencies.
1180  */
1181  have_non_var_grouping = false;
1182  foreach(l, groupClauses)
1183  {
1184  TargetEntry *tle = lfirst(l);
1185 
1186  if (!IsA(tle->expr, Var))
1187  {
1188  have_non_var_grouping = true;
1189  }
1190  else if (!qry->groupingSets ||
1191  list_member_int(gset_common, tle->ressortgroupref))
1192  {
1193  groupClauseCommonVars = lappend(groupClauseCommonVars, tle->expr);
1194  }
1195  }
1196 
1197  /*
1198  * Check the targetlist and HAVING clause for ungrouped variables.
1199  *
1200  * Note: because we check resjunk tlist elements as well as regular ones,
1201  * this will also find ungrouped variables that came from ORDER BY and
1202  * WINDOW clauses. For that matter, it's also going to examine the
1203  * grouping expressions themselves --- but they'll all pass the test ...
1204  *
1205  * We also finalize GROUPING expressions, but for that we need to traverse
1206  * the original (unflattened) clause in order to modify nodes.
1207  */
1208  clause = (Node *) qry->targetList;
1209  finalize_grouping_exprs(clause, pstate, qry,
1210  groupClauses, hasJoinRTEs,
1211  have_non_var_grouping);
1212  if (hasJoinRTEs)
1213  clause = flatten_join_alias_vars(NULL, qry, clause);
1214  check_ungrouped_columns(clause, pstate, qry,
1215  groupClauses, groupClauseCommonVars,
1216  have_non_var_grouping,
1217  &func_grouped_rels);
1218 
1219  clause = (Node *) qry->havingQual;
1220  finalize_grouping_exprs(clause, pstate, qry,
1221  groupClauses, hasJoinRTEs,
1222  have_non_var_grouping);
1223  if (hasJoinRTEs)
1224  clause = flatten_join_alias_vars(NULL, qry, clause);
1225  check_ungrouped_columns(clause, pstate, qry,
1226  groupClauses, groupClauseCommonVars,
1227  have_non_var_grouping,
1228  &func_grouped_rels);
1229 
1230  /*
1231  * Per spec, aggregates can't appear in a recursive term.
1232  */
1233  if (pstate->p_hasAggs && hasSelfRefRTEs)
1234  ereport(ERROR,
1235  (errcode(ERRCODE_INVALID_RECURSION),
1236  errmsg("aggregate functions are not allowed in a recursive query's recursive term"),
1237  parser_errposition(pstate,
1238  locate_agg_of_level((Node *) qry, 0))));
1239 }
1240 
1241 /*
1242  * check_ungrouped_columns -
1243  * Scan the given expression tree for ungrouped variables (variables
1244  * that are not listed in the groupClauses list and are not within
1245  * the arguments of aggregate functions). Emit a suitable error message
1246  * if any are found.
1247  *
1248  * NOTE: we assume that the given clause has been transformed suitably for
1249  * parser output. This means we can use expression_tree_walker.
1250  *
1251  * NOTE: we recognize grouping expressions in the main query, but only
1252  * grouping Vars in subqueries. For example, this will be rejected,
1253  * although it could be allowed:
1254  * SELECT
1255  * (SELECT x FROM bar where y = (foo.a + foo.b))
1256  * FROM foo
1257  * GROUP BY a + b;
1258  * The difficulty is the need to account for different sublevels_up.
1259  * This appears to require a whole custom version of equal(), which is
1260  * way more pain than the feature seems worth.
1261  */
1262 static void
1264  List *groupClauses, List *groupClauseCommonVars,
1265  bool have_non_var_grouping,
1266  List **func_grouped_rels)
1267 {
1269 
1270  context.pstate = pstate;
1271  context.qry = qry;
1272  context.hasJoinRTEs = false; /* assume caller flattened join Vars */
1273  context.groupClauses = groupClauses;
1274  context.groupClauseCommonVars = groupClauseCommonVars;
1275  context.have_non_var_grouping = have_non_var_grouping;
1276  context.func_grouped_rels = func_grouped_rels;
1277  context.sublevels_up = 0;
1278  context.in_agg_direct_args = false;
1279  check_ungrouped_columns_walker(node, &context);
1280 }
1281 
1282 static bool
1285 {
1286  ListCell *gl;
1287 
1288  if (node == NULL)
1289  return false;
1290  if (IsA(node, Const) ||
1291  IsA(node, Param))
1292  return false; /* constants are always acceptable */
1293 
1294  if (IsA(node, Aggref))
1295  {
1296  Aggref *agg = (Aggref *) node;
1297 
1298  if ((int) agg->agglevelsup == context->sublevels_up)
1299  {
1300  /*
1301  * If we find an aggregate call of the original level, do not
1302  * recurse into its normal arguments, ORDER BY arguments, or
1303  * filter; ungrouped vars there are not an error. But we should
1304  * check direct arguments as though they weren't in an aggregate.
1305  * We set a special flag in the context to help produce a useful
1306  * error message for ungrouped vars in direct arguments.
1307  */
1308  bool result;
1309 
1310  Assert(!context->in_agg_direct_args);
1311  context->in_agg_direct_args = true;
1313  context);
1314  context->in_agg_direct_args = false;
1315  return result;
1316  }
1317 
1318  /*
1319  * We can skip recursing into aggregates of higher levels altogether,
1320  * since they could not possibly contain Vars of concern to us (see
1321  * transformAggregateCall). We do need to look at aggregates of lower
1322  * levels, however.
1323  */
1324  if ((int) agg->agglevelsup > context->sublevels_up)
1325  return false;
1326  }
1327 
1328  if (IsA(node, GroupingFunc))
1329  {
1330  GroupingFunc *grp = (GroupingFunc *) node;
1331 
1332  /* handled GroupingFunc separately, no need to recheck at this level */
1333 
1334  if ((int) grp->agglevelsup >= context->sublevels_up)
1335  return false;
1336  }
1337 
1338  /*
1339  * If we have any GROUP BY items that are not simple Vars, check to see if
1340  * subexpression as a whole matches any GROUP BY item. We need to do this
1341  * at every recursion level so that we recognize GROUPed-BY expressions
1342  * before reaching variables within them. But this only works at the outer
1343  * query level, as noted above.
1344  */
1345  if (context->have_non_var_grouping && context->sublevels_up == 0)
1346  {
1347  foreach(gl, context->groupClauses)
1348  {
1349  TargetEntry *tle = lfirst(gl);
1350 
1351  if (equal(node, tle->expr))
1352  return false; /* acceptable, do not descend more */
1353  }
1354  }
1355 
1356  /*
1357  * If we have an ungrouped Var of the original query level, we have a
1358  * failure. Vars below the original query level are not a problem, and
1359  * neither are Vars from above it. (If such Vars are ungrouped as far as
1360  * their own query level is concerned, that's someone else's problem...)
1361  */
1362  if (IsA(node, Var))
1363  {
1364  Var *var = (Var *) node;
1365  RangeTblEntry *rte;
1366  char *attname;
1367 
1368  if (var->varlevelsup != context->sublevels_up)
1369  return false; /* it's not local to my query, ignore */
1370 
1371  /*
1372  * Check for a match, if we didn't do it above.
1373  */
1374  if (!context->have_non_var_grouping || context->sublevels_up != 0)
1375  {
1376  foreach(gl, context->groupClauses)
1377  {
1378  Var *gvar = (Var *) ((TargetEntry *) lfirst(gl))->expr;
1379 
1380  if (IsA(gvar, Var) &&
1381  gvar->varno == var->varno &&
1382  gvar->varattno == var->varattno &&
1383  gvar->varlevelsup == 0)
1384  return false; /* acceptable, we're okay */
1385  }
1386  }
1387 
1388  /*
1389  * Check whether the Var is known functionally dependent on the GROUP
1390  * BY columns. If so, we can allow the Var to be used, because the
1391  * grouping is really a no-op for this table. However, this deduction
1392  * depends on one or more constraints of the table, so we have to add
1393  * those constraints to the query's constraintDeps list, because it's
1394  * not semantically valid anymore if the constraint(s) get dropped.
1395  * (Therefore, this check must be the last-ditch effort before raising
1396  * error: we don't want to add dependencies unnecessarily.)
1397  *
1398  * Because this is a pretty expensive check, and will have the same
1399  * outcome for all columns of a table, we remember which RTEs we've
1400  * already proven functional dependency for in the func_grouped_rels
1401  * list. This test also prevents us from adding duplicate entries to
1402  * the constraintDeps list.
1403  */
1404  if (list_member_int(*context->func_grouped_rels, var->varno))
1405  return false; /* previously proven acceptable */
1406 
1407  Assert(var->varno > 0 &&
1408  (int) var->varno <= list_length(context->pstate->p_rtable));
1409  rte = rt_fetch(var->varno, context->pstate->p_rtable);
1410  if (rte->rtekind == RTE_RELATION)
1411  {
1413  var->varno,
1414  0,
1415  context->groupClauseCommonVars,
1416  &context->qry->constraintDeps))
1417  {
1418  *context->func_grouped_rels =
1419  lappend_int(*context->func_grouped_rels, var->varno);
1420  return false; /* acceptable */
1421  }
1422  }
1423 
1424  /* Found an ungrouped local variable; generate error message */
1426  if (context->sublevels_up == 0)
1427  ereport(ERROR,
1428  (errcode(ERRCODE_GROUPING_ERROR),
1429  errmsg("column \"%s.%s\" must appear in the GROUP BY clause or be used in an aggregate function",
1430  rte->eref->aliasname, attname),
1431  context->in_agg_direct_args ?
1432  errdetail("Direct arguments of an ordered-set aggregate must use only grouped columns.") : 0,
1433  parser_errposition(context->pstate, var->location)));
1434  else
1435  ereport(ERROR,
1436  (errcode(ERRCODE_GROUPING_ERROR),
1437  errmsg("subquery uses ungrouped column \"%s.%s\" from outer query",
1438  rte->eref->aliasname, attname),
1439  parser_errposition(context->pstate, var->location)));
1440  }
1441 
1442  if (IsA(node, Query))
1443  {
1444  /* Recurse into subselects */
1445  bool result;
1446 
1447  context->sublevels_up++;
1448  result = query_tree_walker((Query *) node,
1450  (void *) context,
1451  0);
1452  context->sublevels_up--;
1453  return result;
1454  }
1456  (void *) context);
1457 }
1458 
1459 /*
1460  * finalize_grouping_exprs -
1461  * Scan the given expression tree for GROUPING() and related calls,
1462  * and validate and process their arguments.
1463  *
1464  * This is split out from check_ungrouped_columns above because it needs
1465  * to modify the nodes (which it does in-place, not via a mutator) while
1466  * check_ungrouped_columns may see only a copy of the original thanks to
1467  * flattening of join alias vars. So here, we flatten each individual
1468  * GROUPING argument as we see it before comparing it.
1469  */
1470 static void
1472  List *groupClauses, bool hasJoinRTEs,
1473  bool have_non_var_grouping)
1474 {
1476 
1477  context.pstate = pstate;
1478  context.qry = qry;
1479  context.hasJoinRTEs = hasJoinRTEs;
1480  context.groupClauses = groupClauses;
1481  context.groupClauseCommonVars = NIL;
1482  context.have_non_var_grouping = have_non_var_grouping;
1483  context.func_grouped_rels = NULL;
1484  context.sublevels_up = 0;
1485  context.in_agg_direct_args = false;
1486  finalize_grouping_exprs_walker(node, &context);
1487 }
1488 
1489 static bool
1492 {
1493  ListCell *gl;
1494 
1495  if (node == NULL)
1496  return false;
1497  if (IsA(node, Const) ||
1498  IsA(node, Param))
1499  return false; /* constants are always acceptable */
1500 
1501  if (IsA(node, Aggref))
1502  {
1503  Aggref *agg = (Aggref *) node;
1504 
1505  if ((int) agg->agglevelsup == context->sublevels_up)
1506  {
1507  /*
1508  * If we find an aggregate call of the original level, do not
1509  * recurse into its normal arguments, ORDER BY arguments, or
1510  * filter; GROUPING exprs of this level are not allowed there. But
1511  * check direct arguments as though they weren't in an aggregate.
1512  */
1513  bool result;
1514 
1515  Assert(!context->in_agg_direct_args);
1516  context->in_agg_direct_args = true;
1518  context);
1519  context->in_agg_direct_args = false;
1520  return result;
1521  }
1522 
1523  /*
1524  * We can skip recursing into aggregates of higher levels altogether,
1525  * since they could not possibly contain exprs of concern to us (see
1526  * transformAggregateCall). We do need to look at aggregates of lower
1527  * levels, however.
1528  */
1529  if ((int) agg->agglevelsup > context->sublevels_up)
1530  return false;
1531  }
1532 
1533  if (IsA(node, GroupingFunc))
1534  {
1535  GroupingFunc *grp = (GroupingFunc *) node;
1536 
1537  /*
1538  * We only need to check GroupingFunc nodes at the exact level to
1539  * which they belong, since they cannot mix levels in arguments.
1540  */
1541 
1542  if ((int) grp->agglevelsup == context->sublevels_up)
1543  {
1544  ListCell *lc;
1545  List *ref_list = NIL;
1546 
1547  foreach(lc, grp->args)
1548  {
1549  Node *expr = lfirst(lc);
1550  Index ref = 0;
1551 
1552  if (context->hasJoinRTEs)
1553  expr = flatten_join_alias_vars(NULL, context->qry, expr);
1554 
1555  /*
1556  * Each expression must match a grouping entry at the current
1557  * query level. Unlike the general expression case, we don't
1558  * allow functional dependencies or outer references.
1559  */
1560 
1561  if (IsA(expr, Var))
1562  {
1563  Var *var = (Var *) expr;
1564 
1565  if (var->varlevelsup == context->sublevels_up)
1566  {
1567  foreach(gl, context->groupClauses)
1568  {
1569  TargetEntry *tle = lfirst(gl);
1570  Var *gvar = (Var *) tle->expr;
1571 
1572  if (IsA(gvar, Var) &&
1573  gvar->varno == var->varno &&
1574  gvar->varattno == var->varattno &&
1575  gvar->varlevelsup == 0)
1576  {
1577  ref = tle->ressortgroupref;
1578  break;
1579  }
1580  }
1581  }
1582  }
1583  else if (context->have_non_var_grouping &&
1584  context->sublevels_up == 0)
1585  {
1586  foreach(gl, context->groupClauses)
1587  {
1588  TargetEntry *tle = lfirst(gl);
1589 
1590  if (equal(expr, tle->expr))
1591  {
1592  ref = tle->ressortgroupref;
1593  break;
1594  }
1595  }
1596  }
1597 
1598  if (ref == 0)
1599  ereport(ERROR,
1600  (errcode(ERRCODE_GROUPING_ERROR),
1601  errmsg("arguments to GROUPING must be grouping expressions of the associated query level"),
1602  parser_errposition(context->pstate,
1603  exprLocation(expr))));
1604 
1605  ref_list = lappend_int(ref_list, ref);
1606  }
1607 
1608  grp->refs = ref_list;
1609  }
1610 
1611  if ((int) grp->agglevelsup > context->sublevels_up)
1612  return false;
1613  }
1614 
1615  if (IsA(node, Query))
1616  {
1617  /* Recurse into subselects */
1618  bool result;
1619 
1620  context->sublevels_up++;
1621  result = query_tree_walker((Query *) node,
1623  (void *) context,
1624  0);
1625  context->sublevels_up--;
1626  return result;
1627  }
1629  (void *) context);
1630 }
1631 
1632 
1633 /*
1634  * Given a GroupingSet node, expand it and return a list of lists.
1635  *
1636  * For EMPTY nodes, return a list of one empty list.
1637  *
1638  * For SIMPLE nodes, return a list of one list, which is the node content.
1639  *
1640  * For CUBE and ROLLUP nodes, return a list of the expansions.
1641  *
1642  * For SET nodes, recursively expand contained CUBE and ROLLUP.
1643  */
1644 static List *
1646 {
1647  List *result = NIL;
1648 
1649  switch (gs->kind)
1650  {
1651  case GROUPING_SET_EMPTY:
1652  result = list_make1(NIL);
1653  break;
1654 
1655  case GROUPING_SET_SIMPLE:
1656  result = list_make1(gs->content);
1657  break;
1658 
1659  case GROUPING_SET_ROLLUP:
1660  {
1661  List *rollup_val = gs->content;
1662  ListCell *lc;
1663  int curgroup_size = list_length(gs->content);
1664 
1665  while (curgroup_size > 0)
1666  {
1667  List *current_result = NIL;
1668  int i = curgroup_size;
1669 
1670  foreach(lc, rollup_val)
1671  {
1672  GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
1673 
1674  Assert(gs_current->kind == GROUPING_SET_SIMPLE);
1675 
1676  current_result = list_concat(current_result,
1677  gs_current->content);
1678 
1679  /* If we are done with making the current group, break */
1680  if (--i == 0)
1681  break;
1682  }
1683 
1684  result = lappend(result, current_result);
1685  --curgroup_size;
1686  }
1687 
1688  result = lappend(result, NIL);
1689  }
1690  break;
1691 
1692  case GROUPING_SET_CUBE:
1693  {
1694  List *cube_list = gs->content;
1695  int number_bits = list_length(cube_list);
1696  uint32 num_sets;
1697  uint32 i;
1698 
1699  /* parser should cap this much lower */
1700  Assert(number_bits < 31);
1701 
1702  num_sets = (1U << number_bits);
1703 
1704  for (i = 0; i < num_sets; i++)
1705  {
1706  List *current_result = NIL;
1707  ListCell *lc;
1708  uint32 mask = 1U;
1709 
1710  foreach(lc, cube_list)
1711  {
1712  GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
1713 
1714  Assert(gs_current->kind == GROUPING_SET_SIMPLE);
1715 
1716  if (mask & i)
1717  current_result = list_concat(current_result,
1718  gs_current->content);
1719 
1720  mask <<= 1;
1721  }
1722 
1723  result = lappend(result, current_result);
1724  }
1725  }
1726  break;
1727 
1728  case GROUPING_SET_SETS:
1729  {
1730  ListCell *lc;
1731 
1732  foreach(lc, gs->content)
1733  {
1734  List *current_result = expand_groupingset_node(lfirst(lc));
1735 
1736  result = list_concat(result, current_result);
1737  }
1738  }
1739  break;
1740  }
1741 
1742  return result;
1743 }
1744 
1745 /* list_sort comparator to sort sub-lists by length */
1746 static int
1748 {
1749  int la = list_length((const List *) lfirst(a));
1750  int lb = list_length((const List *) lfirst(b));
1751 
1752  return (la > lb) ? 1 : (la == lb) ? 0 : -1;
1753 }
1754 
1755 /* list_sort comparator to sort sub-lists by length and contents */
1756 static int
1758 {
1759  int res = cmp_list_len_asc(a, b);
1760 
1761  if (res == 0)
1762  {
1763  List *la = (List *) lfirst(a);
1764  List *lb = (List *) lfirst(b);
1765  ListCell *lca;
1766  ListCell *lcb;
1767 
1768  forboth(lca, la, lcb, lb)
1769  {
1770  int va = lfirst_int(lca);
1771  int vb = lfirst_int(lcb);
1772 
1773  if (va > vb)
1774  return 1;
1775  if (va < vb)
1776  return -1;
1777  }
1778  }
1779 
1780  return res;
1781 }
1782 
1783 /*
1784  * Expand a groupingSets clause to a flat list of grouping sets.
1785  * The returned list is sorted by length, shortest sets first.
1786  *
1787  * This is mainly for the planner, but we use it here too to do
1788  * some consistency checks.
1789  */
1790 List *
1791 expand_grouping_sets(List *groupingSets, bool groupDistinct, int limit)
1792 {
1793  List *expanded_groups = NIL;
1794  List *result = NIL;
1795  double numsets = 1;
1796  ListCell *lc;
1797 
1798  if (groupingSets == NIL)
1799  return NIL;
1800 
1801  foreach(lc, groupingSets)
1802  {
1803  List *current_result = NIL;
1804  GroupingSet *gs = lfirst(lc);
1805 
1806  current_result = expand_groupingset_node(gs);
1807 
1808  Assert(current_result != NIL);
1809 
1810  numsets *= list_length(current_result);
1811 
1812  if (limit >= 0 && numsets > limit)
1813  return NIL;
1814 
1815  expanded_groups = lappend(expanded_groups, current_result);
1816  }
1817 
1818  /*
1819  * Do cartesian product between sublists of expanded_groups. While at it,
1820  * remove any duplicate elements from individual grouping sets (we must
1821  * NOT change the number of sets though)
1822  */
1823 
1824  foreach(lc, (List *) linitial(expanded_groups))
1825  {
1826  result = lappend(result, list_union_int(NIL, (List *) lfirst(lc)));
1827  }
1828 
1829  for_each_from(lc, expanded_groups, 1)
1830  {
1831  List *p = lfirst(lc);
1832  List *new_result = NIL;
1833  ListCell *lc2;
1834 
1835  foreach(lc2, result)
1836  {
1837  List *q = lfirst(lc2);
1838  ListCell *lc3;
1839 
1840  foreach(lc3, p)
1841  {
1842  new_result = lappend(new_result,
1843  list_union_int(q, (List *) lfirst(lc3)));
1844  }
1845  }
1846  result = new_result;
1847  }
1848 
1849  /* Now sort the lists by length and deduplicate if necessary */
1850  if (!groupDistinct || list_length(result) < 2)
1851  list_sort(result, cmp_list_len_asc);
1852  else
1853  {
1854  ListCell *cell;
1855  List *prev;
1856 
1857  /* Sort each groupset individually */
1858  foreach(cell, result)
1859  list_sort(lfirst(cell), list_int_cmp);
1860 
1861  /* Now sort the list of groupsets by length and contents */
1863 
1864  /* Finally, remove duplicates */
1865  prev = linitial(result);
1866  for_each_from(cell, result, 1)
1867  {
1868  if (equal(lfirst(cell), prev))
1869  result = foreach_delete_current(result, cell);
1870  else
1871  prev = lfirst(cell);
1872  }
1873  }
1874 
1875  return result;
1876 }
1877 
1878 /*
1879  * get_aggregate_argtypes
1880  * Identify the specific datatypes passed to an aggregate call.
1881  *
1882  * Given an Aggref, extract the actual datatypes of the input arguments.
1883  * The input datatypes are reported in a way that matches up with the
1884  * aggregate's declaration, ie, any ORDER BY columns attached to a plain
1885  * aggregate are ignored, but we report both direct and aggregated args of
1886  * an ordered-set aggregate.
1887  *
1888  * Datatypes are returned into inputTypes[], which must reference an array
1889  * of length FUNC_MAX_ARGS.
1890  *
1891  * The function result is the number of actual arguments.
1892  */
1893 int
1894 get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
1895 {
1896  int numArguments = 0;
1897  ListCell *lc;
1898 
1899  Assert(list_length(aggref->aggargtypes) <= FUNC_MAX_ARGS);
1900 
1901  foreach(lc, aggref->aggargtypes)
1902  {
1903  inputTypes[numArguments++] = lfirst_oid(lc);
1904  }
1905 
1906  return numArguments;
1907 }
1908 
1909 /*
1910  * resolve_aggregate_transtype
1911  * Identify the transition state value's datatype for an aggregate call.
1912  *
1913  * This function resolves a polymorphic aggregate's state datatype.
1914  * It must be passed the aggtranstype from the aggregate's catalog entry,
1915  * as well as the actual argument types extracted by get_aggregate_argtypes.
1916  * (We could fetch pg_aggregate.aggtranstype internally, but all existing
1917  * callers already have the value at hand, so we make them pass it.)
1918  */
1919 Oid
1921  Oid aggtranstype,
1922  Oid *inputTypes,
1923  int numArguments)
1924 {
1925  /* resolve actual type of transition state, if polymorphic */
1926  if (IsPolymorphicType(aggtranstype))
1927  {
1928  /* have to fetch the agg's declared input types... */
1929  Oid *declaredArgTypes;
1930  int agg_nargs;
1931 
1932  (void) get_func_signature(aggfuncid, &declaredArgTypes, &agg_nargs);
1933 
1934  /*
1935  * VARIADIC ANY aggs could have more actual than declared args, but
1936  * such extra args can't affect polymorphic type resolution.
1937  */
1938  Assert(agg_nargs <= numArguments);
1939 
1940  aggtranstype = enforce_generic_type_consistency(inputTypes,
1941  declaredArgTypes,
1942  agg_nargs,
1943  aggtranstype,
1944  false);
1945  pfree(declaredArgTypes);
1946  }
1947  return aggtranstype;
1948 }
1949 
1950 /*
1951  * agg_args_support_sendreceive
1952  * Returns true if all non-byval of aggref's arg types have send and
1953  * receive functions.
1954  */
1955 bool
1957 {
1958  ListCell *lc;
1959 
1960  foreach(lc, aggref->args)
1961  {
1962  HeapTuple typeTuple;
1963  Form_pg_type pt;
1964  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1965  Oid type = exprType((Node *) tle->expr);
1966 
1968  if (!HeapTupleIsValid(typeTuple))
1969  elog(ERROR, "cache lookup failed for type %u", type);
1970 
1971  pt = (Form_pg_type) GETSTRUCT(typeTuple);
1972 
1973  if (!pt->typbyval &&
1974  (!OidIsValid(pt->typsend) || !OidIsValid(pt->typreceive)))
1975  {
1976  ReleaseSysCache(typeTuple);
1977  return false;
1978  }
1979  ReleaseSysCache(typeTuple);
1980  }
1981  return true;
1982 }
1983 
1984 /*
1985  * Create an expression tree for the transition function of an aggregate.
1986  * This is needed so that polymorphic functions can be used within an
1987  * aggregate --- without the expression tree, such functions would not know
1988  * the datatypes they are supposed to use. (The trees will never actually
1989  * be executed, however, so we can skimp a bit on correctness.)
1990  *
1991  * agg_input_types and agg_state_type identifies the input types of the
1992  * aggregate. These should be resolved to actual types (ie, none should
1993  * ever be ANYELEMENT etc).
1994  * agg_input_collation is the aggregate function's input collation.
1995  *
1996  * For an ordered-set aggregate, remember that agg_input_types describes
1997  * the direct arguments followed by the aggregated arguments.
1998  *
1999  * transfn_oid and invtransfn_oid identify the funcs to be called; the
2000  * latter may be InvalidOid, however if invtransfn_oid is set then
2001  * transfn_oid must also be set.
2002  *
2003  * transfn_oid may also be passed as the aggcombinefn when the *transfnexpr is
2004  * to be used for a combine aggregate phase. We expect invtransfn_oid to be
2005  * InvalidOid in this case since there is no such thing as an inverse
2006  * combinefn.
2007  *
2008  * Pointers to the constructed trees are returned into *transfnexpr,
2009  * *invtransfnexpr. If there is no invtransfn, the respective pointer is set
2010  * to NULL. Since use of the invtransfn is optional, NULL may be passed for
2011  * invtransfnexpr.
2012  */
2013 void
2015  int agg_num_inputs,
2016  int agg_num_direct_inputs,
2017  bool agg_variadic,
2018  Oid agg_state_type,
2019  Oid agg_input_collation,
2020  Oid transfn_oid,
2021  Oid invtransfn_oid,
2022  Expr **transfnexpr,
2023  Expr **invtransfnexpr)
2024 {
2025  List *args;
2026  FuncExpr *fexpr;
2027  int i;
2028 
2029  /*
2030  * Build arg list to use in the transfn FuncExpr node.
2031  */
2032  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2033 
2034  for (i = agg_num_direct_inputs; i < agg_num_inputs; i++)
2035  {
2036  args = lappend(args,
2037  make_agg_arg(agg_input_types[i], agg_input_collation));
2038  }
2039 
2040  fexpr = makeFuncExpr(transfn_oid,
2041  agg_state_type,
2042  args,
2043  InvalidOid,
2044  agg_input_collation,
2046  fexpr->funcvariadic = agg_variadic;
2047  *transfnexpr = (Expr *) fexpr;
2048 
2049  /*
2050  * Build invtransfn expression if requested, with same args as transfn
2051  */
2052  if (invtransfnexpr != NULL)
2053  {
2054  if (OidIsValid(invtransfn_oid))
2055  {
2056  fexpr = makeFuncExpr(invtransfn_oid,
2057  agg_state_type,
2058  args,
2059  InvalidOid,
2060  agg_input_collation,
2062  fexpr->funcvariadic = agg_variadic;
2063  *invtransfnexpr = (Expr *) fexpr;
2064  }
2065  else
2066  *invtransfnexpr = NULL;
2067  }
2068 }
2069 
2070 /*
2071  * Like build_aggregate_transfn_expr, but creates an expression tree for the
2072  * serialization function of an aggregate.
2073  */
2074 void
2076  Expr **serialfnexpr)
2077 {
2078  List *args;
2079  FuncExpr *fexpr;
2080 
2081  /* serialfn always takes INTERNAL and returns BYTEA */
2082  args = list_make1(make_agg_arg(INTERNALOID, InvalidOid));
2083 
2084  fexpr = makeFuncExpr(serialfn_oid,
2085  BYTEAOID,
2086  args,
2087  InvalidOid,
2088  InvalidOid,
2090  *serialfnexpr = (Expr *) fexpr;
2091 }
2092 
2093 /*
2094  * Like build_aggregate_transfn_expr, but creates an expression tree for the
2095  * deserialization function of an aggregate.
2096  */
2097 void
2099  Expr **deserialfnexpr)
2100 {
2101  List *args;
2102  FuncExpr *fexpr;
2103 
2104  /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2105  args = list_make2(make_agg_arg(BYTEAOID, InvalidOid),
2106  make_agg_arg(INTERNALOID, InvalidOid));
2107 
2108  fexpr = makeFuncExpr(deserialfn_oid,
2109  INTERNALOID,
2110  args,
2111  InvalidOid,
2112  InvalidOid,
2114  *deserialfnexpr = (Expr *) fexpr;
2115 }
2116 
2117 /*
2118  * Like build_aggregate_transfn_expr, but creates an expression tree for the
2119  * final function of an aggregate, rather than the transition function.
2120  */
2121 void
2123  int num_finalfn_inputs,
2124  Oid agg_state_type,
2125  Oid agg_result_type,
2126  Oid agg_input_collation,
2127  Oid finalfn_oid,
2128  Expr **finalfnexpr)
2129 {
2130  List *args;
2131  int i;
2132 
2133  /*
2134  * Build expr tree for final function
2135  */
2136  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2137 
2138  /* finalfn may take additional args, which match agg's input types */
2139  for (i = 0; i < num_finalfn_inputs - 1; i++)
2140  {
2141  args = lappend(args,
2142  make_agg_arg(agg_input_types[i], agg_input_collation));
2143  }
2144 
2145  *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2146  agg_result_type,
2147  args,
2148  InvalidOid,
2149  agg_input_collation,
2151  /* finalfn is currently never treated as variadic */
2152 }
2153 
2154 /*
2155  * Convenience function to build dummy argument expressions for aggregates.
2156  *
2157  * We really only care that an aggregate support function can discover its
2158  * actual argument types at runtime using get_fn_expr_argtype(), so it's okay
2159  * to use Param nodes that don't correspond to any real Param.
2160  */
2161 static Node *
2162 make_agg_arg(Oid argtype, Oid argcollation)
2163 {
2164  Param *argp = makeNode(Param);
2165 
2166  argp->paramkind = PARAM_EXEC;
2167  argp->paramid = -1;
2168  argp->paramtype = argtype;
2169  argp->paramtypmod = -1;
2170  argp->paramcollid = argcollation;
2171  argp->location = -1;
2172  return (Node *) argp;
2173 }
int16 AttrNumber
Definition: attnum.h:21
unsigned int uint32
Definition: c.h:495
#define Min(x, y)
Definition: c.h:993
unsigned int Index
Definition: c.h:603
#define OidIsValid(objectId)
Definition: c.h:764
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
int errdetail(const char *fmt,...)
Definition: elog.c:1202
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define _(x)
Definition: elog.c:91
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
void err(int eval, const char *fmt,...)
Definition: err.c:43
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
int b
Definition: isn.c:70
int a
Definition: isn.c:69
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Assert(fmt[strlen(fmt) - 1] !='\n')
void list_sort(List *list, list_sort_comparator cmp)
Definition: list.c:1673
List * list_truncate(List *list, int new_size)
Definition: list.c:630
List * lappend(List *list, void *datum)
Definition: list.c:338
List * list_intersection_int(const List *list1, const List *list2)
Definition: list.c:1199
List * lappend_int(List *list, int datum)
Definition: list.c:356
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
bool list_member_int(const List *list, int datum)
Definition: list.c:701
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1612
int list_int_cmp(const ListCell *p1, const ListCell *p2)
Definition: list.c:1690
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
List * list_union_int(const List *list1, const List *list2)
Definition: list.c:1112
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition: lsyscache.c:1700
Datum lca(PG_FUNCTION_ARGS)
Definition: ltree_op.c:501
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:522
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:241
void pfree(void *pointer)
Definition: mcxt.c:1456
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1312
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:156
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:151
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
#define makeNode(_type_)
Definition: nodes.h:176
Node * transformGroupingFunc(ParseState *pstate, GroupingFunc *p)
Definition: parse_agg.c:248
static int check_agg_arguments(ParseState *pstate, List *directargs, List *args, Expr *filter)
Definition: parse_agg.c:625
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:2122
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2162
static void finalize_grouping_exprs(Node *node, ParseState *pstate, Query *qry, List *groupClauses, bool hasJoinRTEs, bool have_non_var_grouping)
Definition: parse_agg.c:1471
static void check_ungrouped_columns(Node *node, ParseState *pstate, Query *qry, List *groupClauses, List *groupClauseCommonVars, bool have_non_var_grouping, List **func_grouped_rels)
Definition: parse_agg.c:1263
List * expand_grouping_sets(List *groupingSets, bool groupDistinct, int limit)
Definition: parse_agg.c:1791
Oid resolve_aggregate_transtype(Oid aggfuncid, Oid aggtranstype, Oid *inputTypes, int numArguments)
Definition: parse_agg.c:1920
void build_aggregate_deserialfn_expr(Oid deserialfn_oid, Expr **deserialfnexpr)
Definition: parse_agg.c:2098
void transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc, WindowDef *windef)
Definition: parse_agg.c:809
static bool check_agg_arguments_walker(Node *node, check_agg_arguments_context *context)
Definition: parse_agg.c:706
static bool check_ungrouped_columns_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1283
void parseCheckAggregates(ParseState *pstate, Query *qry)
Definition: parse_agg.c:1066
static int cmp_list_len_asc(const ListCell *a, const ListCell *b)
Definition: parse_agg.c:1747
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:2014
void transformAggregateCall(ParseState *pstate, Aggref *agg, List *args, List *aggorder, bool agg_distinct)
Definition: parse_agg.c:103
static bool finalize_grouping_exprs_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1490
static int cmp_list_len_contents_asc(const ListCell *a, const ListCell *b)
Definition: parse_agg.c:1757
static List * expand_groupingset_node(GroupingSet *gs)
Definition: parse_agg.c:1645
bool agg_args_support_sendreceive(Aggref *aggref)
Definition: parse_agg.c:1956
int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
Definition: parse_agg.c:1894
void build_aggregate_serialfn_expr(Oid serialfn_oid, Expr **serialfnexpr)
Definition: parse_agg.c:2075
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 * transformDistinctClause(ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:110
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3064
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
@ EXPR_KIND_EXECUTE_PARAMETER
Definition: parse_node.h:75
@ EXPR_KIND_DOMAIN_CHECK
Definition: parse_node.h:68
@ EXPR_KIND_COPY_WHERE
Definition: parse_node.h:81
@ EXPR_KIND_COLUMN_DEFAULT
Definition: parse_node.h:69
@ EXPR_KIND_DISTINCT_ON
Definition: parse_node.h:61
@ EXPR_KIND_MERGE_WHEN
Definition: parse_node.h:58
@ EXPR_KIND_STATS_EXPRESSION
Definition: parse_node.h:73
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:71
@ EXPR_KIND_PARTITION_BOUND
Definition: parse_node.h:78
@ EXPR_KIND_FUNCTION_DEFAULT
Definition: parse_node.h:70
@ EXPR_KIND_WINDOW_FRAME_RANGE
Definition: parse_node.h:51
@ EXPR_KIND_VALUES
Definition: parse_node.h:65
@ EXPR_KIND_FROM_SUBSELECT
Definition: parse_node.h:44
@ EXPR_KIND_POLICY
Definition: parse_node.h:77
@ EXPR_KIND_WINDOW_FRAME_GROUPS
Definition: parse_node.h:53
@ EXPR_KIND_PARTITION_EXPRESSION
Definition: parse_node.h:79
@ EXPR_KIND_JOIN_USING
Definition: parse_node.h:43
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:72
@ EXPR_KIND_ORDER_BY
Definition: parse_node.h:60
@ EXPR_KIND_OFFSET
Definition: parse_node.h:63
@ EXPR_KIND_JOIN_ON
Definition: parse_node.h:42
@ EXPR_KIND_HAVING
Definition: parse_node.h:47
@ EXPR_KIND_INSERT_TARGET
Definition: parse_node.h:55
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition: parse_node.h:74
@ EXPR_KIND_LIMIT
Definition: parse_node.h:62
@ EXPR_KIND_WHERE
Definition: parse_node.h:46
@ EXPR_KIND_UPDATE_TARGET
Definition: parse_node.h:57
@ EXPR_KIND_SELECT_TARGET
Definition: parse_node.h:54
@ EXPR_KIND_RETURNING
Definition: parse_node.h:64
@ EXPR_KIND_GENERATED_COLUMN
Definition: parse_node.h:82
@ EXPR_KIND_NONE
Definition: parse_node.h:40
@ EXPR_KIND_CALL_ARGUMENT
Definition: parse_node.h:80
@ EXPR_KIND_GROUP_BY
Definition: parse_node.h:59
@ EXPR_KIND_OTHER
Definition: parse_node.h:41
@ EXPR_KIND_FROM_FUNCTION
Definition: parse_node.h:45
@ EXPR_KIND_TRIGGER_WHEN
Definition: parse_node.h:76
@ EXPR_KIND_FILTER
Definition: parse_node.h:48
@ EXPR_KIND_UPDATE_SOURCE
Definition: parse_node.h:56
@ EXPR_KIND_CHECK_CONSTRAINT
Definition: parse_node.h:67
@ EXPR_KIND_WINDOW_PARTITION
Definition: parse_node.h:49
@ EXPR_KIND_CYCLE_MARK
Definition: parse_node.h:83
@ EXPR_KIND_WINDOW_FRAME_ROWS
Definition: parse_node.h:52
@ EXPR_KIND_WINDOW_ORDER
Definition: parse_node.h:50
@ EXPR_KIND_VALUES_SINGLE
Definition: parse_node.h:66
char * get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
@ GROUPING_SET_CUBE
Definition: parsenodes.h:1455
@ GROUPING_SET_SIMPLE
Definition: parsenodes.h:1453
@ GROUPING_SET_ROLLUP
Definition: parsenodes.h:1454
@ GROUPING_SET_SETS
Definition: parsenodes.h:1456
@ GROUPING_SET_EMPTY
Definition: parsenodes.h:1452
@ RTE_JOIN
Definition: parsenodes.h:1015
@ RTE_CTE
Definition: parsenodes.h:1019
@ RTE_RELATION
Definition: parsenodes.h:1013
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:605
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
NameData attname
Definition: pg_attribute.h:41
void * arg
#define FUNC_MAX_ARGS
bool check_functional_grouping(Oid relid, Index varno, Index varlevelsup, List *grouping_columns, List **constraintDeps)
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:467
#define lfirst_int(lc)
Definition: pg_list.h:173
#define list_make1(x1)
Definition: pg_list.h:212
#define for_each_from(cell, lst, N)
Definition: pg_list.h:414
#define linitial(l)
Definition: pg_list.h:178
#define lfirst_oid(lc)
Definition: pg_list.h:174
#define list_make2(x1, x2)
Definition: pg_list.h:214
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:390
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
@ PARAM_EXEC
Definition: primnodes.h:346
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:661
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:215
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:149
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:253
List * aggdistinct
Definition: primnodes.h:452
List * aggdirectargs
Definition: primnodes.h:443
List * args
Definition: primnodes.h:446
Expr * aggfilter
Definition: primnodes.h:455
int location
Definition: primnodes.h:485
List * aggorder
Definition: primnodes.h:449
char * aliasname
Definition: primnodes.h:42
Index agglevelsup
Definition: primnodes.h:529
List * content
Definition: parsenodes.h:1463
Definition: pg_list.h:54
Definition: nodes.h:129
int paramid
Definition: primnodes.h:355
Oid paramtype
Definition: primnodes.h:356
ParamKind paramkind
Definition: primnodes.h:354
int location
Definition: primnodes.h:362
ParseState * parentParseState
Definition: parse_node.h:191
bool p_hasWindowFuncs
Definition: parse_node.h:223
ParseExprKind p_expr_kind
Definition: parse_node.h:210
List * p_windowdefs
Definition: parse_node.h:209
int p_next_resno
Definition: parse_node.h:211
bool p_lateral_active
Definition: parse_node.h:202
List * p_rtable
Definition: parse_node.h:193
bool p_hasAggs
Definition: parse_node.h:222
bool groupDistinct
Definition: parsenodes.h:198
List * groupClause
Definition: parsenodes.h:197
Node * havingQual
Definition: parsenodes.h:202
List * targetList
Definition: parsenodes.h:188
List * groupingSets
Definition: parsenodes.h:200
bool self_reference
Definition: parsenodes.h:1165
Alias * eref
Definition: parsenodes.h:1199
RTEKind rtekind
Definition: parsenodes.h:1032
Expr * expr
Definition: primnodes.h:1895
Index ressortgroupref
Definition: primnodes.h:1901
Definition: primnodes.h:226
AttrNumber varattno
Definition: primnodes.h:238
int varno
Definition: primnodes.h:233
Index varlevelsup
Definition: primnodes.h:258
int location
Definition: primnodes.h:271
List * orderClause
Definition: parsenodes.h:564
List * partitionClause
Definition: parsenodes.h:563
Node * startOffset
Definition: parsenodes.h:566
char * refname
Definition: parsenodes.h:562
Node * endOffset
Definition: parsenodes.h:567
int frameOptions
Definition: parsenodes.h:565
int location
Definition: parsenodes.h:568
char * name
Definition: parsenodes.h:561
List * args
Definition: primnodes.h:553
Index winref
Definition: primnodes.h:557
int location
Definition: primnodes.h:563
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:868
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:820
@ TYPEOID
Definition: syscache.h:114
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:379
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:367
Node * flatten_join_alias_vars(PlannerInfo *root, Query *query, Node *node)
Definition: var.c:744
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:509
const char * type