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