PostgreSQL Source Code  git master
parse_agg.c File Reference
Include dependency graph for parse_agg.c:

Go to the source code of this file.

Data Structures

struct  check_agg_arguments_context
 
struct  check_ungrouped_columns_context
 

Functions

static int check_agg_arguments (ParseState *pstate, List *directargs, List *args, Expr *filter)
 
static bool check_agg_arguments_walker (Node *node, check_agg_arguments_context *context)
 
static void check_ungrouped_columns (Node *node, ParseState *pstate, Query *qry, List *groupClauses, List *groupClauseCommonVars, bool have_non_var_grouping, List **func_grouped_rels)
 
static bool check_ungrouped_columns_walker (Node *node, check_ungrouped_columns_context *context)
 
static void finalize_grouping_exprs (Node *node, ParseState *pstate, Query *qry, List *groupClauses, bool hasJoinRTEs, bool have_non_var_grouping)
 
static bool finalize_grouping_exprs_walker (Node *node, check_ungrouped_columns_context *context)
 
static void check_agglevels_and_constraints (ParseState *pstate, Node *expr)
 
static Listexpand_groupingset_node (GroupingSet *gs)
 
static Nodemake_agg_arg (Oid argtype, Oid argcollation)
 
void transformAggregateCall (ParseState *pstate, Aggref *agg, List *args, List *aggorder, bool agg_distinct)
 
NodetransformGroupingFunc (ParseState *pstate, GroupingFunc *p)
 
void transformWindowFuncCall (ParseState *pstate, WindowFunc *wfunc, WindowDef *windef)
 
void parseCheckAggregates (ParseState *pstate, Query *qry)
 
static int cmp_list_len_asc (const ListCell *a, const ListCell *b)
 
static int cmp_list_len_contents_asc (const ListCell *a, const ListCell *b)
 
Listexpand_grouping_sets (List *groupingSets, bool groupDistinct, int limit)
 
int get_aggregate_argtypes (Aggref *aggref, Oid *inputTypes)
 
Oid resolve_aggregate_transtype (Oid aggfuncid, Oid aggtranstype, Oid *inputTypes, int numArguments)
 
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)
 
void build_aggregate_serialfn_expr (Oid serialfn_oid, Expr **serialfnexpr)
 
void build_aggregate_deserialfn_expr (Oid deserialfn_oid, Expr **deserialfnexpr)
 
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)
 

Function Documentation

◆ build_aggregate_deserialfn_expr()

void build_aggregate_deserialfn_expr ( Oid  deserialfn_oid,
Expr **  deserialfnexpr 
)

Definition at line 2060 of file parse_agg.c.

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 }
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:519
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2124
#define list_make2(x1, x2)
Definition: pg_list.h:212
#define InvalidOid
Definition: postgres_ext.h:36
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:586
Definition: pg_list.h:52

References generate_unaccent_rules::args, COERCE_EXPLICIT_CALL, InvalidOid, list_make2, make_agg_arg(), and makeFuncExpr().

Referenced by build_pertrans_for_aggref().

◆ build_aggregate_finalfn_expr()

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 at line 2084 of file parse_agg.c.

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 }
int i
Definition: isn.c:73
List * lappend(List *list, void *datum)
Definition: list.c:338
#define list_make1(x1)
Definition: pg_list.h:210

References generate_unaccent_rules::args, COERCE_EXPLICIT_CALL, i, InvalidOid, lappend(), list_make1, make_agg_arg(), and makeFuncExpr().

Referenced by ExecInitAgg(), and initialize_peragg().

◆ build_aggregate_serialfn_expr()

void build_aggregate_serialfn_expr ( Oid  serialfn_oid,
Expr **  serialfnexpr 
)

Definition at line 2037 of file parse_agg.c.

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 }

References generate_unaccent_rules::args, COERCE_EXPLICIT_CALL, InvalidOid, list_make1, make_agg_arg(), and makeFuncExpr().

Referenced by build_pertrans_for_aggref().

◆ build_aggregate_transfn_expr()

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 at line 1976 of file parse_agg.c.

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 }
#define OidIsValid(objectId)
Definition: c.h:711
bool funcvariadic
Definition: primnodes.h:601

References generate_unaccent_rules::args, COERCE_EXPLICIT_CALL, FuncExpr::funcvariadic, i, InvalidOid, lappend(), list_make1, make_agg_arg(), makeFuncExpr(), and OidIsValid.

Referenced by build_pertrans_for_aggref(), and initialize_peragg().

◆ check_agg_arguments()

static int check_agg_arguments ( ParseState pstate,
List directargs,
List args,
Expr filter 
)
static

Definition at line 624 of file parse_agg.c.

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 }
#define Min(x, y)
Definition: c.h:937
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
static bool check_agg_arguments_walker(Node *node, check_agg_arguments_context *context)
Definition: parse_agg.c:705
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:131
Definition: nodes.h:118
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:499

References generate_unaccent_rules::args, check_agg_arguments_walker(), ereport, errcode(), errmsg(), ERROR, locate_agg_of_level(), locate_var_of_level(), Min, check_agg_arguments_context::min_agglevel, check_agg_arguments_context::min_varlevel, parser_errposition(), check_agg_arguments_context::pstate, and check_agg_arguments_context::sublevels_up.

Referenced by check_agglevels_and_constraints().

◆ check_agg_arguments_walker()

static bool check_agg_arguments_walker ( Node node,
check_agg_arguments_context context 
)
static

Definition at line 705 of file parse_agg.c.

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 }
int errhint(const char *fmt,...)
Definition: elog.c:1153
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1243
#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:168
Definition: primnodes.h:205

References ereport, errcode(), errhint(), errmsg(), ERROR, expression_tree_walker, exprLocation(), IsA, check_agg_arguments_context::min_agglevel, check_agg_arguments_context::min_varlevel, parser_errposition(), check_agg_arguments_context::pstate, query_tree_walker, and check_agg_arguments_context::sublevels_up.

Referenced by check_agg_arguments().

◆ check_agglevels_and_constraints()

static void check_agglevels_and_constraints ( ParseState pstate,
Node expr 
)
static

Definition at line 286 of file parse_agg.c.

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 }
unsigned int Index
Definition: c.h:550
int errmsg_internal(const char *fmt,...)
Definition: elog.c:993
#define _(x)
Definition: elog.c:90
Assert(fmt[strlen(fmt) - 1] !='\n')
static int check_agg_arguments(ParseState *pstate, List *directargs, List *args, Expr *filter)
Definition: parse_agg.c:624
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:2946
@ 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
#define NIL
Definition: pg_list.h:66
List * aggdirectargs
Definition: primnodes.h:394
Index agglevelsup
Definition: primnodes.h:424
List * args
Definition: primnodes.h:397
Expr * aggfilter
Definition: primnodes.h:406
int location
Definition: primnodes.h:436
List * args
Definition: primnodes.h:468
Index agglevelsup
Definition: primnodes.h:477
ParseState * parentParseState
Definition: parse_node.h:184
ParseExprKind p_expr_kind
Definition: parse_node.h:202
bool p_lateral_active
Definition: parse_node.h:194
bool p_hasAggs
Definition: parse_node.h:214

References _, Aggref::aggdirectargs, Aggref::aggfilter, Aggref::agglevelsup, GroupingFunc::agglevelsup, generate_unaccent_rules::args, Aggref::args, GroupingFunc::args, Assert(), check_agg_arguments(), ereport, errcode(), errmsg_internal(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, EXPR_KIND_CALL_ARGUMENT, EXPR_KIND_CHECK_CONSTRAINT, EXPR_KIND_COLUMN_DEFAULT, EXPR_KIND_COPY_WHERE, EXPR_KIND_CYCLE_MARK, EXPR_KIND_DISTINCT_ON, EXPR_KIND_DOMAIN_CHECK, EXPR_KIND_EXECUTE_PARAMETER, EXPR_KIND_FILTER, EXPR_KIND_FROM_FUNCTION, EXPR_KIND_FROM_SUBSELECT, EXPR_KIND_FUNCTION_DEFAULT, EXPR_KIND_GENERATED_COLUMN, EXPR_KIND_GROUP_BY, EXPR_KIND_HAVING, EXPR_KIND_INDEX_EXPRESSION, EXPR_KIND_INDEX_PREDICATE, EXPR_KIND_INSERT_TARGET, EXPR_KIND_JOIN_ON, EXPR_KIND_JOIN_USING, EXPR_KIND_LIMIT, EXPR_KIND_MERGE_WHEN, EXPR_KIND_NONE, EXPR_KIND_OFFSET, EXPR_KIND_ORDER_BY, EXPR_KIND_OTHER, EXPR_KIND_PARTITION_BOUND, EXPR_KIND_PARTITION_EXPRESSION, EXPR_KIND_POLICY, EXPR_KIND_RETURNING, EXPR_KIND_SELECT_TARGET, EXPR_KIND_STATS_EXPRESSION, EXPR_KIND_TRIGGER_WHEN, EXPR_KIND_UPDATE_SOURCE, EXPR_KIND_UPDATE_TARGET, EXPR_KIND_VALUES, EXPR_KIND_VALUES_SINGLE, EXPR_KIND_WHERE, EXPR_KIND_WINDOW_FRAME_GROUPS, EXPR_KIND_WINDOW_FRAME_RANGE, EXPR_KIND_WINDOW_FRAME_ROWS, EXPR_KIND_WINDOW_ORDER, EXPR_KIND_WINDOW_PARTITION, IsA, Aggref::location, GroupingFunc::location, NIL, ParseState::p_expr_kind, ParseState::p_hasAggs, ParseState::p_lateral_active, ParseState::parentParseState, ParseExprKindName(), and parser_errposition().

Referenced by transformAggregateCall(), and transformGroupingFunc().

◆ check_ungrouped_columns()

static void check_ungrouped_columns ( Node node,
ParseState pstate,
Query qry,
List groupClauses,
List groupClauseCommonVars,
bool  have_non_var_grouping,
List **  func_grouped_rels 
)
static

Definition at line 1259 of file parse_agg.c.

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 }
static bool check_ungrouped_columns_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1279

References check_ungrouped_columns_walker(), check_ungrouped_columns_context::func_grouped_rels, check_ungrouped_columns_context::groupClauseCommonVars, check_ungrouped_columns_context::groupClauses, check_ungrouped_columns_context::hasJoinRTEs, check_ungrouped_columns_context::have_non_var_grouping, check_ungrouped_columns_context::in_agg_direct_args, check_ungrouped_columns_context::pstate, check_ungrouped_columns_context::qry, and check_ungrouped_columns_context::sublevels_up.

Referenced by parseCheckAggregates().

◆ check_ungrouped_columns_walker()

static bool check_ungrouped_columns_walker ( Node node,
check_ungrouped_columns_context context 
)
static

Definition at line 1279 of file parse_agg.c.

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 }
int errdetail(const char *fmt,...)
Definition: elog.c:1039
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:225
List * lappend_int(List *list, int datum)
Definition: list.c:356
bool list_member_int(const List *list, int datum)
Definition: list.c:701
char * get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
@ RTE_RELATION
Definition: parsenodes.h:982
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
NameData attname
Definition: pg_attribute.h:41
bool check_functional_grouping(Oid relid, Index varno, Index varlevelsup, List *grouping_columns, List **constraintDeps)
#define lfirst(lc)
Definition: pg_list.h:170
static int list_length(const List *l)
Definition: pg_list.h:150
char * aliasname
Definition: primnodes.h:42
List * p_rtable
Definition: parse_node.h:186
List * constraintDeps
Definition: parsenodes.h:194
Alias * eref
Definition: parsenodes.h:1152
RTEKind rtekind
Definition: parsenodes.h:1001
Expr * expr
Definition: primnodes.h:1555
AttrNumber varattno
Definition: primnodes.h:217
int varno
Definition: primnodes.h:212
Index varlevelsup
Definition: primnodes.h:230
int location
Definition: primnodes.h:243

References Aggref::aggdirectargs, Aggref::agglevelsup, GroupingFunc::agglevelsup, Alias::aliasname, Assert(), attname, check_functional_grouping(), Query::constraintDeps, equal(), RangeTblEntry::eref, ereport, errcode(), errdetail(), errmsg(), ERROR, TargetEntry::expr, expression_tree_walker, check_ungrouped_columns_context::func_grouped_rels, get_rte_attribute_name(), check_ungrouped_columns_context::groupClauseCommonVars, check_ungrouped_columns_context::groupClauses, check_ungrouped_columns_context::have_non_var_grouping, check_ungrouped_columns_context::in_agg_direct_args, IsA, lappend_int(), lfirst, list_length(), list_member_int(), Var::location, ParseState::p_rtable, parser_errposition(), check_ungrouped_columns_context::pstate, check_ungrouped_columns_context::qry, query_tree_walker, RangeTblEntry::relid, rt_fetch, RTE_RELATION, RangeTblEntry::rtekind, check_ungrouped_columns_context::sublevels_up, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by check_ungrouped_columns().

◆ cmp_list_len_asc()

static int cmp_list_len_asc ( const ListCell a,
const ListCell b 
)
static

Definition at line 1743 of file parse_agg.c.

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 }
int b
Definition: isn.c:70
int a
Definition: isn.c:69

References a, b, lfirst, and list_length().

Referenced by cmp_list_len_contents_asc(), and expand_grouping_sets().

◆ cmp_list_len_contents_asc()

static int cmp_list_len_contents_asc ( const ListCell a,
const ListCell b 
)
static

Definition at line 1753 of file parse_agg.c.

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 }
Datum lca(PG_FUNCTION_ARGS)
Definition: ltree_op.c:501
static int cmp_list_len_asc(const ListCell *a, const ListCell *b)
Definition: parse_agg.c:1743
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:465
#define lfirst_int(lc)
Definition: pg_list.h:171

References a, b, cmp_list_len_asc(), forboth, lca(), lfirst, lfirst_int, and res.

Referenced by expand_grouping_sets().

◆ expand_grouping_sets()

List* expand_grouping_sets ( List groupingSets,
bool  groupDistinct,
int  limit 
)

Definition at line 1787 of file parse_agg.c.

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 }
void list_sort(List *list, list_sort_comparator cmp)
Definition: list.c:1673
int list_int_cmp(const ListCell *p1, const ListCell *p2)
Definition: list.c:1690
List * list_union_int(const List *list1, const List *list2)
Definition: list.c:1112
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
#define for_each_from(cell, lst, N)
Definition: pg_list.h:412
#define linitial(l)
Definition: pg_list.h:176
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:388

References Assert(), cmp_list_len_asc(), cmp_list_len_contents_asc(), equal(), expand_groupingset_node(), for_each_from, foreach_delete_current, lappend(), lfirst, linitial, list_int_cmp(), list_length(), list_sort(), list_union_int(), and NIL.

Referenced by parseCheckAggregates(), and preprocess_grouping_sets().

◆ expand_groupingset_node()

static List * expand_groupingset_node ( GroupingSet gs)
static

Definition at line 1641 of file parse_agg.c.

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 }
unsigned int uint32
Definition: c.h:442
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
@ GROUPING_SET_CUBE
Definition: parsenodes.h:1408
@ GROUPING_SET_SIMPLE
Definition: parsenodes.h:1406
@ GROUPING_SET_ROLLUP
Definition: parsenodes.h:1407
@ GROUPING_SET_SETS
Definition: parsenodes.h:1409
@ GROUPING_SET_EMPTY
Definition: parsenodes.h:1405
GroupingSetKind kind
Definition: parsenodes.h:1415
List * content
Definition: parsenodes.h:1416

References Assert(), GroupingSet::content, GROUPING_SET_CUBE, GROUPING_SET_EMPTY, GROUPING_SET_ROLLUP, GROUPING_SET_SETS, GROUPING_SET_SIMPLE, i, GroupingSet::kind, lappend(), lfirst, list_concat(), list_length(), list_make1, and NIL.

Referenced by expand_grouping_sets().

◆ finalize_grouping_exprs()

static void finalize_grouping_exprs ( Node node,
ParseState pstate,
Query qry,
List groupClauses,
bool  hasJoinRTEs,
bool  have_non_var_grouping 
)
static

Definition at line 1467 of file parse_agg.c.

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 }
static bool finalize_grouping_exprs_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1486

References finalize_grouping_exprs_walker(), check_ungrouped_columns_context::func_grouped_rels, check_ungrouped_columns_context::groupClauseCommonVars, check_ungrouped_columns_context::groupClauses, check_ungrouped_columns_context::hasJoinRTEs, check_ungrouped_columns_context::have_non_var_grouping, check_ungrouped_columns_context::in_agg_direct_args, NIL, check_ungrouped_columns_context::pstate, check_ungrouped_columns_context::qry, and check_ungrouped_columns_context::sublevels_up.

Referenced by parseCheckAggregates().

◆ finalize_grouping_exprs_walker()

static bool finalize_grouping_exprs_walker ( Node node,
check_ungrouped_columns_context context 
)
static

Definition at line 1486 of file parse_agg.c.

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 }
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Index ressortgroupref
Definition: primnodes.h:1558
Node * flatten_join_alias_vars(Query *query, Node *node)
Definition: var.c:726

References Aggref::aggdirectargs, Aggref::agglevelsup, GroupingFunc::agglevelsup, GroupingFunc::args, Assert(), equal(), ereport, errcode(), errmsg(), ERROR, TargetEntry::expr, expression_tree_walker, exprLocation(), flatten_join_alias_vars(), check_ungrouped_columns_context::groupClauses, check_ungrouped_columns_context::hasJoinRTEs, check_ungrouped_columns_context::have_non_var_grouping, if(), check_ungrouped_columns_context::in_agg_direct_args, IsA, lappend_int(), lfirst, NIL, parser_errposition(), check_ungrouped_columns_context::pstate, check_ungrouped_columns_context::qry, query_tree_walker, TargetEntry::ressortgroupref, check_ungrouped_columns_context::sublevels_up, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by finalize_grouping_exprs().

◆ get_aggregate_argtypes()

int get_aggregate_argtypes ( Aggref aggref,
Oid inputTypes 
)

Definition at line 1890 of file parse_agg.c.

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 }
#define FUNC_MAX_ARGS
#define lfirst_oid(lc)
Definition: pg_list.h:172
List * aggargtypes
Definition: primnodes.h:391

References Aggref::aggargtypes, Assert(), FUNC_MAX_ARGS, lfirst_oid, and list_length().

Referenced by ExecInitAgg(), get_agg_expr(), and preprocess_aggref().

◆ make_agg_arg()

static Node * make_agg_arg ( Oid  argtype,
Oid  argcollation 
)
static

Definition at line 2124 of file parse_agg.c.

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 }
#define makeNode(_type_)
Definition: nodes.h:165
@ PARAM_EXEC
Definition: primnodes.h:303
int32 paramtypmod
Definition: primnodes.h:314
int paramid
Definition: primnodes.h:312
Oid paramtype
Definition: primnodes.h:313
ParamKind paramkind
Definition: primnodes.h:311
int location
Definition: primnodes.h:316
Oid paramcollid
Definition: primnodes.h:315

References Param::location, makeNode, PARAM_EXEC, Param::paramcollid, Param::paramid, Param::paramkind, Param::paramtype, and Param::paramtypmod.

Referenced by build_aggregate_deserialfn_expr(), build_aggregate_finalfn_expr(), build_aggregate_serialfn_expr(), and build_aggregate_transfn_expr().

◆ parseCheckAggregates()

void parseCheckAggregates ( ParseState pstate,
Query qry 
)

Definition at line 1062 of file parse_agg.c.

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 }
List * list_intersection_int(const List *list1, const List *list2)
Definition: list.c:1199
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
@ RTE_JOIN
Definition: parsenodes.h:984
@ RTE_CTE
Definition: parsenodes.h:988
bool groupDistinct
Definition: parsenodes.h:173
List * groupClause
Definition: parsenodes.h:172
Node * havingQual
Definition: parsenodes.h:177
List * targetList
Definition: parsenodes.h:164
List * groupingSets
Definition: parsenodes.h:175
bool self_reference
Definition: parsenodes.h:1118
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:367

References Assert(), check_ungrouped_columns(), ereport, errcode(), errmsg(), ERROR, expand_grouping_sets(), TargetEntry::expr, exprLocation(), finalize_grouping_exprs(), flatten_join_alias_vars(), for_each_from, get_sortgroupclause_tle(), Query::groupClause, Query::groupDistinct, Query::groupingSets, Query::havingQual, IsA, lappend(), lfirst, linitial, list_intersection_int(), list_length(), list_member_int(), locate_agg_of_level(), NIL, ParseState::p_hasAggs, ParseState::p_rtable, parser_errposition(), TargetEntry::ressortgroupref, RTE_CTE, RTE_JOIN, RangeTblEntry::rtekind, RangeTblEntry::self_reference, and Query::targetList.

Referenced by transformDeleteStmt(), transformPLAssignStmt(), transformSelectStmt(), and transformSetOperationStmt().

◆ resolve_aggregate_transtype()

Oid resolve_aggregate_transtype ( Oid  aggfuncid,
Oid  aggtranstype,
Oid inputTypes,
int  numArguments 
)

Definition at line 1916 of file parse_agg.c.

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 }
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition: lsyscache.c:1678
void pfree(void *pointer)
Definition: mcxt.c:1306
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
unsigned int Oid
Definition: postgres_ext.h:31

References Assert(), enforce_generic_type_consistency(), get_func_signature(), and pfree().

Referenced by initialize_peragg(), and preprocess_aggref().

◆ transformAggregateCall()

void transformAggregateCall ( ParseState pstate,
Aggref agg,
List args,
List aggorder,
bool  agg_distinct 
)

Definition at line 102 of file parse_agg.c.

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 }
int16 AttrNumber
Definition: attnum.h:21
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
List * list_truncate(List *list, int new_size)
Definition: list.c:630
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1612
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition: parse_agg.c:286
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)
void * arg
List * aggdistinct
Definition: primnodes.h:403
char aggkind
Definition: primnodes.h:418
List * aggorder
Definition: primnodes.h:400
int p_next_resno
Definition: parse_node.h:203
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:379

References addTargetToSortList(), Aggref::aggargtypes, Aggref::aggdirectargs, Aggref::aggdistinct, Aggref::aggkind, Aggref::aggorder, arg, generate_unaccent_rules::args, Aggref::args, Assert(), check_agglevels_and_constraints(), ereport, errcode(), errdetail(), errmsg(), ERROR, EXPR_KIND_ORDER_BY, exprLocation(), exprType(), forboth, format_type_be(), get_sortgroupclause_expr(), lappend(), lappend_oid(), lfirst, list_copy_tail(), list_length(), list_truncate(), makeTargetEntry(), NIL, OidIsValid, ParseState::p_next_resno, parser_errposition(), SortGroupClause::sortop, transformDistinctClause(), and transformSortClause().

Referenced by ParseFuncOrColumn().

◆ transformGroupingFunc()

Node* transformGroupingFunc ( ParseState pstate,
GroupingFunc p 
)

Definition at line 247 of file parse_agg.c.

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 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:92

References generate_unaccent_rules::args, GroupingFunc::args, check_agglevels_and_constraints(), ereport, errcode(), errmsg(), ERROR, lappend(), lfirst, list_length(), GroupingFunc::location, makeNode, NIL, ParseState::p_expr_kind, parser_errposition(), and transformExpr().

Referenced by transformExprRecurse().

◆ transformWindowFuncCall()

void transformWindowFuncCall ( ParseState pstate,
WindowFunc wfunc,
WindowDef windef 
)

Definition at line 809 of file parse_agg.c.

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 }
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:575
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
bool p_hasWindowFuncs
Definition: parse_node.h:215
List * p_windowdefs
Definition: parse_node.h:201
List * orderClause
Definition: parsenodes.h:534
List * partitionClause
Definition: parsenodes.h:533
Node * startOffset
Definition: parsenodes.h:536
char * refname
Definition: parsenodes.h:532
Node * endOffset
Definition: parsenodes.h:537
int frameOptions
Definition: parsenodes.h:535
int location
Definition: parsenodes.h:538
char * name
Definition: parsenodes.h:531
List * args
Definition: primnodes.h:493
Index winref
Definition: primnodes.h:495
int location
Definition: primnodes.h:498

References _, WindowFunc::args, Assert(), contain_windowfuncs(), WindowDef::endOffset, equal(), ereport, errcode(), errmsg(), errmsg_internal(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, EXPR_KIND_CALL_ARGUMENT, EXPR_KIND_CHECK_CONSTRAINT, EXPR_KIND_COLUMN_DEFAULT, EXPR_KIND_COPY_WHERE, EXPR_KIND_CYCLE_MARK, EXPR_KIND_DISTINCT_ON, EXPR_KIND_DOMAIN_CHECK, EXPR_KIND_EXECUTE_PARAMETER, EXPR_KIND_FILTER, EXPR_KIND_FROM_FUNCTION, EXPR_KIND_FROM_SUBSELECT, EXPR_KIND_FUNCTION_DEFAULT, EXPR_KIND_GENERATED_COLUMN, EXPR_KIND_GROUP_BY, EXPR_KIND_HAVING, EXPR_KIND_INDEX_EXPRESSION, EXPR_KIND_INDEX_PREDICATE, EXPR_KIND_INSERT_TARGET, EXPR_KIND_JOIN_ON, EXPR_KIND_JOIN_USING, EXPR_KIND_LIMIT, EXPR_KIND_MERGE_WHEN, EXPR_KIND_NONE, EXPR_KIND_OFFSET, EXPR_KIND_ORDER_BY, EXPR_KIND_OTHER, EXPR_KIND_PARTITION_BOUND, EXPR_KIND_PARTITION_EXPRESSION, EXPR_KIND_POLICY, EXPR_KIND_RETURNING, EXPR_KIND_SELECT_TARGET, EXPR_KIND_STATS_EXPRESSION, EXPR_KIND_TRIGGER_WHEN, EXPR_KIND_UPDATE_SOURCE, EXPR_KIND_UPDATE_TARGET, EXPR_KIND_VALUES, EXPR_KIND_VALUES_SINGLE, EXPR_KIND_WHERE, EXPR_KIND_WINDOW_FRAME_GROUPS, EXPR_KIND_WINDOW_FRAME_RANGE, EXPR_KIND_WINDOW_FRAME_ROWS, EXPR_KIND_WINDOW_ORDER, EXPR_KIND_WINDOW_PARTITION, FRAMEOPTION_DEFAULTS, WindowDef::frameOptions, lappend(), lfirst, list_length(), locate_windowfunc(), WindowDef::location, WindowFunc::location, WindowDef::name, NIL, WindowDef::orderClause, ParseState::p_expr_kind, ParseState::p_hasWindowFuncs, ParseState::p_windowdefs, ParseExprKindName(), parser_errposition(), WindowDef::partitionClause, WindowDef::refname, WindowDef::startOffset, and WindowFunc::winref.

Referenced by ParseFuncOrColumn().