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