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)
 
Listexpand_grouping_sets (List *groupingSets, 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_combinefn_expr (Oid agg_state_type, Oid agg_input_collation, Oid combinefn_oid, Expr **combinefnexpr)
 
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_combinefn_expr()

void build_aggregate_combinefn_expr ( Oid  agg_state_type,
Oid  agg_input_collation,
Oid  combinefn_oid,
Expr **  combinefnexpr 
)

Definition at line 1968 of file parse_agg.c.

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

Referenced by build_pertrans_for_aggref().

1972 {
1973  Node *argp;
1974  List *args;
1975  FuncExpr *fexpr;
1976 
1977  /* combinefn takes two arguments of the aggregate state type */
1978  argp = make_agg_arg(agg_state_type, agg_input_collation);
1979 
1980  args = list_make2(argp, argp);
1981 
1982  fexpr = makeFuncExpr(combinefn_oid,
1983  agg_state_type,
1984  args,
1985  InvalidOid,
1986  agg_input_collation,
1988  /* combinefn is currently never treated as variadic */
1989  *combinefnexpr = (Expr *) fexpr;
1990 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2084
Definition: nodes.h:533
#define InvalidOid
Definition: postgres_ext.h:36
Definition: pg_list.h:50
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:519

◆ build_aggregate_deserialfn_expr()

void build_aggregate_deserialfn_expr ( Oid  deserialfn_oid,
Expr **  deserialfnexpr 
)

Definition at line 2020 of file parse_agg.c.

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

Referenced by build_pertrans_for_aggref().

2022 {
2023  List *args;
2024  FuncExpr *fexpr;
2025 
2026  /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2027  args = list_make2(make_agg_arg(BYTEAOID, InvalidOid),
2028  make_agg_arg(INTERNALOID, InvalidOid));
2029 
2030  fexpr = makeFuncExpr(deserialfn_oid,
2031  INTERNALOID,
2032  args,
2033  InvalidOid,
2034  InvalidOid,
2036  *deserialfnexpr = (Expr *) fexpr;
2037 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2084
#define InvalidOid
Definition: postgres_ext.h:36
Definition: pg_list.h:50
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:519

◆ 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 2044 of file parse_agg.c.

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

Referenced by ExecInitAgg(), and initialize_peragg().

2051 {
2052  List *args;
2053  int i;
2054 
2055  /*
2056  * Build expr tree for final function
2057  */
2058  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2059 
2060  /* finalfn may take additional args, which match agg's input types */
2061  for (i = 0; i < num_finalfn_inputs - 1; i++)
2062  {
2063  args = lappend(args,
2064  make_agg_arg(agg_input_types[i], agg_input_collation));
2065  }
2066 
2067  *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2068  agg_result_type,
2069  args,
2070  InvalidOid,
2071  agg_input_collation,
2073  /* finalfn is currently never treated as variadic */
2074 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2084
#define list_make1(x1)
Definition: pg_list.h:206
List * lappend(List *list, void *datum)
Definition: list.c:336
#define InvalidOid
Definition: postgres_ext.h:36
int i
Definition: pg_list.h:50
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:519

◆ build_aggregate_serialfn_expr()

void build_aggregate_serialfn_expr ( Oid  serialfn_oid,
Expr **  serialfnexpr 
)

Definition at line 1997 of file parse_agg.c.

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

Referenced by build_pertrans_for_aggref().

1999 {
2000  List *args;
2001  FuncExpr *fexpr;
2002 
2003  /* serialfn always takes INTERNAL and returns BYTEA */
2004  args = list_make1(make_agg_arg(INTERNALOID, InvalidOid));
2005 
2006  fexpr = makeFuncExpr(serialfn_oid,
2007  BYTEAOID,
2008  args,
2009  InvalidOid,
2010  InvalidOid,
2012  *serialfnexpr = (Expr *) fexpr;
2013 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2084
#define list_make1(x1)
Definition: pg_list.h:206
#define InvalidOid
Definition: postgres_ext.h:36
Definition: pg_list.h:50
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:519

◆ 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 1907 of file parse_agg.c.

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().

1917 {
1918  List *args;
1919  FuncExpr *fexpr;
1920  int i;
1921 
1922  /*
1923  * Build arg list to use in the transfn FuncExpr node.
1924  */
1925  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
1926 
1927  for (i = agg_num_direct_inputs; i < agg_num_inputs; i++)
1928  {
1929  args = lappend(args,
1930  make_agg_arg(agg_input_types[i], agg_input_collation));
1931  }
1932 
1933  fexpr = makeFuncExpr(transfn_oid,
1934  agg_state_type,
1935  args,
1936  InvalidOid,
1937  agg_input_collation,
1939  fexpr->funcvariadic = agg_variadic;
1940  *transfnexpr = (Expr *) fexpr;
1941 
1942  /*
1943  * Build invtransfn expression if requested, with same args as transfn
1944  */
1945  if (invtransfnexpr != NULL)
1946  {
1947  if (OidIsValid(invtransfn_oid))
1948  {
1949  fexpr = makeFuncExpr(invtransfn_oid,
1950  agg_state_type,
1951  args,
1952  InvalidOid,
1953  agg_input_collation,
1955  fexpr->funcvariadic = agg_variadic;
1956  *invtransfnexpr = (Expr *) fexpr;
1957  }
1958  else
1959  *invtransfnexpr = NULL;
1960  }
1961 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2084
#define OidIsValid(objectId)
Definition: c.h:710
#define list_make1(x1)
Definition: pg_list.h:206
List * lappend(List *list, void *datum)
Definition: list.c:336
#define InvalidOid
Definition: postgres_ext.h:36
int i
Definition: pg_list.h:50
bool funcvariadic
Definition: primnodes.h:493
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:519

◆ check_agg_arguments()

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

Definition at line 610 of file parse_agg.c.

References generate_unaccent_rules::args, check_agg_arguments_walker(), ereport, errcode(), errmsg(), ERROR, expression_tree_walker(), 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().

614 {
615  int agglevel;
617 
618  context.pstate = pstate;
619  context.min_varlevel = -1; /* signifies nothing found yet */
620  context.min_agglevel = -1;
621  context.sublevels_up = 0;
622 
623  (void) expression_tree_walker((Node *) args,
625  (void *) &context);
626 
627  (void) expression_tree_walker((Node *) filter,
629  (void *) &context);
630 
631  /*
632  * If we found no vars nor aggs at all, it's a level-zero aggregate;
633  * otherwise, its level is the minimum of vars or aggs.
634  */
635  if (context.min_varlevel < 0)
636  {
637  if (context.min_agglevel < 0)
638  agglevel = 0;
639  else
640  agglevel = context.min_agglevel;
641  }
642  else if (context.min_agglevel < 0)
643  agglevel = context.min_varlevel;
644  else
645  agglevel = Min(context.min_varlevel, context.min_agglevel);
646 
647  /*
648  * If there's a nested aggregate of the same semantic level, complain.
649  */
650  if (agglevel == context.min_agglevel)
651  {
652  int aggloc;
653 
654  aggloc = locate_agg_of_level((Node *) args, agglevel);
655  if (aggloc < 0)
656  aggloc = locate_agg_of_level((Node *) filter, agglevel);
657  ereport(ERROR,
658  (errcode(ERRCODE_GROUPING_ERROR),
659  errmsg("aggregate function calls cannot be nested"),
660  parser_errposition(pstate, aggloc)));
661  }
662 
663  /*
664  * Now check for vars/aggs in the direct arguments, and throw error if
665  * needed. Note that we allow a Var of the agg's semantic level, but not
666  * an Agg of that level. In principle such Aggs could probably be
667  * supported, but it would create an ordering dependency among the
668  * aggregates at execution time. Since the case appears neither to be
669  * required by spec nor particularly useful, we just treat it as a
670  * nested-aggregate situation.
671  */
672  if (directargs)
673  {
674  context.min_varlevel = -1;
675  context.min_agglevel = -1;
676  (void) expression_tree_walker((Node *) directargs,
678  (void *) &context);
679  if (context.min_varlevel >= 0 && context.min_varlevel < agglevel)
680  ereport(ERROR,
681  (errcode(ERRCODE_GROUPING_ERROR),
682  errmsg("outer-level aggregate cannot contain a lower-level variable in its direct arguments"),
683  parser_errposition(pstate,
684  locate_var_of_level((Node *) directargs,
685  context.min_varlevel))));
686  if (context.min_agglevel >= 0 && context.min_agglevel <= agglevel)
687  ereport(ERROR,
688  (errcode(ERRCODE_GROUPING_ERROR),
689  errmsg("aggregate function calls cannot be nested"),
690  parser_errposition(pstate,
691  locate_agg_of_level((Node *) directargs,
692  context.min_agglevel))));
693  }
694  return agglevel;
695 }
#define Min(x, y)
Definition: c.h:986
Definition: nodes.h:533
int errcode(int sqlerrcode)
Definition: elog.c:694
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:464
#define ERROR
Definition: elog.h:45
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:131
#define ereport(elevel,...)
Definition: elog.h:155
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:905
static bool check_agg_arguments_walker(Node *node, check_agg_arguments_context *context)
Definition: parse_agg.c:698

◆ check_agg_arguments_walker()

static bool check_agg_arguments_walker ( Node node,
check_agg_arguments_context context 
)
static

Definition at line 698 of file parse_agg.c.

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().

700 {
701  if (node == NULL)
702  return false;
703  if (IsA(node, Var))
704  {
705  int varlevelsup = ((Var *) node)->varlevelsup;
706 
707  /* convert levelsup to frame of reference of original query */
708  varlevelsup -= context->sublevels_up;
709  /* ignore local vars of subqueries */
710  if (varlevelsup >= 0)
711  {
712  if (context->min_varlevel < 0 ||
713  context->min_varlevel > varlevelsup)
714  context->min_varlevel = varlevelsup;
715  }
716  return false;
717  }
718  if (IsA(node, Aggref))
719  {
720  int agglevelsup = ((Aggref *) node)->agglevelsup;
721 
722  /* convert levelsup to frame of reference of original query */
723  agglevelsup -= context->sublevels_up;
724  /* ignore local aggs of subqueries */
725  if (agglevelsup >= 0)
726  {
727  if (context->min_agglevel < 0 ||
728  context->min_agglevel > agglevelsup)
729  context->min_agglevel = agglevelsup;
730  }
731  /* no need to examine args of the inner aggregate */
732  return false;
733  }
734  if (IsA(node, GroupingFunc))
735  {
736  int agglevelsup = ((GroupingFunc *) node)->agglevelsup;
737 
738  /* convert levelsup to frame of reference of original query */
739  agglevelsup -= context->sublevels_up;
740  /* ignore local aggs of subqueries */
741  if (agglevelsup >= 0)
742  {
743  if (context->min_agglevel < 0 ||
744  context->min_agglevel > agglevelsup)
745  context->min_agglevel = agglevelsup;
746  }
747  /* Continue and descend into subtree */
748  }
749 
750  /*
751  * SRFs and window functions can be rejected immediately, unless we are
752  * within a sub-select within the aggregate's arguments; in that case
753  * they're OK.
754  */
755  if (context->sublevels_up == 0)
756  {
757  if ((IsA(node, FuncExpr) && ((FuncExpr *) node)->funcretset) ||
758  (IsA(node, OpExpr) && ((OpExpr *) node)->opretset))
759  ereport(ERROR,
760  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
761  errmsg("aggregate function calls cannot contain set-returning function calls"),
762  errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
763  parser_errposition(context->pstate, exprLocation(node))));
764  if (IsA(node, WindowFunc))
765  ereport(ERROR,
766  (errcode(ERRCODE_GROUPING_ERROR),
767  errmsg("aggregate function calls cannot contain window function calls"),
768  parser_errposition(context->pstate,
769  ((WindowFunc *) node)->location)));
770  }
771  if (IsA(node, Query))
772  {
773  /* Recurse into subselects */
774  bool result;
775 
776  context->sublevels_up++;
777  result = query_tree_walker((Query *) node,
779  (void *) context,
780  0);
781  context->sublevels_up--;
782  return result;
783  }
784 
785  return expression_tree_walker(node,
787  (void *) context);
788 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2336
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
int errhint(const char *fmt,...)
Definition: elog.c:1152
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1231
int errcode(int sqlerrcode)
Definition: elog.c:694
Definition: primnodes.h:181
#define ERROR
Definition: elog.h:45
#define ereport(elevel,...)
Definition: elog.h:155
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:905
static bool check_agg_arguments_walker(Node *node, check_agg_arguments_context *context)
Definition: parse_agg.c:698

◆ check_agglevels_and_constraints()

static void check_agglevels_and_constraints ( ParseState pstate,
Node expr 
)
static

Definition at line 286 of file parse_agg.c.

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_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_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().

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;
437  case EXPR_KIND_GROUP_BY:
438  errkind = true;
439  break;
440  case EXPR_KIND_ORDER_BY:
441  /* okay */
442  break;
444  /* okay */
445  break;
446  case EXPR_KIND_LIMIT:
447  case EXPR_KIND_OFFSET:
448  errkind = true;
449  break;
450  case EXPR_KIND_RETURNING:
451  errkind = true;
452  break;
453  case EXPR_KIND_VALUES:
455  errkind = true;
456  break;
459  if (isAgg)
460  err = _("aggregate functions are not allowed in check constraints");
461  else
462  err = _("grouping operations are not allowed in check constraints");
463 
464  break;
467 
468  if (isAgg)
469  err = _("aggregate functions are not allowed in DEFAULT expressions");
470  else
471  err = _("grouping operations are not allowed in DEFAULT expressions");
472 
473  break;
475  if (isAgg)
476  err = _("aggregate functions are not allowed in index expressions");
477  else
478  err = _("grouping operations are not allowed in index expressions");
479 
480  break;
482  if (isAgg)
483  err = _("aggregate functions are not allowed in index predicates");
484  else
485  err = _("grouping operations are not allowed in index predicates");
486 
487  break;
489  if (isAgg)
490  err = _("aggregate functions are not allowed in transform expressions");
491  else
492  err = _("grouping operations are not allowed in transform expressions");
493 
494  break;
496  if (isAgg)
497  err = _("aggregate functions are not allowed in EXECUTE parameters");
498  else
499  err = _("grouping operations are not allowed in EXECUTE parameters");
500 
501  break;
503  if (isAgg)
504  err = _("aggregate functions are not allowed in trigger WHEN conditions");
505  else
506  err = _("grouping operations are not allowed in trigger WHEN conditions");
507 
508  break;
510  if (isAgg)
511  err = _("aggregate functions are not allowed in partition bound");
512  else
513  err = _("grouping operations are not allowed in partition bound");
514 
515  break;
517  if (isAgg)
518  err = _("aggregate functions are not allowed in partition key expressions");
519  else
520  err = _("grouping operations are not allowed in partition key expressions");
521 
522  break;
524 
525  if (isAgg)
526  err = _("aggregate functions are not allowed in column generation expressions");
527  else
528  err = _("grouping operations are not allowed in column generation expressions");
529 
530  break;
531 
533  if (isAgg)
534  err = _("aggregate functions are not allowed in CALL arguments");
535  else
536  err = _("grouping operations are not allowed in CALL arguments");
537 
538  break;
539 
541  if (isAgg)
542  err = _("aggregate functions are not allowed in COPY FROM WHERE conditions");
543  else
544  err = _("grouping operations are not allowed in COPY FROM WHERE conditions");
545 
546  break;
547 
549  errkind = true;
550  break;
551 
552  /*
553  * There is intentionally no default: case here, so that the
554  * compiler will warn if we add a new ParseExprKind without
555  * extending this switch. If we do see an unrecognized value at
556  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
557  * which is sane anyway.
558  */
559  }
560 
561  if (err)
562  ereport(ERROR,
563  (errcode(ERRCODE_GROUPING_ERROR),
564  errmsg_internal("%s", err),
565  parser_errposition(pstate, location)));
566 
567  if (errkind)
568  {
569  if (isAgg)
570  /* translator: %s is name of a SQL construct, eg GROUP BY */
571  err = _("aggregate functions are not allowed in %s");
572  else
573  /* translator: %s is name of a SQL construct, eg GROUP BY */
574  err = _("grouping operations are not allowed in %s");
575 
576  ereport(ERROR,
577  (errcode(ERRCODE_GROUPING_ERROR),
578  errmsg_internal(err,
579  ParseExprKindName(pstate->p_expr_kind)),
580  parser_errposition(pstate, location)));
581  }
582 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
List * args
Definition: primnodes.h:367
ParseState * parentParseState
Definition: parse_node.h:179
int errcode(int sqlerrcode)
Definition: elog.c:694
List * args
Definition: primnodes.h:325
bool p_hasAggs
Definition: parse_node.h:207
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:2967
#define ERROR
Definition: elog.h:45
int location
Definition: primnodes.h:337
Index agglevelsup
Definition: primnodes.h:333
List * aggdirectargs
Definition: primnodes.h:324
Index agglevelsup
Definition: primnodes.h:371
unsigned int Index
Definition: c.h:549
ParseExprKind p_expr_kind
Definition: parse_node.h:195
#define ereport(elevel,...)
Definition: elog.h:155
bool p_lateral_active
Definition: parse_node.h:187
int errmsg_internal(const char *fmt,...)
Definition: elog.c:992
#define Assert(condition)
Definition: c.h:804
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Expr * aggfilter
Definition: primnodes.h:328
static int check_agg_arguments(ParseState *pstate, List *directargs, List *args, Expr *filter)
Definition: parse_agg.c:610
Definition: pg_list.h:50
#define _(x)
Definition: elog.c:89

◆ 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 1246 of file parse_agg.c.

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().

1250 {
1252 
1253  context.pstate = pstate;
1254  context.qry = qry;
1255  context.hasJoinRTEs = false; /* assume caller flattened join Vars */
1256  context.groupClauses = groupClauses;
1257  context.groupClauseCommonVars = groupClauseCommonVars;
1258  context.have_non_var_grouping = have_non_var_grouping;
1259  context.func_grouped_rels = func_grouped_rels;
1260  context.sublevels_up = 0;
1261  context.in_agg_direct_args = false;
1262  check_ungrouped_columns_walker(node, &context);
1263 }
static bool check_ungrouped_columns_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1266

◆ check_ungrouped_columns_walker()

static bool check_ungrouped_columns_walker ( Node node,
check_ungrouped_columns_context context 
)
static

Definition at line 1266 of file parse_agg.c.

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().

1268 {
1269  ListCell *gl;
1270 
1271  if (node == NULL)
1272  return false;
1273  if (IsA(node, Const) ||
1274  IsA(node, Param))
1275  return false; /* constants are always acceptable */
1276 
1277  if (IsA(node, Aggref))
1278  {
1279  Aggref *agg = (Aggref *) node;
1280 
1281  if ((int) agg->agglevelsup == context->sublevels_up)
1282  {
1283  /*
1284  * If we find an aggregate call of the original level, do not
1285  * recurse into its normal arguments, ORDER BY arguments, or
1286  * filter; ungrouped vars there are not an error. But we should
1287  * check direct arguments as though they weren't in an aggregate.
1288  * We set a special flag in the context to help produce a useful
1289  * error message for ungrouped vars in direct arguments.
1290  */
1291  bool result;
1292 
1293  Assert(!context->in_agg_direct_args);
1294  context->in_agg_direct_args = true;
1296  context);
1297  context->in_agg_direct_args = false;
1298  return result;
1299  }
1300 
1301  /*
1302  * We can skip recursing into aggregates of higher levels altogether,
1303  * since they could not possibly contain Vars of concern to us (see
1304  * transformAggregateCall). We do need to look at aggregates of lower
1305  * levels, however.
1306  */
1307  if ((int) agg->agglevelsup > context->sublevels_up)
1308  return false;
1309  }
1310 
1311  if (IsA(node, GroupingFunc))
1312  {
1313  GroupingFunc *grp = (GroupingFunc *) node;
1314 
1315  /* handled GroupingFunc separately, no need to recheck at this level */
1316 
1317  if ((int) grp->agglevelsup >= context->sublevels_up)
1318  return false;
1319  }
1320 
1321  /*
1322  * If we have any GROUP BY items that are not simple Vars, check to see if
1323  * subexpression as a whole matches any GROUP BY item. We need to do this
1324  * at every recursion level so that we recognize GROUPed-BY expressions
1325  * before reaching variables within them. But this only works at the outer
1326  * query level, as noted above.
1327  */
1328  if (context->have_non_var_grouping && context->sublevels_up == 0)
1329  {
1330  foreach(gl, context->groupClauses)
1331  {
1332  TargetEntry *tle = lfirst(gl);
1333 
1334  if (equal(node, tle->expr))
1335  return false; /* acceptable, do not descend more */
1336  }
1337  }
1338 
1339  /*
1340  * If we have an ungrouped Var of the original query level, we have a
1341  * failure. Vars below the original query level are not a problem, and
1342  * neither are Vars from above it. (If such Vars are ungrouped as far as
1343  * their own query level is concerned, that's someone else's problem...)
1344  */
1345  if (IsA(node, Var))
1346  {
1347  Var *var = (Var *) node;
1348  RangeTblEntry *rte;
1349  char *attname;
1350 
1351  if (var->varlevelsup != context->sublevels_up)
1352  return false; /* it's not local to my query, ignore */
1353 
1354  /*
1355  * Check for a match, if we didn't do it above.
1356  */
1357  if (!context->have_non_var_grouping || context->sublevels_up != 0)
1358  {
1359  foreach(gl, context->groupClauses)
1360  {
1361  Var *gvar = (Var *) ((TargetEntry *) lfirst(gl))->expr;
1362 
1363  if (IsA(gvar, Var) &&
1364  gvar->varno == var->varno &&
1365  gvar->varattno == var->varattno &&
1366  gvar->varlevelsup == 0)
1367  return false; /* acceptable, we're okay */
1368  }
1369  }
1370 
1371  /*
1372  * Check whether the Var is known functionally dependent on the GROUP
1373  * BY columns. If so, we can allow the Var to be used, because the
1374  * grouping is really a no-op for this table. However, this deduction
1375  * depends on one or more constraints of the table, so we have to add
1376  * those constraints to the query's constraintDeps list, because it's
1377  * not semantically valid anymore if the constraint(s) get dropped.
1378  * (Therefore, this check must be the last-ditch effort before raising
1379  * error: we don't want to add dependencies unnecessarily.)
1380  *
1381  * Because this is a pretty expensive check, and will have the same
1382  * outcome for all columns of a table, we remember which RTEs we've
1383  * already proven functional dependency for in the func_grouped_rels
1384  * list. This test also prevents us from adding duplicate entries to
1385  * the constraintDeps list.
1386  */
1387  if (list_member_int(*context->func_grouped_rels, var->varno))
1388  return false; /* previously proven acceptable */
1389 
1390  Assert(var->varno > 0 &&
1391  (int) var->varno <= list_length(context->pstate->p_rtable));
1392  rte = rt_fetch(var->varno, context->pstate->p_rtable);
1393  if (rte->rtekind == RTE_RELATION)
1394  {
1396  var->varno,
1397  0,
1398  context->groupClauseCommonVars,
1399  &context->qry->constraintDeps))
1400  {
1401  *context->func_grouped_rels =
1402  lappend_int(*context->func_grouped_rels, var->varno);
1403  return false; /* acceptable */
1404  }
1405  }
1406 
1407  /* Found an ungrouped local variable; generate error message */
1408  attname = get_rte_attribute_name(rte, var->varattno);
1409  if (context->sublevels_up == 0)
1410  ereport(ERROR,
1411  (errcode(ERRCODE_GROUPING_ERROR),
1412  errmsg("column \"%s.%s\" must appear in the GROUP BY clause or be used in an aggregate function",
1413  rte->eref->aliasname, attname),
1414  context->in_agg_direct_args ?
1415  errdetail("Direct arguments of an ordered-set aggregate must use only grouped columns.") : 0,
1416  parser_errposition(context->pstate, var->location)));
1417  else
1418  ereport(ERROR,
1419  (errcode(ERRCODE_GROUPING_ERROR),
1420  errmsg("subquery uses ungrouped column \"%s.%s\" from outer query",
1421  rte->eref->aliasname, attname),
1422  parser_errposition(context->pstate, var->location)));
1423  }
1424 
1425  if (IsA(node, Query))
1426  {
1427  /* Recurse into subselects */
1428  bool result;
1429 
1430  context->sublevels_up++;
1431  result = query_tree_walker((Query *) node,
1433  (void *) context,
1434  0);
1435  context->sublevels_up--;
1436  return result;
1437  }
1439  (void *) context);
1440 }
bool check_functional_grouping(Oid relid, Index varno, Index varlevelsup, List *grouping_columns, List **constraintDeps)
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2336
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
static bool check_ungrouped_columns_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1266
Index varlevelsup
Definition: primnodes.h:191
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3073
List * constraintDeps
Definition: parsenodes.h:169
Definition: nodes.h:533
int errcode(int sqlerrcode)
Definition: elog.c:694
AttrNumber varattno
Definition: primnodes.h:186
Definition: primnodes.h:181
#define ERROR
Definition: elog.h:45
NameData attname
Definition: pg_attribute.h:41
bool list_member_int(const List *list, int datum)
Definition: list.c:669
int location
Definition: primnodes.h:196
int errdetail(const char *fmt,...)
Definition: elog.c:1038
Index agglevelsup
Definition: primnodes.h:333
List * aggdirectargs
Definition: primnodes.h:324
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
List * lappend_int(List *list, int datum)
Definition: list.c:354
Index varno
Definition: primnodes.h:184
Index agglevelsup
Definition: primnodes.h:371
#define ereport(elevel,...)
Definition: elog.h:155
char * get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1431
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
RTEKind rtekind
Definition: parsenodes.h:981
int errmsg(const char *fmt,...)
Definition: elog.c:905
Alias * eref
Definition: parsenodes.h:1120
List * p_rtable
Definition: parse_node.h:181

◆ cmp_list_len_asc()

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

Definition at line 1730 of file parse_agg.c.

References lfirst, and list_length().

Referenced by expand_grouping_sets().

1731 {
1732  int la = list_length((const List *) lfirst(a));
1733  int lb = list_length((const List *) lfirst(b));
1734 
1735  return (la > lb) ? 1 : (la == lb) ? 0 : -1;
1736 }
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
Definition: pg_list.h:50

◆ expand_grouping_sets()

List* expand_grouping_sets ( List groupingSets,
int  limit 
)

Definition at line 1746 of file parse_agg.c.

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

Referenced by parseCheckAggregates(), and preprocess_grouping_sets().

1747 {
1748  List *expanded_groups = NIL;
1749  List *result = NIL;
1750  double numsets = 1;
1751  ListCell *lc;
1752 
1753  if (groupingSets == NIL)
1754  return NIL;
1755 
1756  foreach(lc, groupingSets)
1757  {
1758  List *current_result = NIL;
1759  GroupingSet *gs = lfirst(lc);
1760 
1761  current_result = expand_groupingset_node(gs);
1762 
1763  Assert(current_result != NIL);
1764 
1765  numsets *= list_length(current_result);
1766 
1767  if (limit >= 0 && numsets > limit)
1768  return NIL;
1769 
1770  expanded_groups = lappend(expanded_groups, current_result);
1771  }
1772 
1773  /*
1774  * Do cartesian product between sublists of expanded_groups. While at it,
1775  * remove any duplicate elements from individual grouping sets (we must
1776  * NOT change the number of sets though)
1777  */
1778 
1779  foreach(lc, (List *) linitial(expanded_groups))
1780  {
1781  result = lappend(result, list_union_int(NIL, (List *) lfirst(lc)));
1782  }
1783 
1784  for_each_from(lc, expanded_groups, 1)
1785  {
1786  List *p = lfirst(lc);
1787  List *new_result = NIL;
1788  ListCell *lc2;
1789 
1790  foreach(lc2, result)
1791  {
1792  List *q = lfirst(lc2);
1793  ListCell *lc3;
1794 
1795  foreach(lc3, p)
1796  {
1797  new_result = lappend(new_result,
1798  list_union_int(q, (List *) lfirst(lc3)));
1799  }
1800  }
1801  result = new_result;
1802  }
1803 
1804  /* Now sort the lists by length */
1805  list_sort(result, cmp_list_len_asc);
1806 
1807  return result;
1808 }
#define NIL
Definition: pg_list.h:65
#define linitial(l)
Definition: pg_list.h:174
static List * expand_groupingset_node(GroupingSet *gs)
Definition: parse_agg.c:1628
List * list_union_int(const List *list1, const List *list2)
Definition: list.c:977
List * lappend(List *list, void *datum)
Definition: list.c:336
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
#define for_each_from(cell, lst, N)
Definition: pg_list.h:393
static int cmp_list_len_asc(const ListCell *a, const ListCell *b)
Definition: parse_agg.c:1730
void list_sort(List *list, list_sort_comparator cmp)
Definition: list.c:1496
Definition: pg_list.h:50

◆ expand_groupingset_node()

static List * expand_groupingset_node ( GroupingSet gs)
static

Definition at line 1628 of file parse_agg.c.

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().

1629 {
1630  List *result = NIL;
1631 
1632  switch (gs->kind)
1633  {
1634  case GROUPING_SET_EMPTY:
1635  result = list_make1(NIL);
1636  break;
1637 
1638  case GROUPING_SET_SIMPLE:
1639  result = list_make1(gs->content);
1640  break;
1641 
1642  case GROUPING_SET_ROLLUP:
1643  {
1644  List *rollup_val = gs->content;
1645  ListCell *lc;
1646  int curgroup_size = list_length(gs->content);
1647 
1648  while (curgroup_size > 0)
1649  {
1650  List *current_result = NIL;
1651  int i = curgroup_size;
1652 
1653  foreach(lc, rollup_val)
1654  {
1655  GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
1656 
1657  Assert(gs_current->kind == GROUPING_SET_SIMPLE);
1658 
1659  current_result = list_concat(current_result,
1660  gs_current->content);
1661 
1662  /* If we are done with making the current group, break */
1663  if (--i == 0)
1664  break;
1665  }
1666 
1667  result = lappend(result, current_result);
1668  --curgroup_size;
1669  }
1670 
1671  result = lappend(result, NIL);
1672  }
1673  break;
1674 
1675  case GROUPING_SET_CUBE:
1676  {
1677  List *cube_list = gs->content;
1678  int number_bits = list_length(cube_list);
1679  uint32 num_sets;
1680  uint32 i;
1681 
1682  /* parser should cap this much lower */
1683  Assert(number_bits < 31);
1684 
1685  num_sets = (1U << number_bits);
1686 
1687  for (i = 0; i < num_sets; i++)
1688  {
1689  List *current_result = NIL;
1690  ListCell *lc;
1691  uint32 mask = 1U;
1692 
1693  foreach(lc, cube_list)
1694  {
1695  GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
1696 
1697  Assert(gs_current->kind == GROUPING_SET_SIMPLE);
1698 
1699  if (mask & i)
1700  current_result = list_concat(current_result,
1701  gs_current->content);
1702 
1703  mask <<= 1;
1704  }
1705 
1706  result = lappend(result, current_result);
1707  }
1708  }
1709  break;
1710 
1711  case GROUPING_SET_SETS:
1712  {
1713  ListCell *lc;
1714 
1715  foreach(lc, gs->content)
1716  {
1717  List *current_result = expand_groupingset_node(lfirst(lc));
1718 
1719  result = list_concat(result, current_result);
1720  }
1721  }
1722  break;
1723  }
1724 
1725  return result;
1726 }
#define NIL
Definition: pg_list.h:65
List * content
Definition: parsenodes.h:1332
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
GroupingSetKind kind
Definition: parsenodes.h:1331
#define list_make1(x1)
Definition: pg_list.h:206
static List * expand_groupingset_node(GroupingSet *gs)
Definition: parse_agg.c:1628
unsigned int uint32
Definition: c.h:441
List * lappend(List *list, void *datum)
Definition: list.c:336
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
int i
Definition: pg_list.h:50

◆ 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 1454 of file parse_agg.c.

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().

1457 {
1459 
1460  context.pstate = pstate;
1461  context.qry = qry;
1462  context.hasJoinRTEs = hasJoinRTEs;
1463  context.groupClauses = groupClauses;
1464  context.groupClauseCommonVars = NIL;
1465  context.have_non_var_grouping = have_non_var_grouping;
1466  context.func_grouped_rels = NULL;
1467  context.sublevels_up = 0;
1468  context.in_agg_direct_args = false;
1469  finalize_grouping_exprs_walker(node, &context);
1470 }
#define NIL
Definition: pg_list.h:65
static bool finalize_grouping_exprs_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1473

◆ finalize_grouping_exprs_walker()

static bool finalize_grouping_exprs_walker ( Node node,
check_ungrouped_columns_context context 
)
static

Definition at line 1473 of file parse_agg.c.

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, 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(), GroupingFunc::refs, TargetEntry::ressortgroupref, check_ungrouped_columns_context::sublevels_up, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by finalize_grouping_exprs().

1475 {
1476  ListCell *gl;
1477 
1478  if (node == NULL)
1479  return false;
1480  if (IsA(node, Const) ||
1481  IsA(node, Param))
1482  return false; /* constants are always acceptable */
1483 
1484  if (IsA(node, Aggref))
1485  {
1486  Aggref *agg = (Aggref *) node;
1487 
1488  if ((int) agg->agglevelsup == context->sublevels_up)
1489  {
1490  /*
1491  * If we find an aggregate call of the original level, do not
1492  * recurse into its normal arguments, ORDER BY arguments, or
1493  * filter; GROUPING exprs of this level are not allowed there. But
1494  * check direct arguments as though they weren't in an aggregate.
1495  */
1496  bool result;
1497 
1498  Assert(!context->in_agg_direct_args);
1499  context->in_agg_direct_args = true;
1501  context);
1502  context->in_agg_direct_args = false;
1503  return result;
1504  }
1505 
1506  /*
1507  * We can skip recursing into aggregates of higher levels altogether,
1508  * since they could not possibly contain exprs of concern to us (see
1509  * transformAggregateCall). We do need to look at aggregates of lower
1510  * levels, however.
1511  */
1512  if ((int) agg->agglevelsup > context->sublevels_up)
1513  return false;
1514  }
1515 
1516  if (IsA(node, GroupingFunc))
1517  {
1518  GroupingFunc *grp = (GroupingFunc *) node;
1519 
1520  /*
1521  * We only need to check GroupingFunc nodes at the exact level to
1522  * which they belong, since they cannot mix levels in arguments.
1523  */
1524 
1525  if ((int) grp->agglevelsup == context->sublevels_up)
1526  {
1527  ListCell *lc;
1528  List *ref_list = NIL;
1529 
1530  foreach(lc, grp->args)
1531  {
1532  Node *expr = lfirst(lc);
1533  Index ref = 0;
1534 
1535  if (context->hasJoinRTEs)
1536  expr = flatten_join_alias_vars(context->qry, expr);
1537 
1538  /*
1539  * Each expression must match a grouping entry at the current
1540  * query level. Unlike the general expression case, we don't
1541  * allow functional dependencies or outer references.
1542  */
1543 
1544  if (IsA(expr, Var))
1545  {
1546  Var *var = (Var *) expr;
1547 
1548  if (var->varlevelsup == context->sublevels_up)
1549  {
1550  foreach(gl, context->groupClauses)
1551  {
1552  TargetEntry *tle = lfirst(gl);
1553  Var *gvar = (Var *) tle->expr;
1554 
1555  if (IsA(gvar, Var) &&
1556  gvar->varno == var->varno &&
1557  gvar->varattno == var->varattno &&
1558  gvar->varlevelsup == 0)
1559  {
1560  ref = tle->ressortgroupref;
1561  break;
1562  }
1563  }
1564  }
1565  }
1566  else if (context->have_non_var_grouping &&
1567  context->sublevels_up == 0)
1568  {
1569  foreach(gl, context->groupClauses)
1570  {
1571  TargetEntry *tle = lfirst(gl);
1572 
1573  if (equal(expr, tle->expr))
1574  {
1575  ref = tle->ressortgroupref;
1576  break;
1577  }
1578  }
1579  }
1580 
1581  if (ref == 0)
1582  ereport(ERROR,
1583  (errcode(ERRCODE_GROUPING_ERROR),
1584  errmsg("arguments to GROUPING must be grouping expressions of the associated query level"),
1585  parser_errposition(context->pstate,
1586  exprLocation(expr))));
1587 
1588  ref_list = lappend_int(ref_list, ref);
1589  }
1590 
1591  grp->refs = ref_list;
1592  }
1593 
1594  if ((int) grp->agglevelsup > context->sublevels_up)
1595  return false;
1596  }
1597 
1598  if (IsA(node, Query))
1599  {
1600  /* Recurse into subselects */
1601  bool result;
1602 
1603  context->sublevels_up++;
1604  result = query_tree_walker((Query *) node,
1606  (void *) context,
1607  0);
1608  context->sublevels_up--;
1609  return result;
1610  }
1612  (void *) context);
1613 }
#define NIL
Definition: pg_list.h:65
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2336
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
Index varlevelsup
Definition: primnodes.h:191
List * args
Definition: primnodes.h:367
List * refs
Definition: primnodes.h:369
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1231
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3073
Definition: nodes.h:533
int errcode(int sqlerrcode)
Definition: elog.c:694
AttrNumber varattno
Definition: primnodes.h:186
Definition: primnodes.h:181
#define ERROR
Definition: elog.h:45
static bool finalize_grouping_exprs_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1473
Index agglevelsup
Definition: primnodes.h:333
List * aggdirectargs
Definition: primnodes.h:324
List * lappend_int(List *list, int datum)
Definition: list.c:354
Index varno
Definition: primnodes.h:184
Index agglevelsup
Definition: primnodes.h:371
unsigned int Index
Definition: c.h:549
Node * flatten_join_alias_vars(Query *query, Node *node)
Definition: var.c:697
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Expr * expr
Definition: primnodes.h:1431
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1885
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:905
Index ressortgroupref
Definition: primnodes.h:1434
Definition: pg_list.h:50

◆ get_aggregate_argtypes()

int get_aggregate_argtypes ( Aggref aggref,
Oid inputTypes 
)

Definition at line 1826 of file parse_agg.c.

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

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

1827 {
1828  int numArguments = 0;
1829  ListCell *lc;
1830 
1832 
1833  foreach(lc, aggref->aggargtypes)
1834  {
1835  inputTypes[numArguments++] = lfirst_oid(lc);
1836  }
1837 
1838  return numArguments;
1839 }
#define FUNC_MAX_ARGS
List * aggargtypes
Definition: primnodes.h:323
#define Assert(condition)
Definition: c.h:804
static int list_length(const List *l)
Definition: pg_list.h:149
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ make_agg_arg()

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

Definition at line 2084 of file parse_agg.c.

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

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

2085 {
2086  Param *argp = makeNode(Param);
2087 
2088  argp->paramkind = PARAM_EXEC;
2089  argp->paramid = -1;
2090  argp->paramtype = argtype;
2091  argp->paramtypmod = -1;
2092  argp->paramcollid = argcollation;
2093  argp->location = -1;
2094  return (Node *) argp;
2095 }
ParamKind paramkind
Definition: primnodes.h:262
Definition: nodes.h:533
Oid paramcollid
Definition: primnodes.h:266
int location
Definition: primnodes.h:267
int32 paramtypmod
Definition: primnodes.h:265
#define makeNode(_type_)
Definition: nodes.h:581
int paramid
Definition: primnodes.h:263
Oid paramtype
Definition: primnodes.h:264

◆ parseCheckAggregates()

void parseCheckAggregates ( ParseState pstate,
Query qry 
)

Definition at line 1049 of file parse_agg.c.

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::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().

1050 {
1051  List *gset_common = NIL;
1052  List *groupClauses = NIL;
1053  List *groupClauseCommonVars = NIL;
1054  bool have_non_var_grouping;
1055  List *func_grouped_rels = NIL;
1056  ListCell *l;
1057  bool hasJoinRTEs;
1058  bool hasSelfRefRTEs;
1059  Node *clause;
1060 
1061  /* This should only be called if we found aggregates or grouping */
1062  Assert(pstate->p_hasAggs || qry->groupClause || qry->havingQual || qry->groupingSets);
1063 
1064  /*
1065  * If we have grouping sets, expand them and find the intersection of all
1066  * sets.
1067  */
1068  if (qry->groupingSets)
1069  {
1070  /*
1071  * The limit of 4096 is arbitrary and exists simply to avoid resource
1072  * issues from pathological constructs.
1073  */
1074  List *gsets = expand_grouping_sets(qry->groupingSets, 4096);
1075 
1076  if (!gsets)
1077  ereport(ERROR,
1078  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
1079  errmsg("too many grouping sets present (maximum 4096)"),
1080  parser_errposition(pstate,
1081  qry->groupClause
1082  ? exprLocation((Node *) qry->groupClause)
1083  : exprLocation((Node *) qry->groupingSets))));
1084 
1085  /*
1086  * The intersection will often be empty, so help things along by
1087  * seeding the intersect with the smallest set.
1088  */
1089  gset_common = linitial(gsets);
1090 
1091  if (gset_common)
1092  {
1093  for_each_from(l, gsets, 1)
1094  {
1095  gset_common = list_intersection_int(gset_common, lfirst(l));
1096  if (!gset_common)
1097  break;
1098  }
1099  }
1100 
1101  /*
1102  * If there was only one grouping set in the expansion, AND if the
1103  * groupClause is non-empty (meaning that the grouping set is not
1104  * empty either), then we can ditch the grouping set and pretend we
1105  * just had a normal GROUP BY.
1106  */
1107  if (list_length(gsets) == 1 && qry->groupClause)
1108  qry->groupingSets = NIL;
1109  }
1110 
1111  /*
1112  * Scan the range table to see if there are JOIN or self-reference CTE
1113  * entries. We'll need this info below.
1114  */
1115  hasJoinRTEs = hasSelfRefRTEs = false;
1116  foreach(l, pstate->p_rtable)
1117  {
1118  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
1119 
1120  if (rte->rtekind == RTE_JOIN)
1121  hasJoinRTEs = true;
1122  else if (rte->rtekind == RTE_CTE && rte->self_reference)
1123  hasSelfRefRTEs = true;
1124  }
1125 
1126  /*
1127  * Build a list of the acceptable GROUP BY expressions for use by
1128  * check_ungrouped_columns().
1129  *
1130  * We get the TLE, not just the expr, because GROUPING wants to know the
1131  * sortgroupref.
1132  */
1133  foreach(l, qry->groupClause)
1134  {
1135  SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
1136  TargetEntry *expr;
1137 
1138  expr = get_sortgroupclause_tle(grpcl, qry->targetList);
1139  if (expr == NULL)
1140  continue; /* probably cannot happen */
1141 
1142  groupClauses = lappend(groupClauses, expr);
1143  }
1144 
1145  /*
1146  * If there are join alias vars involved, we have to flatten them to the
1147  * underlying vars, so that aliased and unaliased vars will be correctly
1148  * taken as equal. We can skip the expense of doing this if no rangetable
1149  * entries are RTE_JOIN kind.
1150  */
1151  if (hasJoinRTEs)
1152  groupClauses = (List *) flatten_join_alias_vars(qry,
1153  (Node *) groupClauses);
1154 
1155  /*
1156  * Detect whether any of the grouping expressions aren't simple Vars; if
1157  * they're all Vars then we don't have to work so hard in the recursive
1158  * scans. (Note we have to flatten aliases before this.)
1159  *
1160  * Track Vars that are included in all grouping sets separately in
1161  * groupClauseCommonVars, since these are the only ones we can use to
1162  * check for functional dependencies.
1163  */
1164  have_non_var_grouping = false;
1165  foreach(l, groupClauses)
1166  {
1167  TargetEntry *tle = lfirst(l);
1168 
1169  if (!IsA(tle->expr, Var))
1170  {
1171  have_non_var_grouping = true;
1172  }
1173  else if (!qry->groupingSets ||
1174  list_member_int(gset_common, tle->ressortgroupref))
1175  {
1176  groupClauseCommonVars = lappend(groupClauseCommonVars, tle->expr);
1177  }
1178  }
1179 
1180  /*
1181  * Check the targetlist and HAVING clause for ungrouped variables.
1182  *
1183  * Note: because we check resjunk tlist elements as well as regular ones,
1184  * this will also find ungrouped variables that came from ORDER BY and
1185  * WINDOW clauses. For that matter, it's also going to examine the
1186  * grouping expressions themselves --- but they'll all pass the test ...
1187  *
1188  * We also finalize GROUPING expressions, but for that we need to traverse
1189  * the original (unflattened) clause in order to modify nodes.
1190  */
1191  clause = (Node *) qry->targetList;
1192  finalize_grouping_exprs(clause, pstate, qry,
1193  groupClauses, hasJoinRTEs,
1194  have_non_var_grouping);
1195  if (hasJoinRTEs)
1196  clause = flatten_join_alias_vars(qry, clause);
1197  check_ungrouped_columns(clause, pstate, qry,
1198  groupClauses, groupClauseCommonVars,
1199  have_non_var_grouping,
1200  &func_grouped_rels);
1201 
1202  clause = (Node *) qry->havingQual;
1203  finalize_grouping_exprs(clause, pstate, qry,
1204  groupClauses, hasJoinRTEs,
1205  have_non_var_grouping);
1206  if (hasJoinRTEs)
1207  clause = flatten_join_alias_vars(qry, clause);
1208  check_ungrouped_columns(clause, pstate, qry,
1209  groupClauses, groupClauseCommonVars,
1210  have_non_var_grouping,
1211  &func_grouped_rels);
1212 
1213  /*
1214  * Per spec, aggregates can't appear in a recursive term.
1215  */
1216  if (pstate->p_hasAggs && hasSelfRefRTEs)
1217  ereport(ERROR,
1218  (errcode(ERRCODE_INVALID_RECURSION),
1219  errmsg("aggregate functions are not allowed in a recursive query's recursive term"),
1220  parser_errposition(pstate,
1221  locate_agg_of_level((Node *) qry, 0))));
1222 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:384
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1231
List * list_intersection_int(const List *list1, const List *list2)
Definition: list.c:1059
List * groupingSets
Definition: parsenodes.h:150
Definition: nodes.h:533
static void finalize_grouping_exprs(Node *node, ParseState *pstate, Query *qry, List *groupClauses, bool hasJoinRTEs, bool have_non_var_grouping)
Definition: parse_agg.c:1454
int errcode(int sqlerrcode)
Definition: elog.c:694
bool p_hasAggs
Definition: parse_node.h:207
Definition: primnodes.h:181
List * targetList
Definition: parsenodes.h:140
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:45
bool list_member_int(const List *list, int datum)
Definition: list.c:669
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:1246
List * lappend(List *list, void *datum)
Definition: list.c:336
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:131
bool self_reference
Definition: parsenodes.h:1086
Node * flatten_join_alias_vars(Query *query, Node *node)
Definition: var.c:697
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Expr * expr
Definition: primnodes.h:1431
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define for_each_from(cell, lst, N)
Definition: pg_list.h:393
List * expand_grouping_sets(List *groupingSets, int limit)
Definition: parse_agg.c:1746
RTEKind rtekind
Definition: parsenodes.h:981
List * groupClause
Definition: parsenodes.h:148
int errmsg(const char *fmt,...)
Definition: elog.c:905
Index ressortgroupref
Definition: primnodes.h:1434
Node * havingQual
Definition: parsenodes.h:152
Definition: pg_list.h:50
List * p_rtable
Definition: parse_node.h:181

◆ resolve_aggregate_transtype()

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

Definition at line 1852 of file parse_agg.c.

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

Referenced by initialize_peragg(), and preprocess_aggref().

1856 {
1857  /* resolve actual type of transition state, if polymorphic */
1858  if (IsPolymorphicType(aggtranstype))
1859  {
1860  /* have to fetch the agg's declared input types... */
1861  Oid *declaredArgTypes;
1862  int agg_nargs;
1863 
1864  (void) get_func_signature(aggfuncid, &declaredArgTypes, &agg_nargs);
1865 
1866  /*
1867  * VARIADIC ANY aggs could have more actual than declared args, but
1868  * such extra args can't affect polymorphic type resolution.
1869  */
1870  Assert(agg_nargs <= numArguments);
1871 
1872  aggtranstype = enforce_generic_type_consistency(inputTypes,
1873  declaredArgTypes,
1874  agg_nargs,
1875  aggtranstype,
1876  false);
1877  pfree(declaredArgTypes);
1878  }
1879  return aggtranstype;
1880 }
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition: lsyscache.c:1667
unsigned int Oid
Definition: postgres_ext.h:31
void pfree(void *pointer)
Definition: mcxt.c:1057
#define Assert(condition)
Definition: c.h:804

◆ transformAggregateCall()

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

Definition at line 102 of file parse_agg.c.

References addTargetToSortList(), Aggref::aggargtypes, Aggref::aggdirectargs, Aggref::aggdistinct, Aggref::aggkind, Aggref::aggorder, arg, 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().

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 }
List * aggdistinct
Definition: primnodes.h:327
#define NIL
Definition: pg_list.h:65
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1231
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 * list_truncate(List *list, int new_size)
Definition: list.c:600
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:396
Definition: nodes.h:533
int errcode(int sqlerrcode)
Definition: elog.c:694
List * args
Definition: primnodes.h:325
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition: parse_agg.c:286
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1437
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
#define OidIsValid(objectId)
Definition: c.h:710
List * aggargtypes
Definition: primnodes.h:323
#define ERROR
Definition: elog.h:45
List * aggorder
Definition: primnodes.h:326
int errdetail(const char *fmt,...)
Definition: elog.c:1038
int p_next_resno
Definition: parse_node.h:196
List * aggdirectargs
Definition: primnodes.h:324
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
List * lappend(List *list, void *datum)
Definition: list.c:336
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:905
void * arg
char aggkind
Definition: primnodes.h:332
List * transformDistinctClause(ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21

◆ transformGroupingFunc()

Node* transformGroupingFunc ( ParseState pstate,
GroupingFunc p 
)

Definition at line 247 of file parse_agg.c.

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().

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 }
#define NIL
Definition: pg_list.h:65
List * args
Definition: primnodes.h:367
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
Definition: nodes.h:533
int errcode(int sqlerrcode)
Definition: elog.c:694
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition: parse_agg.c:286
#define ERROR
Definition: elog.h:45
List * lappend(List *list, void *datum)
Definition: list.c:336
ParseExprKind p_expr_kind
Definition: parse_node.h:195
#define ereport(elevel,...)
Definition: elog.h:155
#define makeNode(_type_)
Definition: nodes.h:581
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:905
Definition: pg_list.h:50

◆ transformWindowFuncCall()

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

Definition at line 802 of file parse_agg.c.

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_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_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(), WindowFunc::location, WindowDef::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().

804 {
805  const char *err;
806  bool errkind;
807 
808  /*
809  * A window function call can't contain another one (but aggs are OK). XXX
810  * is this required by spec, or just an unimplemented feature?
811  *
812  * Note: we don't need to check the filter expression here, because the
813  * context checks done below and in transformAggregateCall would have
814  * already rejected any window funcs or aggs within the filter.
815  */
816  if (pstate->p_hasWindowFuncs &&
817  contain_windowfuncs((Node *) wfunc->args))
818  ereport(ERROR,
819  (errcode(ERRCODE_WINDOWING_ERROR),
820  errmsg("window function calls cannot be nested"),
821  parser_errposition(pstate,
822  locate_windowfunc((Node *) wfunc->args))));
823 
824  /*
825  * Check to see if the window function is in an invalid place within the
826  * query.
827  *
828  * For brevity we support two schemes for reporting an error here: set
829  * "err" to a custom message, or set "errkind" true if the error context
830  * is sufficiently identified by what ParseExprKindName will return, *and*
831  * what it will return is just a SQL keyword. (Otherwise, use a custom
832  * message to avoid creating translation problems.)
833  */
834  err = NULL;
835  errkind = false;
836  switch (pstate->p_expr_kind)
837  {
838  case EXPR_KIND_NONE:
839  Assert(false); /* can't happen */
840  break;
841  case EXPR_KIND_OTHER:
842  /* Accept window func here; caller must throw error if wanted */
843  break;
844  case EXPR_KIND_JOIN_ON:
846  err = _("window functions are not allowed in JOIN conditions");
847  break;
849  /* can't get here, but just in case, throw an error */
850  errkind = true;
851  break;
853  err = _("window functions are not allowed in functions in FROM");
854  break;
855  case EXPR_KIND_WHERE:
856  errkind = true;
857  break;
858  case EXPR_KIND_POLICY:
859  err = _("window functions are not allowed in policy expressions");
860  break;
861  case EXPR_KIND_HAVING:
862  errkind = true;
863  break;
864  case EXPR_KIND_FILTER:
865  errkind = true;
866  break;
872  err = _("window functions are not allowed in window definitions");
873  break;
875  /* okay */
876  break;
880  errkind = true;
881  break;
882  case EXPR_KIND_GROUP_BY:
883  errkind = true;
884  break;
885  case EXPR_KIND_ORDER_BY:
886  /* okay */
887  break;
889  /* okay */
890  break;
891  case EXPR_KIND_LIMIT:
892  case EXPR_KIND_OFFSET:
893  errkind = true;
894  break;
895  case EXPR_KIND_RETURNING:
896  errkind = true;
897  break;
898  case EXPR_KIND_VALUES:
900  errkind = true;
901  break;
904  err = _("window functions are not allowed in check constraints");
905  break;
908  err = _("window functions are not allowed in DEFAULT expressions");
909  break;
911  err = _("window functions are not allowed in index expressions");
912  break;
914  err = _("window functions are not allowed in index predicates");
915  break;
917  err = _("window functions are not allowed in transform expressions");
918  break;
920  err = _("window functions are not allowed in EXECUTE parameters");
921  break;
923  err = _("window functions are not allowed in trigger WHEN conditions");
924  break;
926  err = _("window functions are not allowed in partition bound");
927  break;
929  err = _("window functions are not allowed in partition key expressions");
930  break;
932  err = _("window functions are not allowed in CALL arguments");
933  break;
935  err = _("window functions are not allowed in COPY FROM WHERE conditions");
936  break;
938  err = _("window functions are not allowed in column generation expressions");
939  break;
941  errkind = true;
942  break;
943 
944  /*
945  * There is intentionally no default: case here, so that the
946  * compiler will warn if we add a new ParseExprKind without
947  * extending this switch. If we do see an unrecognized value at
948  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
949  * which is sane anyway.
950  */
951  }
952  if (err)
953  ereport(ERROR,
954  (errcode(ERRCODE_WINDOWING_ERROR),
955  errmsg_internal("%s", err),
956  parser_errposition(pstate, wfunc->location)));
957  if (errkind)
958  ereport(ERROR,
959  (errcode(ERRCODE_WINDOWING_ERROR),
960  /* translator: %s is name of a SQL construct, eg GROUP BY */
961  errmsg("window functions are not allowed in %s",
962  ParseExprKindName(pstate->p_expr_kind)),
963  parser_errposition(pstate, wfunc->location)));
964 
965  /*
966  * If the OVER clause just specifies a window name, find that WINDOW
967  * clause (which had better be present). Otherwise, try to match all the
968  * properties of the OVER clause, and make a new entry in the p_windowdefs
969  * list if no luck.
970  */
971  if (windef->name)
972  {
973  Index winref = 0;
974  ListCell *lc;
975 
976  Assert(windef->refname == NULL &&
977  windef->partitionClause == NIL &&
978  windef->orderClause == NIL &&
980 
981  foreach(lc, pstate->p_windowdefs)
982  {
983  WindowDef *refwin = (WindowDef *) lfirst(lc);
984 
985  winref++;
986  if (refwin->name && strcmp(refwin->name, windef->name) == 0)
987  {
988  wfunc->winref = winref;
989  break;
990  }
991  }
992  if (lc == NULL) /* didn't find it? */
993  ereport(ERROR,
994  (errcode(ERRCODE_UNDEFINED_OBJECT),
995  errmsg("window \"%s\" does not exist", windef->name),
996  parser_errposition(pstate, windef->location)));
997  }
998  else
999  {
1000  Index winref = 0;
1001  ListCell *lc;
1002 
1003  foreach(lc, pstate->p_windowdefs)
1004  {
1005  WindowDef *refwin = (WindowDef *) lfirst(lc);
1006 
1007  winref++;
1008  if (refwin->refname && windef->refname &&
1009  strcmp(refwin->refname, windef->refname) == 0)
1010  /* matched on refname */ ;
1011  else if (!refwin->refname && !windef->refname)
1012  /* matched, no refname */ ;
1013  else
1014  continue;
1015  if (equal(refwin->partitionClause, windef->partitionClause) &&
1016  equal(refwin->orderClause, windef->orderClause) &&
1017  refwin->frameOptions == windef->frameOptions &&
1018  equal(refwin->startOffset, windef->startOffset) &&
1019  equal(refwin->endOffset, windef->endOffset))
1020  {
1021  /* found a duplicate window specification */
1022  wfunc->winref = winref;
1023  break;
1024  }
1025  }
1026  if (lc == NULL) /* didn't find it? */
1027  {
1028  pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
1029  wfunc->winref = list_length(pstate->p_windowdefs);
1030  }
1031  }
1032 
1033  pstate->p_hasWindowFuncs = true;
1034 }
List * partitionClause
Definition: parsenodes.h:490
#define NIL
Definition: pg_list.h:65
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:532
List * args
Definition: primnodes.h:385
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3073
int frameOptions
Definition: parsenodes.h:492
char * name
Definition: parsenodes.h:488
Definition: nodes.h:533
int errcode(int sqlerrcode)
Definition: elog.c:694
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
Index winref
Definition: primnodes.h:387
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:2967
bool p_hasWindowFuncs
Definition: parse_node.h:208
Node * startOffset
Definition: parsenodes.h:493
#define ERROR
Definition: elog.h:45
int location
Definition: parsenodes.h:495
List * p_windowdefs
Definition: parse_node.h:194
Node * endOffset
Definition: parsenodes.h:494
List * lappend(List *list, void *datum)
Definition: list.c:336
List * orderClause
Definition: parsenodes.h:491
unsigned int Index
Definition: c.h:549
ParseExprKind p_expr_kind
Definition: parse_node.h:195
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:992
int location
Definition: primnodes.h:390
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:905
char * refname
Definition: parsenodes.h:489
#define _(x)
Definition: elog.c:89
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197