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

2032 {
2033  Node *argp;
2034  List *args;
2035  FuncExpr *fexpr;
2036 
2037  /* combinefn takes two arguments of the aggregate state type */
2038  argp = make_agg_arg(agg_state_type, agg_input_collation);
2039 
2040  args = list_make2(argp, argp);
2041 
2042  fexpr = makeFuncExpr(combinefn_oid,
2043  agg_state_type,
2044  args,
2045  InvalidOid,
2046  agg_input_collation,
2048  /* combinefn is currently never treated as variadic */
2049  *combinefnexpr = (Expr *) fexpr;
2050 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2144
Definition: nodes.h:539
#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 2080 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().

2082 {
2083  List *args;
2084  FuncExpr *fexpr;
2085 
2086  /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2087  args = list_make2(make_agg_arg(BYTEAOID, InvalidOid),
2088  make_agg_arg(INTERNALOID, InvalidOid));
2089 
2090  fexpr = makeFuncExpr(deserialfn_oid,
2091  INTERNALOID,
2092  args,
2093  InvalidOid,
2094  InvalidOid,
2096  *deserialfnexpr = (Expr *) fexpr;
2097 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2144
#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 2104 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().

2111 {
2112  List *args;
2113  int i;
2114 
2115  /*
2116  * Build expr tree for final function
2117  */
2118  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2119 
2120  /* finalfn may take additional args, which match agg's input types */
2121  for (i = 0; i < num_finalfn_inputs - 1; i++)
2122  {
2123  args = lappend(args,
2124  make_agg_arg(agg_input_types[i], agg_input_collation));
2125  }
2126 
2127  *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2128  agg_result_type,
2129  args,
2130  InvalidOid,
2131  agg_input_collation,
2133  /* finalfn is currently never treated as variadic */
2134 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2144
#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 2057 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().

2059 {
2060  List *args;
2061  FuncExpr *fexpr;
2062 
2063  /* serialfn always takes INTERNAL and returns BYTEA */
2064  args = list_make1(make_agg_arg(INTERNALOID, InvalidOid));
2065 
2066  fexpr = makeFuncExpr(serialfn_oid,
2067  BYTEAOID,
2068  args,
2069  InvalidOid,
2070  InvalidOid,
2072  *serialfnexpr = (Expr *) fexpr;
2073 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2144
#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 1967 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().

1977 {
1978  List *args;
1979  FuncExpr *fexpr;
1980  int i;
1981 
1982  /*
1983  * Build arg list to use in the transfn FuncExpr node.
1984  */
1985  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
1986 
1987  for (i = agg_num_direct_inputs; i < agg_num_inputs; i++)
1988  {
1989  args = lappend(args,
1990  make_agg_arg(agg_input_types[i], agg_input_collation));
1991  }
1992 
1993  fexpr = makeFuncExpr(transfn_oid,
1994  agg_state_type,
1995  args,
1996  InvalidOid,
1997  agg_input_collation,
1999  fexpr->funcvariadic = agg_variadic;
2000  *transfnexpr = (Expr *) fexpr;
2001 
2002  /*
2003  * Build invtransfn expression if requested, with same args as transfn
2004  */
2005  if (invtransfnexpr != NULL)
2006  {
2007  if (OidIsValid(invtransfn_oid))
2008  {
2009  fexpr = makeFuncExpr(invtransfn_oid,
2010  agg_state_type,
2011  args,
2012  InvalidOid,
2013  agg_input_collation,
2015  fexpr->funcvariadic = agg_variadic;
2016  *invtransfnexpr = (Expr *) fexpr;
2017  }
2018  else
2019  *invtransfnexpr = NULL;
2020  }
2021 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2144
#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:498
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 617 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().

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

◆ 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.

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

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 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2355
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
int errhint(const char *fmt,...)
Definition: elog.c:1156
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1250
int errcode(int sqlerrcode)
Definition: elog.c:698
Definition: primnodes.h:186
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1904
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:909
static bool check_agg_arguments_walker(Node *node, check_agg_arguments_context *context)
Definition: parse_agg.c:705

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

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 statistics expressions");
491  else
492  err = _("grouping operations are not allowed in statistics expressions");
493 
494  break;
496  if (isAgg)
497  err = _("aggregate functions are not allowed in transform expressions");
498  else
499  err = _("grouping operations are not allowed in transform expressions");
500 
501  break;
503  if (isAgg)
504  err = _("aggregate functions are not allowed in EXECUTE parameters");
505  else
506  err = _("grouping operations are not allowed in EXECUTE parameters");
507 
508  break;
510  if (isAgg)
511  err = _("aggregate functions are not allowed in trigger WHEN conditions");
512  else
513  err = _("grouping operations are not allowed in trigger WHEN conditions");
514 
515  break;
517  if (isAgg)
518  err = _("aggregate functions are not allowed in partition bound");
519  else
520  err = _("grouping operations are not allowed in partition bound");
521 
522  break;
524  if (isAgg)
525  err = _("aggregate functions are not allowed in partition key expressions");
526  else
527  err = _("grouping operations are not allowed in partition key expressions");
528 
529  break;
531 
532  if (isAgg)
533  err = _("aggregate functions are not allowed in column generation expressions");
534  else
535  err = _("grouping operations are not allowed in column generation expressions");
536 
537  break;
538 
540  if (isAgg)
541  err = _("aggregate functions are not allowed in CALL arguments");
542  else
543  err = _("grouping operations are not allowed in CALL arguments");
544 
545  break;
546 
548  if (isAgg)
549  err = _("aggregate functions are not allowed in COPY FROM WHERE conditions");
550  else
551  err = _("grouping operations are not allowed in COPY FROM WHERE conditions");
552 
553  break;
554 
556  errkind = true;
557  break;
558 
559  /*
560  * There is intentionally no default: case here, so that the
561  * compiler will warn if we add a new ParseExprKind without
562  * extending this switch. If we do see an unrecognized value at
563  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
564  * which is sane anyway.
565  */
566  }
567 
568  if (err)
569  ereport(ERROR,
570  (errcode(ERRCODE_GROUPING_ERROR),
571  errmsg_internal("%s", err),
572  parser_errposition(pstate, location)));
573 
574  if (errkind)
575  {
576  if (isAgg)
577  /* translator: %s is name of a SQL construct, eg GROUP BY */
578  err = _("aggregate functions are not allowed in %s");
579  else
580  /* translator: %s is name of a SQL construct, eg GROUP BY */
581  err = _("grouping operations are not allowed in %s");
582 
583  ereport(ERROR,
584  (errcode(ERRCODE_GROUPING_ERROR),
585  errmsg_internal(err,
586  ParseExprKindName(pstate->p_expr_kind)),
587  parser_errposition(pstate, location)));
588  }
589 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
List * args
Definition: primnodes.h:372
ParseState * parentParseState
Definition: parse_node.h:180
int errcode(int sqlerrcode)
Definition: elog.c:698
List * args
Definition: primnodes.h:330
bool p_hasAggs
Definition: parse_node.h:208
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3006
#define ERROR
Definition: elog.h:46
int location
Definition: primnodes.h:342
Index agglevelsup
Definition: primnodes.h:338
List * aggdirectargs
Definition: primnodes.h:329
Index agglevelsup
Definition: primnodes.h:376
unsigned int Index
Definition: c.h:549
ParseExprKind p_expr_kind
Definition: parse_node.h:196
#define ereport(elevel,...)
Definition: elog.h:157
bool p_lateral_active
Definition: parse_node.h:188
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define Assert(condition)
Definition: c.h:804
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Expr * aggfilter
Definition: primnodes.h:333
static int check_agg_arguments(ParseState *pstate, List *directargs, List *args, Expr *filter)
Definition: parse_agg.c:617
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 1256 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().

1260 {
1262 
1263  context.pstate = pstate;
1264  context.qry = qry;
1265  context.hasJoinRTEs = false; /* assume caller flattened join Vars */
1266  context.groupClauses = groupClauses;
1267  context.groupClauseCommonVars = groupClauseCommonVars;
1268  context.have_non_var_grouping = have_non_var_grouping;
1269  context.func_grouped_rels = func_grouped_rels;
1270  context.sublevels_up = 0;
1271  context.in_agg_direct_args = false;
1272  check_ungrouped_columns_walker(node, &context);
1273 }
static bool check_ungrouped_columns_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1276

◆ check_ungrouped_columns_walker()

static bool check_ungrouped_columns_walker ( Node node,
check_ungrouped_columns_context context 
)
static

Definition at line 1276 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().

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

◆ cmp_list_len_asc()

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

Definition at line 1740 of file parse_agg.c.

References lfirst, and list_length().

Referenced by cmp_list_len_contents_asc(), and expand_grouping_sets().

1741 {
1742  int la = list_length((const List *) lfirst(a));
1743  int lb = list_length((const List *) lfirst(b));
1744 
1745  return (la > lb) ? 1 : (la == lb) ? 0 : -1;
1746 }
#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

◆ cmp_list_len_contents_asc()

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

Definition at line 1750 of file parse_agg.c.

References cmp_list_len_asc(), forboth, lca(), lfirst, and lfirst_int.

Referenced by expand_grouping_sets().

1751 {
1752  int res = cmp_list_len_asc(a, b);
1753 
1754  if (res == 0)
1755  {
1756  List *la = (List *) lfirst(a);
1757  List *lb = (List *) lfirst(b);
1758  ListCell *lca;
1759  ListCell *lcb;
1760 
1761  forboth(lca, la, lcb, lb)
1762  {
1763  int va = lfirst_int(lca);
1764  int vb = lfirst_int(lcb);
1765  if (va > vb)
1766  return 1;
1767  if (va < vb)
1768  return -1;
1769  }
1770  }
1771 
1772  return res;
1773 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
#define lfirst_int(lc)
Definition: pg_list.h:170
#define lfirst(lc)
Definition: pg_list.h:169
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:1740
Definition: pg_list.h:50

◆ expand_grouping_sets()

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

Definition at line 1783 of file parse_agg.c.

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

Referenced by parseCheckAggregates(), and preprocess_grouping_sets().

1784 {
1785  List *expanded_groups = NIL;
1786  List *result = NIL;
1787  double numsets = 1;
1788  ListCell *lc;
1789 
1790  if (groupingSets == NIL)
1791  return NIL;
1792 
1793  foreach(lc, groupingSets)
1794  {
1795  List *current_result = NIL;
1796  GroupingSet *gs = lfirst(lc);
1797 
1798  current_result = expand_groupingset_node(gs);
1799 
1800  Assert(current_result != NIL);
1801 
1802  numsets *= list_length(current_result);
1803 
1804  if (limit >= 0 && numsets > limit)
1805  return NIL;
1806 
1807  expanded_groups = lappend(expanded_groups, current_result);
1808  }
1809 
1810  /*
1811  * Do cartesian product between sublists of expanded_groups. While at it,
1812  * remove any duplicate elements from individual grouping sets (we must
1813  * NOT change the number of sets though)
1814  */
1815 
1816  foreach(lc, (List *) linitial(expanded_groups))
1817  {
1818  result = lappend(result, list_union_int(NIL, (List *) lfirst(lc)));
1819  }
1820 
1821  for_each_from(lc, expanded_groups, 1)
1822  {
1823  List *p = lfirst(lc);
1824  List *new_result = NIL;
1825  ListCell *lc2;
1826 
1827  foreach(lc2, result)
1828  {
1829  List *q = lfirst(lc2);
1830  ListCell *lc3;
1831 
1832  foreach(lc3, p)
1833  {
1834  new_result = lappend(new_result,
1835  list_union_int(q, (List *) lfirst(lc3)));
1836  }
1837  }
1838  result = new_result;
1839  }
1840 
1841  /* Now sort the lists by length and deduplicate if necessary */
1842  if (!groupDistinct || list_length(result) < 2)
1843  list_sort(result, cmp_list_len_asc);
1844  else
1845  {
1846  ListCell *cell;
1847  List *prev;
1848 
1849  /* Sort each groupset individually */
1850  foreach(cell, result)
1851  list_sort(lfirst(cell), list_int_cmp);
1852 
1853  /* Now sort the list of groupsets by length and contents */
1855 
1856  /* Finally, remove duplicates */
1857  prev = linitial_node(List, result);
1858  for_each_from(cell, result, 1)
1859  {
1860  if (equal(lfirst(cell), prev))
1861  result = foreach_delete_current(result, cell);
1862  else
1863  prev = lfirst(cell);
1864  }
1865  }
1866 
1867  return result;
1868 }
#define NIL
Definition: pg_list.h:65
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3113
#define linitial_node(type, l)
Definition: pg_list.h:177
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:369
#define linitial(l)
Definition: pg_list.h:174
static List * expand_groupingset_node(GroupingSet *gs)
Definition: parse_agg.c:1638
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_contents_asc(const ListCell *a, const ListCell *b)
Definition: parse_agg.c:1750
static int cmp_list_len_asc(const ListCell *a, const ListCell *b)
Definition: parse_agg.c:1740
void list_sort(List *list, list_sort_comparator cmp)
Definition: list.c:1496
int list_int_cmp(const ListCell *p1, const ListCell *p2)
Definition: list.c:1513
Definition: pg_list.h:50

◆ expand_groupingset_node()

static List * expand_groupingset_node ( GroupingSet gs)
static

Definition at line 1638 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().

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

1467 {
1469 
1470  context.pstate = pstate;
1471  context.qry = qry;
1472  context.hasJoinRTEs = hasJoinRTEs;
1473  context.groupClauses = groupClauses;
1474  context.groupClauseCommonVars = NIL;
1475  context.have_non_var_grouping = have_non_var_grouping;
1476  context.func_grouped_rels = NULL;
1477  context.sublevels_up = 0;
1478  context.in_agg_direct_args = false;
1479  finalize_grouping_exprs_walker(node, &context);
1480 }
#define NIL
Definition: pg_list.h:65
static bool finalize_grouping_exprs_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1483

◆ finalize_grouping_exprs_walker()

static bool finalize_grouping_exprs_walker ( Node node,
check_ungrouped_columns_context context 
)
static

Definition at line 1483 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().

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

◆ get_aggregate_argtypes()

int get_aggregate_argtypes ( Aggref aggref,
Oid inputTypes 
)

Definition at line 1886 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().

1887 {
1888  int numArguments = 0;
1889  ListCell *lc;
1890 
1892 
1893  foreach(lc, aggref->aggargtypes)
1894  {
1895  inputTypes[numArguments++] = lfirst_oid(lc);
1896  }
1897 
1898  return numArguments;
1899 }
#define FUNC_MAX_ARGS
List * aggargtypes
Definition: primnodes.h:328
#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 2144 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().

2145 {
2146  Param *argp = makeNode(Param);
2147 
2148  argp->paramkind = PARAM_EXEC;
2149  argp->paramid = -1;
2150  argp->paramtype = argtype;
2151  argp->paramtypmod = -1;
2152  argp->paramcollid = argcollation;
2153  argp->location = -1;
2154  return (Node *) argp;
2155 }
ParamKind paramkind
Definition: primnodes.h:267
Definition: nodes.h:539
Oid paramcollid
Definition: primnodes.h:271
int location
Definition: primnodes.h:272
int32 paramtypmod
Definition: primnodes.h:270
#define makeNode(_type_)
Definition: nodes.h:587
int paramid
Definition: primnodes.h:268
Oid paramtype
Definition: primnodes.h:269

◆ parseCheckAggregates()

void parseCheckAggregates ( ParseState pstate,
Query qry 
)

Definition at line 1059 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::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().

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

◆ resolve_aggregate_transtype()

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

Definition at line 1912 of file parse_agg.c.

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

Referenced by initialize_peragg(), and preprocess_aggref().

1916 {
1917  /* resolve actual type of transition state, if polymorphic */
1918  if (IsPolymorphicType(aggtranstype))
1919  {
1920  /* have to fetch the agg's declared input types... */
1921  Oid *declaredArgTypes;
1922  int agg_nargs;
1923 
1924  (void) get_func_signature(aggfuncid, &declaredArgTypes, &agg_nargs);
1925 
1926  /*
1927  * VARIADIC ANY aggs could have more actual than declared args, but
1928  * such extra args can't affect polymorphic type resolution.
1929  */
1930  Assert(agg_nargs <= numArguments);
1931 
1932  aggtranstype = enforce_generic_type_consistency(inputTypes,
1933  declaredArgTypes,
1934  agg_nargs,
1935  aggtranstype,
1936  false);
1937  pfree(declaredArgTypes);
1938  }
1939  return aggtranstype;
1940 }
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:1169
#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:332
#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:1250
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:368
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
List * args
Definition: primnodes.h:330
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:328
#define ERROR
Definition: elog.h:46
List * aggorder
Definition: primnodes.h:331
int errdetail(const char *fmt,...)
Definition: elog.c:1042
int p_next_resno
Definition: parse_node.h:197
List * aggdirectargs
Definition: primnodes.h:329
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:157
#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:909
void * arg
char aggkind
Definition: primnodes.h:337
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:372
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition: parse_agg.c:286
#define ERROR
Definition: elog.h:46
List * lappend(List *list, void *datum)
Definition: list.c:336
ParseExprKind p_expr_kind
Definition: parse_node.h:196
#define ereport(elevel,...)
Definition: elog.h:157
#define makeNode(_type_)
Definition: nodes.h:587
#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:909
Definition: pg_list.h:50

◆ transformWindowFuncCall()

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

Definition at line 809 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_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(), 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().

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;
889  case EXPR_KIND_GROUP_BY:
890  errkind = true;
891  break;
892  case EXPR_KIND_ORDER_BY:
893  /* okay */
894  break;
896  /* okay */
897  break;
898  case EXPR_KIND_LIMIT:
899  case EXPR_KIND_OFFSET:
900  errkind = true;
901  break;
902  case EXPR_KIND_RETURNING:
903  errkind = true;
904  break;
905  case EXPR_KIND_VALUES:
907  errkind = true;
908  break;
911  err = _("window functions are not allowed in check constraints");
912  break;
915  err = _("window functions are not allowed in DEFAULT expressions");
916  break;
918  err = _("window functions are not allowed in index expressions");
919  break;
921  err = _("window functions are not allowed in statistics expressions");
922  break;
924  err = _("window functions are not allowed in index predicates");
925  break;
927  err = _("window functions are not allowed in transform expressions");
928  break;
930  err = _("window functions are not allowed in EXECUTE parameters");
931  break;
933  err = _("window functions are not allowed in trigger WHEN conditions");
934  break;
936  err = _("window functions are not allowed in partition bound");
937  break;
939  err = _("window functions are not allowed in partition key expressions");
940  break;
942  err = _("window functions are not allowed in CALL arguments");
943  break;
945  err = _("window functions are not allowed in COPY FROM WHERE conditions");
946  break;
948  err = _("window functions are not allowed in column generation expressions");
949  break;
951  errkind = true;
952  break;
953 
954  /*
955  * There is intentionally no default: case here, so that the
956  * compiler will warn if we add a new ParseExprKind without
957  * extending this switch. If we do see an unrecognized value at
958  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
959  * which is sane anyway.
960  */
961  }
962  if (err)
963  ereport(ERROR,
964  (errcode(ERRCODE_WINDOWING_ERROR),
965  errmsg_internal("%s", err),
966  parser_errposition(pstate, wfunc->location)));
967  if (errkind)
968  ereport(ERROR,
969  (errcode(ERRCODE_WINDOWING_ERROR),
970  /* translator: %s is name of a SQL construct, eg GROUP BY */
971  errmsg("window functions are not allowed in %s",
972  ParseExprKindName(pstate->p_expr_kind)),
973  parser_errposition(pstate, wfunc->location)));
974 
975  /*
976  * If the OVER clause just specifies a window name, find that WINDOW
977  * clause (which had better be present). Otherwise, try to match all the
978  * properties of the OVER clause, and make a new entry in the p_windowdefs
979  * list if no luck.
980  */
981  if (windef->name)
982  {
983  Index winref = 0;
984  ListCell *lc;
985 
986  Assert(windef->refname == NULL &&
987  windef->partitionClause == NIL &&
988  windef->orderClause == NIL &&
990 
991  foreach(lc, pstate->p_windowdefs)
992  {
993  WindowDef *refwin = (WindowDef *) lfirst(lc);
994 
995  winref++;
996  if (refwin->name && strcmp(refwin->name, windef->name) == 0)
997  {
998  wfunc->winref = winref;
999  break;
1000  }
1001  }
1002  if (lc == NULL) /* didn't find it? */
1003  ereport(ERROR,
1004  (errcode(ERRCODE_UNDEFINED_OBJECT),
1005  errmsg("window \"%s\" does not exist", windef->name),
1006  parser_errposition(pstate, windef->location)));
1007  }
1008  else
1009  {
1010  Index winref = 0;
1011  ListCell *lc;
1012 
1013  foreach(lc, pstate->p_windowdefs)
1014  {
1015  WindowDef *refwin = (WindowDef *) lfirst(lc);
1016 
1017  winref++;
1018  if (refwin->refname && windef->refname &&
1019  strcmp(refwin->refname, windef->refname) == 0)
1020  /* matched on refname */ ;
1021  else if (!refwin->refname && !windef->refname)
1022  /* matched, no refname */ ;
1023  else
1024  continue;
1025  if (equal(refwin->partitionClause, windef->partitionClause) &&
1026  equal(refwin->orderClause, windef->orderClause) &&
1027  refwin->frameOptions == windef->frameOptions &&
1028  equal(refwin->startOffset, windef->startOffset) &&
1029  equal(refwin->endOffset, windef->endOffset))
1030  {
1031  /* found a duplicate window specification */
1032  wfunc->winref = winref;
1033  break;
1034  }
1035  }
1036  if (lc == NULL) /* didn't find it? */
1037  {
1038  pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
1039  wfunc->winref = list_length(pstate->p_windowdefs);
1040  }
1041  }
1042 
1043  pstate->p_hasWindowFuncs = true;
1044 }
List * partitionClause
Definition: parsenodes.h:501
#define NIL
Definition: pg_list.h:65
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:543
List * args
Definition: primnodes.h:390
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3113
int frameOptions
Definition: parsenodes.h:503
char * name
Definition: parsenodes.h:499
Definition: nodes.h:539
int errcode(int sqlerrcode)
Definition: elog.c:698
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
Index winref
Definition: primnodes.h:392
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3006
bool p_hasWindowFuncs
Definition: parse_node.h:209
Node * startOffset
Definition: parsenodes.h:504
#define ERROR
Definition: elog.h:46
int location
Definition: parsenodes.h:506
List * p_windowdefs
Definition: parse_node.h:195
Node * endOffset
Definition: parsenodes.h:505
List * lappend(List *list, void *datum)
Definition: list.c:336
List * orderClause
Definition: parsenodes.h:502
unsigned int Index
Definition: c.h:549
ParseExprKind p_expr_kind
Definition: parse_node.h:196
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
int location
Definition: primnodes.h:395
#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:909
char * refname
Definition: parsenodes.h:500
#define _(x)
Definition: elog.c:89
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197