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