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 *groupClauseVars, 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, PlannerInfo *root, 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 void *a, const void *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 1954 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().

1958 {
1959  Node *argp;
1960  List *args;
1961  FuncExpr *fexpr;
1962 
1963  /* combinefn takes two arguments of the aggregate state type */
1964  argp = make_agg_arg(agg_state_type, agg_input_collation);
1965 
1966  args = list_make2(argp, argp);
1967 
1968  fexpr = makeFuncExpr(combinefn_oid,
1969  agg_state_type,
1970  args,
1971  InvalidOid,
1972  agg_input_collation,
1974  /* combinefn is currently never treated as variadic */
1975  *combinefnexpr = (Expr *) fexpr;
1976 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2070
Definition: nodes.h:512
#define InvalidOid
Definition: postgres_ext.h:36
Definition: pg_list.h:45
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 2006 of file parse_agg.c.

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

Referenced by build_pertrans_for_aggref().

2008 {
2009  List *args;
2010  FuncExpr *fexpr;
2011 
2012  /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2015 
2016  fexpr = makeFuncExpr(deserialfn_oid,
2017  INTERNALOID,
2018  args,
2019  InvalidOid,
2020  InvalidOid,
2022  *deserialfnexpr = (Expr *) fexpr;
2023 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2070
#define InvalidOid
Definition: postgres_ext.h:36
#define INTERNALOID
Definition: pg_type.h:698
#define BYTEAOID
Definition: pg_type.h:292
Definition: pg_list.h:45
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 2030 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().

2037 {
2038  List *args;
2039  int i;
2040 
2041  /*
2042  * Build expr tree for final function
2043  */
2044  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2045 
2046  /* finalfn may take additional args, which match agg's input types */
2047  for (i = 0; i < num_finalfn_inputs - 1; i++)
2048  {
2049  args = lappend(args,
2050  make_agg_arg(agg_input_types[i], agg_input_collation));
2051  }
2052 
2053  *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2054  agg_result_type,
2055  args,
2056  InvalidOid,
2057  agg_input_collation,
2059  /* finalfn is currently never treated as variadic */
2060 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2070
#define list_make1(x1)
Definition: pg_list.h:139
List * lappend(List *list, void *datum)
Definition: list.c:128
#define InvalidOid
Definition: postgres_ext.h:36
int i
Definition: pg_list.h:45
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 1983 of file parse_agg.c.

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

Referenced by build_pertrans_for_aggref().

1985 {
1986  List *args;
1987  FuncExpr *fexpr;
1988 
1989  /* serialfn always takes INTERNAL and returns BYTEA */
1991 
1992  fexpr = makeFuncExpr(serialfn_oid,
1993  BYTEAOID,
1994  args,
1995  InvalidOid,
1996  InvalidOid,
1998  *serialfnexpr = (Expr *) fexpr;
1999 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2070
#define list_make1(x1)
Definition: pg_list.h:139
#define InvalidOid
Definition: postgres_ext.h:36
#define INTERNALOID
Definition: pg_type.h:698
#define BYTEAOID
Definition: pg_type.h:292
Definition: pg_list.h:45
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 1893 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().

1903 {
1904  List *args;
1905  FuncExpr *fexpr;
1906  int i;
1907 
1908  /*
1909  * Build arg list to use in the transfn FuncExpr node.
1910  */
1911  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
1912 
1913  for (i = agg_num_direct_inputs; i < agg_num_inputs; i++)
1914  {
1915  args = lappend(args,
1916  make_agg_arg(agg_input_types[i], agg_input_collation));
1917  }
1918 
1919  fexpr = makeFuncExpr(transfn_oid,
1920  agg_state_type,
1921  args,
1922  InvalidOid,
1923  agg_input_collation,
1925  fexpr->funcvariadic = agg_variadic;
1926  *transfnexpr = (Expr *) fexpr;
1927 
1928  /*
1929  * Build invtransfn expression if requested, with same args as transfn
1930  */
1931  if (invtransfnexpr != NULL)
1932  {
1933  if (OidIsValid(invtransfn_oid))
1934  {
1935  fexpr = makeFuncExpr(invtransfn_oid,
1936  agg_state_type,
1937  args,
1938  InvalidOid,
1939  agg_input_collation,
1941  fexpr->funcvariadic = agg_variadic;
1942  *invtransfnexpr = (Expr *) fexpr;
1943  }
1944  else
1945  *invtransfnexpr = NULL;
1946  }
1947 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2070
#define OidIsValid(objectId)
Definition: c.h:576
#define list_make1(x1)
Definition: pg_list.h:139
List * lappend(List *list, void *datum)
Definition: list.c:128
#define InvalidOid
Definition: postgres_ext.h:36
int i
Definition: pg_list.h:45
bool funcvariadic
Definition: primnodes.h:452
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 577 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().

581 {
582  int agglevel;
584 
585  context.pstate = pstate;
586  context.min_varlevel = -1; /* signifies nothing found yet */
587  context.min_agglevel = -1;
588  context.sublevels_up = 0;
589 
590  (void) expression_tree_walker((Node *) args,
592  (void *) &context);
593 
594  (void) expression_tree_walker((Node *) filter,
596  (void *) &context);
597 
598  /*
599  * If we found no vars nor aggs at all, it's a level-zero aggregate;
600  * otherwise, its level is the minimum of vars or aggs.
601  */
602  if (context.min_varlevel < 0)
603  {
604  if (context.min_agglevel < 0)
605  agglevel = 0;
606  else
607  agglevel = context.min_agglevel;
608  }
609  else if (context.min_agglevel < 0)
610  agglevel = context.min_varlevel;
611  else
612  agglevel = Min(context.min_varlevel, context.min_agglevel);
613 
614  /*
615  * If there's a nested aggregate of the same semantic level, complain.
616  */
617  if (agglevel == context.min_agglevel)
618  {
619  int aggloc;
620 
621  aggloc = locate_agg_of_level((Node *) args, agglevel);
622  if (aggloc < 0)
623  aggloc = locate_agg_of_level((Node *) filter, agglevel);
624  ereport(ERROR,
625  (errcode(ERRCODE_GROUPING_ERROR),
626  errmsg("aggregate function calls cannot be nested"),
627  parser_errposition(pstate, aggloc)));
628  }
629 
630  /*
631  * Now check for vars/aggs in the direct arguments, and throw error if
632  * needed. Note that we allow a Var of the agg's semantic level, but not
633  * an Agg of that level. In principle such Aggs could probably be
634  * supported, but it would create an ordering dependency among the
635  * aggregates at execution time. Since the case appears neither to be
636  * required by spec nor particularly useful, we just treat it as a
637  * nested-aggregate situation.
638  */
639  if (directargs)
640  {
641  context.min_varlevel = -1;
642  context.min_agglevel = -1;
643  (void) expression_tree_walker((Node *) directargs,
645  (void *) &context);
646  if (context.min_varlevel >= 0 && context.min_varlevel < agglevel)
647  ereport(ERROR,
648  (errcode(ERRCODE_GROUPING_ERROR),
649  errmsg("outer-level aggregate cannot contain a lower-level variable in its direct arguments"),
650  parser_errposition(pstate,
651  locate_var_of_level((Node *) directargs,
652  context.min_varlevel))));
653  if (context.min_agglevel >= 0 && context.min_agglevel <= agglevel)
654  ereport(ERROR,
655  (errcode(ERRCODE_GROUPING_ERROR),
656  errmsg("aggregate function calls cannot be nested"),
657  parser_errposition(pstate,
658  locate_agg_of_level((Node *) directargs,
659  context.min_agglevel))));
660  }
661  return agglevel;
662 }
#define Min(x, y)
Definition: c.h:802
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:437
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:131
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
static bool check_agg_arguments_walker(Node *node, check_agg_arguments_context *context)
Definition: parse_agg.c:665

◆ check_agg_arguments_walker()

static bool check_agg_arguments_walker ( Node node,
check_agg_arguments_context context 
)
static

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

667 {
668  if (node == NULL)
669  return false;
670  if (IsA(node, Var))
671  {
672  int varlevelsup = ((Var *) node)->varlevelsup;
673 
674  /* convert levelsup to frame of reference of original query */
675  varlevelsup -= context->sublevels_up;
676  /* ignore local vars of subqueries */
677  if (varlevelsup >= 0)
678  {
679  if (context->min_varlevel < 0 ||
680  context->min_varlevel > varlevelsup)
681  context->min_varlevel = varlevelsup;
682  }
683  return false;
684  }
685  if (IsA(node, Aggref))
686  {
687  int agglevelsup = ((Aggref *) node)->agglevelsup;
688 
689  /* convert levelsup to frame of reference of original query */
690  agglevelsup -= context->sublevels_up;
691  /* ignore local aggs of subqueries */
692  if (agglevelsup >= 0)
693  {
694  if (context->min_agglevel < 0 ||
695  context->min_agglevel > agglevelsup)
696  context->min_agglevel = agglevelsup;
697  }
698  /* no need to examine args of the inner aggregate */
699  return false;
700  }
701  if (IsA(node, GroupingFunc))
702  {
703  int agglevelsup = ((GroupingFunc *) node)->agglevelsup;
704 
705  /* convert levelsup to frame of reference of original query */
706  agglevelsup -= context->sublevels_up;
707  /* ignore local aggs of subqueries */
708  if (agglevelsup >= 0)
709  {
710  if (context->min_agglevel < 0 ||
711  context->min_agglevel > agglevelsup)
712  context->min_agglevel = agglevelsup;
713  }
714  /* Continue and descend into subtree */
715  }
716 
717  /*
718  * SRFs and window functions can be rejected immediately, unless we are
719  * within a sub-select within the aggregate's arguments; in that case
720  * they're OK.
721  */
722  if (context->sublevels_up == 0)
723  {
724  if ((IsA(node, FuncExpr) &&((FuncExpr *) node)->funcretset) ||
725  (IsA(node, OpExpr) &&((OpExpr *) node)->opretset))
726  ereport(ERROR,
727  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
728  errmsg("aggregate function calls cannot contain set-returning function calls"),
729  errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
730  parser_errposition(context->pstate, exprLocation(node))));
731  if (IsA(node, WindowFunc))
732  ereport(ERROR,
733  (errcode(ERRCODE_GROUPING_ERROR),
734  errmsg("aggregate function calls cannot contain window function calls"),
735  parser_errposition(context->pstate,
736  ((WindowFunc *) node)->location)));
737  }
738  if (IsA(node, Query))
739  {
740  /* Recurse into subselects */
741  bool result;
742 
743  context->sublevels_up++;
744  result = query_tree_walker((Query *) node,
746  (void *) context,
747  0);
748  context->sublevels_up--;
749  return result;
750  }
751 
752  return expression_tree_walker(node,
754  (void *) context);
755 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2245
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
int errhint(const char *fmt,...)
Definition: elog.c:987
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
int errcode(int sqlerrcode)
Definition: elog.c:575
Definition: primnodes.h:163
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
static bool check_agg_arguments_walker(Node *node, check_agg_arguments_context *context)
Definition: parse_agg.c:665

◆ check_agglevels_and_constraints()

static void check_agglevels_and_constraints ( ParseState pstate,
Node expr 
)
static

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

288 {
289  List *directargs = NIL;
290  List *args = NIL;
291  Expr *filter = NULL;
292  int min_varlevel;
293  int location = -1;
294  Index *p_levelsup;
295  const char *err;
296  bool errkind;
297  bool isAgg = IsA(expr, Aggref);
298 
299  if (isAgg)
300  {
301  Aggref *agg = (Aggref *) expr;
302 
303  directargs = agg->aggdirectargs;
304  args = agg->args;
305  filter = agg->aggfilter;
306  location = agg->location;
307  p_levelsup = &agg->agglevelsup;
308  }
309  else
310  {
311  GroupingFunc *grp = (GroupingFunc *) expr;
312 
313  args = grp->args;
314  location = grp->location;
315  p_levelsup = &grp->agglevelsup;
316  }
317 
318  /*
319  * Check the arguments to compute the aggregate's level and detect
320  * improper nesting.
321  */
322  min_varlevel = check_agg_arguments(pstate,
323  directargs,
324  args,
325  filter);
326 
327  *p_levelsup = min_varlevel;
328 
329  /* Mark the correct pstate level as having aggregates */
330  while (min_varlevel-- > 0)
331  pstate = pstate->parentParseState;
332  pstate->p_hasAggs = true;
333 
334  /*
335  * Check to see if the aggregate function is in an invalid place within
336  * its aggregation query.
337  *
338  * For brevity we support two schemes for reporting an error here: set
339  * "err" to a custom message, or set "errkind" true if the error context
340  * is sufficiently identified by what ParseExprKindName will return, *and*
341  * what it will return is just a SQL keyword. (Otherwise, use a custom
342  * message to avoid creating translation problems.)
343  */
344  err = NULL;
345  errkind = false;
346  switch (pstate->p_expr_kind)
347  {
348  case EXPR_KIND_NONE:
349  Assert(false); /* can't happen */
350  break;
351  case EXPR_KIND_OTHER:
352 
353  /*
354  * Accept aggregate/grouping here; caller must throw error if
355  * wanted
356  */
357  break;
358  case EXPR_KIND_JOIN_ON:
360  if (isAgg)
361  err = _("aggregate functions are not allowed in JOIN conditions");
362  else
363  err = _("grouping operations are not allowed in JOIN conditions");
364 
365  break;
367  /* Should only be possible in a LATERAL subquery */
368  Assert(pstate->p_lateral_active);
369 
370  /*
371  * Aggregate/grouping scope rules make it worth being explicit
372  * here
373  */
374  if (isAgg)
375  err = _("aggregate functions are not allowed in FROM clause of their own query level");
376  else
377  err = _("grouping operations are not allowed in FROM clause of their own query level");
378 
379  break;
381  if (isAgg)
382  err = _("aggregate functions are not allowed in functions in FROM");
383  else
384  err = _("grouping operations are not allowed in functions in FROM");
385 
386  break;
387  case EXPR_KIND_WHERE:
388  errkind = true;
389  break;
390  case EXPR_KIND_POLICY:
391  if (isAgg)
392  err = _("aggregate functions are not allowed in policy expressions");
393  else
394  err = _("grouping operations are not allowed in policy expressions");
395 
396  break;
397  case EXPR_KIND_HAVING:
398  /* okay */
399  break;
400  case EXPR_KIND_FILTER:
401  errkind = true;
402  break;
404  /* okay */
405  break;
407  /* okay */
408  break;
410  if (isAgg)
411  err = _("aggregate functions are not allowed in window RANGE");
412  else
413  err = _("grouping operations are not allowed in window RANGE");
414 
415  break;
417  if (isAgg)
418  err = _("aggregate functions are not allowed in window ROWS");
419  else
420  err = _("grouping operations are not allowed in window ROWS");
421 
422  break;
424  /* okay */
425  break;
429  errkind = true;
430  break;
431  case EXPR_KIND_GROUP_BY:
432  errkind = true;
433  break;
434  case EXPR_KIND_ORDER_BY:
435  /* okay */
436  break;
438  /* okay */
439  break;
440  case EXPR_KIND_LIMIT:
441  case EXPR_KIND_OFFSET:
442  errkind = true;
443  break;
444  case EXPR_KIND_RETURNING:
445  errkind = true;
446  break;
447  case EXPR_KIND_VALUES:
449  errkind = true;
450  break;
453  if (isAgg)
454  err = _("aggregate functions are not allowed in check constraints");
455  else
456  err = _("grouping operations are not allowed in check constraints");
457 
458  break;
461 
462  if (isAgg)
463  err = _("aggregate functions are not allowed in DEFAULT expressions");
464  else
465  err = _("grouping operations are not allowed in DEFAULT expressions");
466 
467  break;
469  if (isAgg)
470  err = _("aggregate functions are not allowed in index expressions");
471  else
472  err = _("grouping operations are not allowed in index expressions");
473 
474  break;
476  if (isAgg)
477  err = _("aggregate functions are not allowed in index predicates");
478  else
479  err = _("grouping operations are not allowed in index predicates");
480 
481  break;
483  if (isAgg)
484  err = _("aggregate functions are not allowed in transform expressions");
485  else
486  err = _("grouping operations are not allowed in transform expressions");
487 
488  break;
490  if (isAgg)
491  err = _("aggregate functions are not allowed in EXECUTE parameters");
492  else
493  err = _("grouping operations are not allowed in EXECUTE parameters");
494 
495  break;
497  if (isAgg)
498  err = _("aggregate functions are not allowed in trigger WHEN conditions");
499  else
500  err = _("grouping operations are not allowed in trigger WHEN conditions");
501 
502  break;
504  if (isAgg)
505  err = _("aggregate functions are not allowed in partition key expression");
506  else
507  err = _("grouping operations are not allowed in partition key expression");
508 
509  break;
510 
511  case EXPR_KIND_CALL:
512  if (isAgg)
513  err = _("aggregate functions are not allowed in CALL arguments");
514  else
515  err = _("grouping operations are not allowed in CALL arguments");
516 
517  break;
518 
519  /*
520  * There is intentionally no default: case here, so that the
521  * compiler will warn if we add a new ParseExprKind without
522  * extending this switch. If we do see an unrecognized value at
523  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
524  * which is sane anyway.
525  */
526  }
527 
528  if (err)
529  ereport(ERROR,
530  (errcode(ERRCODE_GROUPING_ERROR),
531  errmsg_internal("%s", err),
532  parser_errposition(pstate, location)));
533 
534  if (errkind)
535  {
536  if (isAgg)
537  /* translator: %s is name of a SQL construct, eg GROUP BY */
538  err = _("aggregate functions are not allowed in %s");
539  else
540  /* translator: %s is name of a SQL construct, eg GROUP BY */
541  err = _("grouping operations are not allowed in %s");
542 
543  ereport(ERROR,
544  (errcode(ERRCODE_GROUPING_ERROR),
545  errmsg_internal(err,
546  ParseExprKindName(pstate->p_expr_kind)),
547  parser_errposition(pstate, location)));
548  }
549 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
List * args
Definition: primnodes.h:341
int errcode(int sqlerrcode)
Definition: elog.c:575
List * args
Definition: primnodes.h:301
bool p_hasAggs
Definition: parse_node.h:199
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3399
#define ERROR
Definition: elog.h:43
int location
Definition: primnodes.h:311
Index agglevelsup
Definition: primnodes.h:309
List * aggdirectargs
Definition: primnodes.h:300
#define ereport(elevel, rest)
Definition: elog.h:122
struct ParseState * parentParseState
Definition: parse_node.h:171
Index agglevelsup
Definition: primnodes.h:345
unsigned int Index
Definition: c.h:413
ParseExprKind p_expr_kind
Definition: parse_node.h:187
bool p_lateral_active
Definition: parse_node.h:179
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
#define Assert(condition)
Definition: c.h:670
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
Expr * aggfilter
Definition: primnodes.h:304
static int check_agg_arguments(ParseState *pstate, List *directargs, List *args, Expr *filter)
Definition: parse_agg.c:577
Definition: pg_list.h:45
#define _(x)
Definition: elog.c:84

◆ check_ungrouped_columns()

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

Definition at line 1210 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::have_non_var_grouping, check_ungrouped_columns_context::in_agg_direct_args, check_ungrouped_columns_context::pstate, check_ungrouped_columns_context::qry, check_ungrouped_columns_context::root, and check_ungrouped_columns_context::sublevels_up.

Referenced by parseCheckAggregates().

1214 {
1216 
1217  context.pstate = pstate;
1218  context.qry = qry;
1219  context.root = NULL;
1220  context.groupClauses = groupClauses;
1221  context.groupClauseCommonVars = groupClauseCommonVars;
1222  context.have_non_var_grouping = have_non_var_grouping;
1223  context.func_grouped_rels = func_grouped_rels;
1224  context.sublevels_up = 0;
1225  context.in_agg_direct_args = false;
1226  check_ungrouped_columns_walker(node, &context);
1227 }
static bool check_ungrouped_columns_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1230

◆ check_ungrouped_columns_walker()

static bool check_ungrouped_columns_walker ( Node node,
check_ungrouped_columns_context context 
)
static

Definition at line 1230 of file parse_agg.c.

References Aggref::aggdirectargs, Aggref::agglevelsup, GroupingFunc::agglevelsup, Alias::aliasname, Assert, 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().

1232 {
1233  ListCell *gl;
1234 
1235  if (node == NULL)
1236  return false;
1237  if (IsA(node, Const) ||
1238  IsA(node, Param))
1239  return false; /* constants are always acceptable */
1240 
1241  if (IsA(node, Aggref))
1242  {
1243  Aggref *agg = (Aggref *) node;
1244 
1245  if ((int) agg->agglevelsup == context->sublevels_up)
1246  {
1247  /*
1248  * If we find an aggregate call of the original level, do not
1249  * recurse into its normal arguments, ORDER BY arguments, or
1250  * filter; ungrouped vars there are not an error. But we should
1251  * check direct arguments as though they weren't in an aggregate.
1252  * We set a special flag in the context to help produce a useful
1253  * error message for ungrouped vars in direct arguments.
1254  */
1255  bool result;
1256 
1257  Assert(!context->in_agg_direct_args);
1258  context->in_agg_direct_args = true;
1260  context);
1261  context->in_agg_direct_args = false;
1262  return result;
1263  }
1264 
1265  /*
1266  * We can skip recursing into aggregates of higher levels altogether,
1267  * since they could not possibly contain Vars of concern to us (see
1268  * transformAggregateCall). We do need to look at aggregates of lower
1269  * levels, however.
1270  */
1271  if ((int) agg->agglevelsup > context->sublevels_up)
1272  return false;
1273  }
1274 
1275  if (IsA(node, GroupingFunc))
1276  {
1277  GroupingFunc *grp = (GroupingFunc *) node;
1278 
1279  /* handled GroupingFunc separately, no need to recheck at this level */
1280 
1281  if ((int) grp->agglevelsup >= context->sublevels_up)
1282  return false;
1283  }
1284 
1285  /*
1286  * If we have any GROUP BY items that are not simple Vars, check to see if
1287  * subexpression as a whole matches any GROUP BY item. We need to do this
1288  * at every recursion level so that we recognize GROUPed-BY expressions
1289  * before reaching variables within them. But this only works at the outer
1290  * query level, as noted above.
1291  */
1292  if (context->have_non_var_grouping && context->sublevels_up == 0)
1293  {
1294  foreach(gl, context->groupClauses)
1295  {
1296  TargetEntry *tle = lfirst(gl);
1297 
1298  if (equal(node, tle->expr))
1299  return false; /* acceptable, do not descend more */
1300  }
1301  }
1302 
1303  /*
1304  * If we have an ungrouped Var of the original query level, we have a
1305  * failure. Vars below the original query level are not a problem, and
1306  * neither are Vars from above it. (If such Vars are ungrouped as far as
1307  * their own query level is concerned, that's someone else's problem...)
1308  */
1309  if (IsA(node, Var))
1310  {
1311  Var *var = (Var *) node;
1312  RangeTblEntry *rte;
1313  char *attname;
1314 
1315  if (var->varlevelsup != context->sublevels_up)
1316  return false; /* it's not local to my query, ignore */
1317 
1318  /*
1319  * Check for a match, if we didn't do it above.
1320  */
1321  if (!context->have_non_var_grouping || context->sublevels_up != 0)
1322  {
1323  foreach(gl, context->groupClauses)
1324  {
1325  Var *gvar = (Var *) ((TargetEntry *) lfirst(gl))->expr;
1326 
1327  if (IsA(gvar, Var) &&
1328  gvar->varno == var->varno &&
1329  gvar->varattno == var->varattno &&
1330  gvar->varlevelsup == 0)
1331  return false; /* acceptable, we're okay */
1332  }
1333  }
1334 
1335  /*
1336  * Check whether the Var is known functionally dependent on the GROUP
1337  * BY columns. If so, we can allow the Var to be used, because the
1338  * grouping is really a no-op for this table. However, this deduction
1339  * depends on one or more constraints of the table, so we have to add
1340  * those constraints to the query's constraintDeps list, because it's
1341  * not semantically valid anymore if the constraint(s) get dropped.
1342  * (Therefore, this check must be the last-ditch effort before raising
1343  * error: we don't want to add dependencies unnecessarily.)
1344  *
1345  * Because this is a pretty expensive check, and will have the same
1346  * outcome for all columns of a table, we remember which RTEs we've
1347  * already proven functional dependency for in the func_grouped_rels
1348  * list. This test also prevents us from adding duplicate entries to
1349  * the constraintDeps list.
1350  */
1351  if (list_member_int(*context->func_grouped_rels, var->varno))
1352  return false; /* previously proven acceptable */
1353 
1354  Assert(var->varno > 0 &&
1355  (int) var->varno <= list_length(context->pstate->p_rtable));
1356  rte = rt_fetch(var->varno, context->pstate->p_rtable);
1357  if (rte->rtekind == RTE_RELATION)
1358  {
1360  var->varno,
1361  0,
1362  context->groupClauseCommonVars,
1363  &context->qry->constraintDeps))
1364  {
1365  *context->func_grouped_rels =
1366  lappend_int(*context->func_grouped_rels, var->varno);
1367  return false; /* acceptable */
1368  }
1369  }
1370 
1371  /* Found an ungrouped local variable; generate error message */
1372  attname = get_rte_attribute_name(rte, var->varattno);
1373  if (context->sublevels_up == 0)
1374  ereport(ERROR,
1375  (errcode(ERRCODE_GROUPING_ERROR),
1376  errmsg("column \"%s.%s\" must appear in the GROUP BY clause or be used in an aggregate function",
1377  rte->eref->aliasname, attname),
1378  context->in_agg_direct_args ?
1379  errdetail("Direct arguments of an ordered-set aggregate must use only grouped columns.") : 0,
1380  parser_errposition(context->pstate, var->location)));
1381  else
1382  ereport(ERROR,
1383  (errcode(ERRCODE_GROUPING_ERROR),
1384  errmsg("subquery uses ungrouped column \"%s.%s\" from outer query",
1385  rte->eref->aliasname, attname),
1386  parser_errposition(context->pstate, var->location)));
1387  }
1388 
1389  if (IsA(node, Query))
1390  {
1391  /* Recurse into subselects */
1392  bool result;
1393 
1394  context->sublevels_up++;
1395  result = query_tree_walker((Query *) node,
1397  (void *) context,
1398  0);
1399  context->sublevels_up--;
1400  return result;
1401  }
1403  (void *) context);
1404 }
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:2245
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
static bool check_ungrouped_columns_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1230
Index varlevelsup
Definition: primnodes.h:173
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2984
List * constraintDeps
Definition: parsenodes.h:166
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
AttrNumber varattno
Definition: primnodes.h:168
Definition: primnodes.h:163
#define ERROR
Definition: elog.h:43
bool list_member_int(const List *list, int datum)
Definition: list.c:485
int location
Definition: primnodes.h:178
int errdetail(const char *fmt,...)
Definition: elog.c:873
Index agglevelsup
Definition: primnodes.h:309
List * aggdirectargs
Definition: primnodes.h:300
#define ereport(elevel, rest)
Definition: elog.h:122
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
List * lappend_int(List *list, int datum)
Definition: list.c:146
Index varno
Definition: primnodes.h:166
Index agglevelsup
Definition: primnodes.h:345
char * get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
char * aliasname
Definition: primnodes.h:42
Expr * expr
Definition: primnodes.h:1375
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
RTEKind rtekind
Definition: parsenodes.h:951
int errmsg(const char *fmt,...)
Definition: elog.c:797
Alias * eref
Definition: parsenodes.h:1055
List * p_rtable
Definition: parse_node.h:173

◆ cmp_list_len_asc()

static int cmp_list_len_asc ( const void *  a,
const void *  b 
)
static

Definition at line 1697 of file parse_agg.c.

References list_length().

Referenced by expand_grouping_sets().

1698 {
1699  int la = list_length(*(List *const *) a);
1700  int lb = list_length(*(List *const *) b);
1701 
1702  return (la > lb) ? 1 : (la == lb) ? 0 : -1;
1703 }
static int list_length(const List *l)
Definition: pg_list.h:89
Definition: pg_list.h:45

◆ expand_grouping_sets()

List* expand_grouping_sets ( List groupingSets,
int  limit 
)

Definition at line 1713 of file parse_agg.c.

References Assert, buf, cmp_list_len_asc(), expand_groupingset_node(), for_each_cell, lappend(), lfirst, linitial, list_head(), list_length(), list_union_int(), lnext, NIL, palloc(), pfree(), and qsort.

Referenced by parseCheckAggregates(), and preprocess_grouping_sets().

1714 {
1715  List *expanded_groups = NIL;
1716  List *result = NIL;
1717  double numsets = 1;
1718  ListCell *lc;
1719 
1720  if (groupingSets == NIL)
1721  return NIL;
1722 
1723  foreach(lc, groupingSets)
1724  {
1725  List *current_result = NIL;
1726  GroupingSet *gs = lfirst(lc);
1727 
1728  current_result = expand_groupingset_node(gs);
1729 
1730  Assert(current_result != NIL);
1731 
1732  numsets *= list_length(current_result);
1733 
1734  if (limit >= 0 && numsets > limit)
1735  return NIL;
1736 
1737  expanded_groups = lappend(expanded_groups, current_result);
1738  }
1739 
1740  /*
1741  * Do cartesian product between sublists of expanded_groups. While at it,
1742  * remove any duplicate elements from individual grouping sets (we must
1743  * NOT change the number of sets though)
1744  */
1745 
1746  foreach(lc, (List *) linitial(expanded_groups))
1747  {
1748  result = lappend(result, list_union_int(NIL, (List *) lfirst(lc)));
1749  }
1750 
1751  for_each_cell(lc, lnext(list_head(expanded_groups)))
1752  {
1753  List *p = lfirst(lc);
1754  List *new_result = NIL;
1755  ListCell *lc2;
1756 
1757  foreach(lc2, result)
1758  {
1759  List *q = lfirst(lc2);
1760  ListCell *lc3;
1761 
1762  foreach(lc3, p)
1763  {
1764  new_result = lappend(new_result,
1765  list_union_int(q, (List *) lfirst(lc3)));
1766  }
1767  }
1768  result = new_result;
1769  }
1770 
1771  if (list_length(result) > 1)
1772  {
1773  int result_len = list_length(result);
1774  List **buf = palloc(sizeof(List *) * result_len);
1775  List **ptr = buf;
1776 
1777  foreach(lc, result)
1778  {
1779  *ptr++ = lfirst(lc);
1780  }
1781 
1782  qsort(buf, result_len, sizeof(List *), cmp_list_len_asc);
1783 
1784  result = NIL;
1785  ptr = buf;
1786 
1787  while (result_len-- > 0)
1788  result = lappend(result, *ptr++);
1789 
1790  pfree(buf);
1791  }
1792 
1793  return result;
1794 }
static int cmp_list_len_asc(const void *a, const void *b)
Definition: parse_agg.c:1697
#define NIL
Definition: pg_list.h:69
void pfree(void *pointer)
Definition: mcxt.c:949
#define linitial(l)
Definition: pg_list.h:111
static List * expand_groupingset_node(GroupingSet *gs)
Definition: parse_agg.c:1592
static char * buf
Definition: pg_test_fsync.c:67
List * list_union_int(const List *list1, const List *list2)
Definition: list.c:744
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
List * lappend(List *list, void *datum)
Definition: list.c:128
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
#define for_each_cell(cell, initcell)
Definition: pg_list.h:169
void * palloc(Size size)
Definition: mcxt.c:848
#define qsort(a, b, c, d)
Definition: port.h:408
Definition: pg_list.h:45

◆ expand_groupingset_node()

static List * expand_groupingset_node ( GroupingSet gs)
static

Definition at line 1592 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_copy(), list_length(), list_make1, and NIL.

Referenced by expand_grouping_sets().

1593 {
1594  List *result = NIL;
1595 
1596  switch (gs->kind)
1597  {
1598  case GROUPING_SET_EMPTY:
1599  result = list_make1(NIL);
1600  break;
1601 
1602  case GROUPING_SET_SIMPLE:
1603  result = list_make1(gs->content);
1604  break;
1605 
1606  case GROUPING_SET_ROLLUP:
1607  {
1608  List *rollup_val = gs->content;
1609  ListCell *lc;
1610  int curgroup_size = list_length(gs->content);
1611 
1612  while (curgroup_size > 0)
1613  {
1614  List *current_result = NIL;
1615  int i = curgroup_size;
1616 
1617  foreach(lc, rollup_val)
1618  {
1619  GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
1620 
1621  Assert(gs_current->kind == GROUPING_SET_SIMPLE);
1622 
1623  current_result
1624  = list_concat(current_result,
1625  list_copy(gs_current->content));
1626 
1627  /* If we are done with making the current group, break */
1628  if (--i == 0)
1629  break;
1630  }
1631 
1632  result = lappend(result, current_result);
1633  --curgroup_size;
1634  }
1635 
1636  result = lappend(result, NIL);
1637  }
1638  break;
1639 
1640  case GROUPING_SET_CUBE:
1641  {
1642  List *cube_list = gs->content;
1643  int number_bits = list_length(cube_list);
1644  uint32 num_sets;
1645  uint32 i;
1646 
1647  /* parser should cap this much lower */
1648  Assert(number_bits < 31);
1649 
1650  num_sets = (1U << number_bits);
1651 
1652  for (i = 0; i < num_sets; i++)
1653  {
1654  List *current_result = NIL;
1655  ListCell *lc;
1656  uint32 mask = 1U;
1657 
1658  foreach(lc, cube_list)
1659  {
1660  GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
1661 
1662  Assert(gs_current->kind == GROUPING_SET_SIMPLE);
1663 
1664  if (mask & i)
1665  {
1666  current_result
1667  = list_concat(current_result,
1668  list_copy(gs_current->content));
1669  }
1670 
1671  mask <<= 1;
1672  }
1673 
1674  result = lappend(result, current_result);
1675  }
1676  }
1677  break;
1678 
1679  case GROUPING_SET_SETS:
1680  {
1681  ListCell *lc;
1682 
1683  foreach(lc, gs->content)
1684  {
1685  List *current_result = expand_groupingset_node(lfirst(lc));
1686 
1687  result = list_concat(result, current_result);
1688  }
1689  }
1690  break;
1691  }
1692 
1693  return result;
1694 }
#define NIL
Definition: pg_list.h:69
List * content
Definition: parsenodes.h:1266
List * list_copy(const List *oldlist)
Definition: list.c:1160
List * list_concat(List *list1, List *list2)
Definition: list.c:321
GroupingSetKind kind
Definition: parsenodes.h:1265
#define list_make1(x1)
Definition: pg_list.h:139
static List * expand_groupingset_node(GroupingSet *gs)
Definition: parse_agg.c:1592
unsigned int uint32
Definition: c.h:296
List * lappend(List *list, void *datum)
Definition: list.c:128
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
int i
Definition: pg_list.h:45

◆ finalize_grouping_exprs()

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

Definition at line 1418 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::have_non_var_grouping, check_ungrouped_columns_context::in_agg_direct_args, NIL, check_ungrouped_columns_context::pstate, check_ungrouped_columns_context::qry, check_ungrouped_columns_context::root, and check_ungrouped_columns_context::sublevels_up.

Referenced by parseCheckAggregates().

1421 {
1423 
1424  context.pstate = pstate;
1425  context.qry = qry;
1426  context.root = root;
1427  context.groupClauses = groupClauses;
1428  context.groupClauseCommonVars = NIL;
1429  context.have_non_var_grouping = have_non_var_grouping;
1430  context.func_grouped_rels = NULL;
1431  context.sublevels_up = 0;
1432  context.in_agg_direct_args = false;
1433  finalize_grouping_exprs_walker(node, &context);
1434 }
#define NIL
Definition: pg_list.h:69
static bool finalize_grouping_exprs_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1437

◆ finalize_grouping_exprs_walker()

static bool finalize_grouping_exprs_walker ( Node node,
check_ungrouped_columns_context context 
)
static

Definition at line 1437 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::have_non_var_grouping, check_ungrouped_columns_context::in_agg_direct_args, IsA, lappend_int(), lfirst, NIL, parser_errposition(), check_ungrouped_columns_context::pstate, query_tree_walker(), GroupingFunc::refs, TargetEntry::ressortgroupref, check_ungrouped_columns_context::root, check_ungrouped_columns_context::sublevels_up, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by finalize_grouping_exprs().

1439 {
1440  ListCell *gl;
1441 
1442  if (node == NULL)
1443  return false;
1444  if (IsA(node, Const) ||
1445  IsA(node, Param))
1446  return false; /* constants are always acceptable */
1447 
1448  if (IsA(node, Aggref))
1449  {
1450  Aggref *agg = (Aggref *) node;
1451 
1452  if ((int) agg->agglevelsup == context->sublevels_up)
1453  {
1454  /*
1455  * If we find an aggregate call of the original level, do not
1456  * recurse into its normal arguments, ORDER BY arguments, or
1457  * filter; GROUPING exprs of this level are not allowed there. But
1458  * check direct arguments as though they weren't in an aggregate.
1459  */
1460  bool result;
1461 
1462  Assert(!context->in_agg_direct_args);
1463  context->in_agg_direct_args = true;
1465  context);
1466  context->in_agg_direct_args = false;
1467  return result;
1468  }
1469 
1470  /*
1471  * We can skip recursing into aggregates of higher levels altogether,
1472  * since they could not possibly contain exprs of concern to us (see
1473  * transformAggregateCall). We do need to look at aggregates of lower
1474  * levels, however.
1475  */
1476  if ((int) agg->agglevelsup > context->sublevels_up)
1477  return false;
1478  }
1479 
1480  if (IsA(node, GroupingFunc))
1481  {
1482  GroupingFunc *grp = (GroupingFunc *) node;
1483 
1484  /*
1485  * We only need to check GroupingFunc nodes at the exact level to
1486  * which they belong, since they cannot mix levels in arguments.
1487  */
1488 
1489  if ((int) grp->agglevelsup == context->sublevels_up)
1490  {
1491  ListCell *lc;
1492  List *ref_list = NIL;
1493 
1494  foreach(lc, grp->args)
1495  {
1496  Node *expr = lfirst(lc);
1497  Index ref = 0;
1498 
1499  if (context->root)
1500  expr = flatten_join_alias_vars(context->root, expr);
1501 
1502  /*
1503  * Each expression must match a grouping entry at the current
1504  * query level. Unlike the general expression case, we don't
1505  * allow functional dependencies or outer references.
1506  */
1507 
1508  if (IsA(expr, Var))
1509  {
1510  Var *var = (Var *) expr;
1511 
1512  if (var->varlevelsup == context->sublevels_up)
1513  {
1514  foreach(gl, context->groupClauses)
1515  {
1516  TargetEntry *tle = lfirst(gl);
1517  Var *gvar = (Var *) tle->expr;
1518 
1519  if (IsA(gvar, Var) &&
1520  gvar->varno == var->varno &&
1521  gvar->varattno == var->varattno &&
1522  gvar->varlevelsup == 0)
1523  {
1524  ref = tle->ressortgroupref;
1525  break;
1526  }
1527  }
1528  }
1529  }
1530  else if (context->have_non_var_grouping &&
1531  context->sublevels_up == 0)
1532  {
1533  foreach(gl, context->groupClauses)
1534  {
1535  TargetEntry *tle = lfirst(gl);
1536 
1537  if (equal(expr, tle->expr))
1538  {
1539  ref = tle->ressortgroupref;
1540  break;
1541  }
1542  }
1543  }
1544 
1545  if (ref == 0)
1546  ereport(ERROR,
1547  (errcode(ERRCODE_GROUPING_ERROR),
1548  errmsg("arguments to GROUPING must be grouping expressions of the associated query level"),
1549  parser_errposition(context->pstate,
1550  exprLocation(expr))));
1551 
1552  ref_list = lappend_int(ref_list, ref);
1553  }
1554 
1555  grp->refs = ref_list;
1556  }
1557 
1558  if ((int) grp->agglevelsup > context->sublevels_up)
1559  return false;
1560  }
1561 
1562  if (IsA(node, Query))
1563  {
1564  /* Recurse into subselects */
1565  bool result;
1566 
1567  context->sublevels_up++;
1568  result = query_tree_walker((Query *) node,
1570  (void *) context,
1571  0);
1572  context->sublevels_up--;
1573  return result;
1574  }
1576  (void *) context);
1577 }
#define NIL
Definition: pg_list.h:69
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2245
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
Index varlevelsup
Definition: primnodes.h:173
List * args
Definition: primnodes.h:341
List * refs
Definition: primnodes.h:343
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2984
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
AttrNumber varattno
Definition: primnodes.h:168
Definition: primnodes.h:163
#define ERROR
Definition: elog.h:43
static bool finalize_grouping_exprs_walker(Node *node, check_ungrouped_columns_context *context)
Definition: parse_agg.c:1437
Index agglevelsup
Definition: primnodes.h:309
List * aggdirectargs
Definition: primnodes.h:300
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend_int(List *list, int datum)
Definition: list.c:146
Index varno
Definition: primnodes.h:166
Node * flatten_join_alias_vars(PlannerInfo *root, Node *node)
Definition: var.c:670
Index agglevelsup
Definition: primnodes.h:345
unsigned int Index
Definition: c.h:413
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1375
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
Index ressortgroupref
Definition: primnodes.h:1378
Definition: pg_list.h:45

◆ get_aggregate_argtypes()

int get_aggregate_argtypes ( Aggref aggref,
Oid inputTypes 
)

Definition at line 1812 of file parse_agg.c.

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

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

1813 {
1814  int numArguments = 0;
1815  ListCell *lc;
1816 
1818 
1819  foreach(lc, aggref->aggargtypes)
1820  {
1821  inputTypes[numArguments++] = lfirst_oid(lc);
1822  }
1823 
1824  return numArguments;
1825 }
#define FUNC_MAX_ARGS
List * aggargtypes
Definition: primnodes.h:299
#define Assert(condition)
Definition: c.h:670
static int list_length(const List *l)
Definition: pg_list.h:89
#define lfirst_oid(lc)
Definition: pg_list.h:108

◆ make_agg_arg()

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

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

2071 {
2072  Param *argp = makeNode(Param);
2073 
2074  argp->paramkind = PARAM_EXEC;
2075  argp->paramid = -1;
2076  argp->paramtype = argtype;
2077  argp->paramtypmod = -1;
2078  argp->paramcollid = argcollation;
2079  argp->location = -1;
2080  return (Node *) argp;
2081 }
ParamKind paramkind
Definition: primnodes.h:244
Definition: nodes.h:512
Oid paramcollid
Definition: primnodes.h:248
int location
Definition: primnodes.h:249
int32 paramtypmod
Definition: primnodes.h:247
#define makeNode(_type_)
Definition: nodes.h:560
int paramid
Definition: primnodes.h:245
Oid paramtype
Definition: primnodes.h:246

◆ parseCheckAggregates()

void parseCheckAggregates ( ParseState pstate,
Query qry 
)

Definition at line 1003 of file parse_agg.c.

References Assert, check_ungrouped_columns(), CurrentMemoryContext, ereport, errcode(), errmsg(), ERROR, expand_grouping_sets(), TargetEntry::expr, exprLocation(), finalize_grouping_exprs(), flatten_join_alias_vars(), for_each_cell, get_sortgroupclause_tle(), Query::groupClause, Query::groupingSets, PlannerInfo::hasJoinRTEs, Query::havingQual, IsA, lappend(), lcons(), lfirst, linitial, list_head(), list_intersection_int(), list_length(), list_member_int(), lnext, locate_agg_of_level(), makeNode, NIL, ParseState::p_hasAggs, ParseState::p_rtable, PlannerInfo::parse, parser_errposition(), PlannerInfo::planner_cxt, TargetEntry::ressortgroupref, RTE_CTE, RTE_JOIN, RangeTblEntry::rtekind, RangeTblEntry::self_reference, and Query::targetList.

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

1004 {
1005  List *gset_common = NIL;
1006  List *groupClauses = NIL;
1007  List *groupClauseCommonVars = NIL;
1008  bool have_non_var_grouping;
1009  List *func_grouped_rels = NIL;
1010  ListCell *l;
1011  bool hasJoinRTEs;
1012  bool hasSelfRefRTEs;
1013  PlannerInfo *root = NULL;
1014  Node *clause;
1015 
1016  /* This should only be called if we found aggregates or grouping */
1017  Assert(pstate->p_hasAggs || qry->groupClause || qry->havingQual || qry->groupingSets);
1018 
1019  /*
1020  * If we have grouping sets, expand them and find the intersection of all
1021  * sets.
1022  */
1023  if (qry->groupingSets)
1024  {
1025  /*
1026  * The limit of 4096 is arbitrary and exists simply to avoid resource
1027  * issues from pathological constructs.
1028  */
1029  List *gsets = expand_grouping_sets(qry->groupingSets, 4096);
1030 
1031  if (!gsets)
1032  ereport(ERROR,
1033  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
1034  errmsg("too many grouping sets present (maximum 4096)"),
1035  parser_errposition(pstate,
1036  qry->groupClause
1037  ? exprLocation((Node *) qry->groupClause)
1038  : exprLocation((Node *) qry->groupingSets))));
1039 
1040  /*
1041  * The intersection will often be empty, so help things along by
1042  * seeding the intersect with the smallest set.
1043  */
1044  gset_common = linitial(gsets);
1045 
1046  if (gset_common)
1047  {
1048  for_each_cell(l, lnext(list_head(gsets)))
1049  {
1050  gset_common = list_intersection_int(gset_common, lfirst(l));
1051  if (!gset_common)
1052  break;
1053  }
1054  }
1055 
1056  /*
1057  * If there was only one grouping set in the expansion, AND if the
1058  * groupClause is non-empty (meaning that the grouping set is not
1059  * empty either), then we can ditch the grouping set and pretend we
1060  * just had a normal GROUP BY.
1061  */
1062  if (list_length(gsets) == 1 && qry->groupClause)
1063  qry->groupingSets = NIL;
1064  }
1065 
1066  /*
1067  * Scan the range table to see if there are JOIN or self-reference CTE
1068  * entries. We'll need this info below.
1069  */
1070  hasJoinRTEs = hasSelfRefRTEs = false;
1071  foreach(l, pstate->p_rtable)
1072  {
1073  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
1074 
1075  if (rte->rtekind == RTE_JOIN)
1076  hasJoinRTEs = true;
1077  else if (rte->rtekind == RTE_CTE && rte->self_reference)
1078  hasSelfRefRTEs = true;
1079  }
1080 
1081  /*
1082  * Build a list of the acceptable GROUP BY expressions for use by
1083  * check_ungrouped_columns().
1084  *
1085  * We get the TLE, not just the expr, because GROUPING wants to know the
1086  * sortgroupref.
1087  */
1088  foreach(l, qry->groupClause)
1089  {
1090  SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
1091  TargetEntry *expr;
1092 
1093  expr = get_sortgroupclause_tle(grpcl, qry->targetList);
1094  if (expr == NULL)
1095  continue; /* probably cannot happen */
1096 
1097  groupClauses = lcons(expr, groupClauses);
1098  }
1099 
1100  /*
1101  * If there are join alias vars involved, we have to flatten them to the
1102  * underlying vars, so that aliased and unaliased vars will be correctly
1103  * taken as equal. We can skip the expense of doing this if no rangetable
1104  * entries are RTE_JOIN kind. We use the planner's flatten_join_alias_vars
1105  * routine to do the flattening; it wants a PlannerInfo root node, which
1106  * fortunately can be mostly dummy.
1107  */
1108  if (hasJoinRTEs)
1109  {
1110  root = makeNode(PlannerInfo);
1111  root->parse = qry;
1113  root->hasJoinRTEs = true;
1114 
1115  groupClauses = (List *) flatten_join_alias_vars(root,
1116  (Node *) groupClauses);
1117  }
1118 
1119  /*
1120  * Detect whether any of the grouping expressions aren't simple Vars; if
1121  * they're all Vars then we don't have to work so hard in the recursive
1122  * scans. (Note we have to flatten aliases before this.)
1123  *
1124  * Track Vars that are included in all grouping sets separately in
1125  * groupClauseCommonVars, since these are the only ones we can use to
1126  * check for functional dependencies.
1127  */
1128  have_non_var_grouping = false;
1129  foreach(l, groupClauses)
1130  {
1131  TargetEntry *tle = lfirst(l);
1132 
1133  if (!IsA(tle->expr, Var))
1134  {
1135  have_non_var_grouping = true;
1136  }
1137  else if (!qry->groupingSets ||
1138  list_member_int(gset_common, tle->ressortgroupref))
1139  {
1140  groupClauseCommonVars = lappend(groupClauseCommonVars, tle->expr);
1141  }
1142  }
1143 
1144  /*
1145  * Check the targetlist and HAVING clause for ungrouped variables.
1146  *
1147  * Note: because we check resjunk tlist elements as well as regular ones,
1148  * this will also find ungrouped variables that came from ORDER BY and
1149  * WINDOW clauses. For that matter, it's also going to examine the
1150  * grouping expressions themselves --- but they'll all pass the test ...
1151  *
1152  * We also finalize GROUPING expressions, but for that we need to traverse
1153  * the original (unflattened) clause in order to modify nodes.
1154  */
1155  clause = (Node *) qry->targetList;
1156  finalize_grouping_exprs(clause, pstate, qry,
1157  groupClauses, root,
1158  have_non_var_grouping);
1159  if (hasJoinRTEs)
1160  clause = flatten_join_alias_vars(root, clause);
1161  check_ungrouped_columns(clause, pstate, qry,
1162  groupClauses, groupClauseCommonVars,
1163  have_non_var_grouping,
1164  &func_grouped_rels);
1165 
1166  clause = (Node *) qry->havingQual;
1167  finalize_grouping_exprs(clause, pstate, qry,
1168  groupClauses, root,
1169  have_non_var_grouping);
1170  if (hasJoinRTEs)
1171  clause = flatten_join_alias_vars(root, clause);
1172  check_ungrouped_columns(clause, pstate, qry,
1173  groupClauses, groupClauseCommonVars,
1174  have_non_var_grouping,
1175  &func_grouped_rels);
1176 
1177  /*
1178  * Per spec, aggregates can't appear in a recursive term.
1179  */
1180  if (pstate->p_hasAggs && hasSelfRefRTEs)
1181  ereport(ERROR,
1182  (errcode(ERRCODE_INVALID_RECURSION),
1183  errmsg("aggregate functions are not allowed in a recursive query's recursive term"),
1184  parser_errposition(pstate,
1185  locate_agg_of_level((Node *) qry, 0))));
1186 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:563
Query * parse
Definition: relation.h:155
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:370
bool hasJoinRTEs
Definition: relation.h:302
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
List * list_intersection_int(const List *list1, const List *list2)
Definition: list.c:826
List * groupingSets
Definition: parsenodes.h:148
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
bool p_hasAggs
Definition: parse_node.h:199
Definition: primnodes.h:163
List * targetList
Definition: parsenodes.h:138
static void check_ungrouped_columns(Node *node, ParseState *pstate, Query *qry, List *groupClauses, List *groupClauseVars, bool have_non_var_grouping, List **func_grouped_rels)
Definition: parse_agg.c:1210
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
static void finalize_grouping_exprs(Node *node, ParseState *pstate, Query *qry, List *groupClauses, PlannerInfo *root, bool have_non_var_grouping)
Definition: parse_agg.c:1418
bool list_member_int(const List *list, int datum)
Definition: list.c:485
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:131
Node * flatten_join_alias_vars(PlannerInfo *root, Node *node)
Definition: var.c:670
bool self_reference
Definition: parsenodes.h:1023
List * lcons(void *datum, List *list)
Definition: list.c:259
#define makeNode(_type_)
Definition: nodes.h:560
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1375
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define for_each_cell(cell, initcell)
Definition: pg_list.h:169
List * expand_grouping_sets(List *groupingSets, int limit)
Definition: parse_agg.c:1713
RTEKind rtekind
Definition: parsenodes.h:951
List * groupClause
Definition: parsenodes.h:146
int errmsg(const char *fmt,...)
Definition: elog.c:797
Index ressortgroupref
Definition: primnodes.h:1378
MemoryContext planner_cxt
Definition: relation.h:290
Node * havingQual
Definition: parsenodes.h:150
Definition: pg_list.h:45
List * p_rtable
Definition: parse_node.h:173

◆ resolve_aggregate_transtype()

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

Definition at line 1838 of file parse_agg.c.

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

Referenced by get_agg_clause_costs_walker(), and initialize_peragg().

1842 {
1843  /* resolve actual type of transition state, if polymorphic */
1844  if (IsPolymorphicType(aggtranstype))
1845  {
1846  /* have to fetch the agg's declared input types... */
1847  Oid *declaredArgTypes;
1848  int agg_nargs;
1849 
1850  (void) get_func_signature(aggfuncid, &declaredArgTypes, &agg_nargs);
1851 
1852  /*
1853  * VARIADIC ANY aggs could have more actual than declared args, but
1854  * such extra args can't affect polymorphic type resolution.
1855  */
1856  Assert(agg_nargs <= numArguments);
1857 
1858  aggtranstype = enforce_generic_type_consistency(inputTypes,
1859  declaredArgTypes,
1860  agg_nargs,
1861  aggtranstype,
1862  false);
1863  pfree(declaredArgTypes);
1864  }
1865  return aggtranstype;
1866 }
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition: lsyscache.c:1500
unsigned int Oid
Definition: postgres_ext.h:31
void pfree(void *pointer)
Definition: mcxt.c:949
#define IsPolymorphicType(typid)
Definition: pg_type.h:745
Oid enforce_generic_type_consistency(Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
#define Assert(condition)
Definition: c.h:670

◆ transformAggregateCall()

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

Definition at line 103 of file parse_agg.c.

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

105 {
106  List *argtypes = NIL;
107  List *tlist = NIL;
108  List *torder = NIL;
109  List *tdistinct = NIL;
110  AttrNumber attno = 1;
111  int save_next_resno;
112  ListCell *lc;
113 
114  /*
115  * Before separating the args into direct and aggregated args, make a list
116  * of their data type OIDs for use later.
117  */
118  foreach(lc, args)
119  {
120  Expr *arg = (Expr *) lfirst(lc);
121 
122  argtypes = lappend_oid(argtypes, exprType((Node *) arg));
123  }
124  agg->aggargtypes = argtypes;
125 
127  {
128  /*
129  * For an ordered-set agg, the args list includes direct args and
130  * aggregated args; we must split them apart.
131  */
132  int numDirectArgs = list_length(args) - list_length(aggorder);
133  List *aargs;
134  ListCell *lc2;
135 
136  Assert(numDirectArgs >= 0);
137 
138  aargs = list_copy_tail(args, numDirectArgs);
139  agg->aggdirectargs = list_truncate(args, numDirectArgs);
140 
141  /*
142  * Build a tlist from the aggregated args, and make a sortlist entry
143  * for each one. Note that the expressions in the SortBy nodes are
144  * ignored (they are the raw versions of the transformed args); we are
145  * just looking at the sort information in the SortBy nodes.
146  */
147  forboth(lc, aargs, lc2, aggorder)
148  {
149  Expr *arg = (Expr *) lfirst(lc);
150  SortBy *sortby = (SortBy *) lfirst(lc2);
151  TargetEntry *tle;
152 
153  /* We don't bother to assign column names to the entries */
154  tle = makeTargetEntry(arg, attno++, NULL, false);
155  tlist = lappend(tlist, tle);
156 
157  torder = addTargetToSortList(pstate, tle,
158  torder, tlist, sortby);
159  }
160 
161  /* Never any DISTINCT in an ordered-set agg */
162  Assert(!agg_distinct);
163  }
164  else
165  {
166  /* Regular aggregate, so it has no direct args */
167  agg->aggdirectargs = NIL;
168 
169  /*
170  * Transform the plain list of Exprs into a targetlist.
171  */
172  foreach(lc, args)
173  {
174  Expr *arg = (Expr *) lfirst(lc);
175  TargetEntry *tle;
176 
177  /* We don't bother to assign column names to the entries */
178  tle = makeTargetEntry(arg, attno++, NULL, false);
179  tlist = lappend(tlist, tle);
180  }
181 
182  /*
183  * If we have an ORDER BY, transform it. This will add columns to the
184  * tlist if they appear in ORDER BY but weren't already in the arg
185  * list. They will be marked resjunk = true so we can tell them apart
186  * from regular aggregate arguments later.
187  *
188  * We need to mess with p_next_resno since it will be used to number
189  * any new targetlist entries.
190  */
191  save_next_resno = pstate->p_next_resno;
192  pstate->p_next_resno = attno;
193 
194  torder = transformSortClause(pstate,
195  aggorder,
196  &tlist,
198  true /* force SQL99 rules */ );
199 
200  /*
201  * If we have DISTINCT, transform that to produce a distinctList.
202  */
203  if (agg_distinct)
204  {
205  tdistinct = transformDistinctClause(pstate, &tlist, torder, true);
206 
207  /*
208  * Remove this check if executor support for hashed distinct for
209  * aggregates is ever added.
210  */
211  foreach(lc, tdistinct)
212  {
213  SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc);
214 
215  if (!OidIsValid(sortcl->sortop))
216  {
217  Node *expr = get_sortgroupclause_expr(sortcl, tlist);
218 
219  ereport(ERROR,
220  (errcode(ERRCODE_UNDEFINED_FUNCTION),
221  errmsg("could not identify an ordering operator for type %s",
222  format_type_be(exprType(expr))),
223  errdetail("Aggregates with DISTINCT must be able to sort their inputs."),
224  parser_errposition(pstate, exprLocation(expr))));
225  }
226  }
227  }
228 
229  pstate->p_next_resno = save_next_resno;
230  }
231 
232  /* Update the Aggref with the transformation results */
233  agg->args = tlist;
234  agg->aggorder = torder;
235  agg->aggdistinct = tdistinct;
236 
237  check_agglevels_and_constraints(pstate, (Node *) agg);
238 }
List * aggdistinct
Definition: primnodes.h:303
#define NIL
Definition: pg_list.h:69
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
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:350
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:382
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
List * args
Definition: primnodes.h:301
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition: parse_agg.c:287
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1203
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:576
#define AGGKIND_IS_ORDERED_SET(kind)
Definition: pg_aggregate.h:133
List * aggargtypes
Definition: primnodes.h:299
#define ERROR
Definition: elog.h:43
List * aggorder
Definition: primnodes.h:302
int errdetail(const char *fmt,...)
Definition: elog.c:873
int p_next_resno
Definition: parse_node.h:188
List * aggdirectargs
Definition: primnodes.h:300
#define ereport(elevel, rest)
Definition: elog.h:122
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:237
List * lappend(List *list, void *datum)
Definition: list.c:128
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
void * arg
char aggkind
Definition: primnodes.h:308
List * transformDistinctClause(ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21

◆ transformGroupingFunc()

Node* transformGroupingFunc ( ParseState pstate,
GroupingFunc p 
)

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

249 {
250  ListCell *lc;
251  List *args = p->args;
252  List *result_list = NIL;
254 
255  if (list_length(args) > 31)
256  ereport(ERROR,
257  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
258  errmsg("GROUPING must have fewer than 32 arguments"),
259  parser_errposition(pstate, p->location)));
260 
261  foreach(lc, args)
262  {
263  Node *current_result;
264 
265  current_result = transformExpr(pstate, (Node *) lfirst(lc), pstate->p_expr_kind);
266 
267  /* acceptability of expressions is checked later */
268 
269  result_list = lappend(result_list, current_result);
270  }
271 
272  result->args = result_list;
273  result->location = p->location;
274 
275  check_agglevels_and_constraints(pstate, (Node *) result);
276 
277  return (Node *) result;
278 }
#define NIL
Definition: pg_list.h:69
List * args
Definition: primnodes.h:341
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:146
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition: parse_agg.c:287
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
ParseExprKind p_expr_kind
Definition: parse_node.h:187
#define makeNode(_type_)
Definition: nodes.h:560
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
Definition: pg_list.h:45

◆ transformWindowFuncCall()

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

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

771 {
772  const char *err;
773  bool errkind;
774 
775  /*
776  * A window function call can't contain another one (but aggs are OK). XXX
777  * is this required by spec, or just an unimplemented feature?
778  *
779  * Note: we don't need to check the filter expression here, because the
780  * context checks done below and in transformAggregateCall would have
781  * already rejected any window funcs or aggs within the filter.
782  */
783  if (pstate->p_hasWindowFuncs &&
784  contain_windowfuncs((Node *) wfunc->args))
785  ereport(ERROR,
786  (errcode(ERRCODE_WINDOWING_ERROR),
787  errmsg("window function calls cannot be nested"),
788  parser_errposition(pstate,
789  locate_windowfunc((Node *) wfunc->args))));
790 
791  /*
792  * Check to see if the window function is in an invalid place within the
793  * query.
794  *
795  * For brevity we support two schemes for reporting an error here: set
796  * "err" to a custom message, or set "errkind" true if the error context
797  * is sufficiently identified by what ParseExprKindName will return, *and*
798  * what it will return is just a SQL keyword. (Otherwise, use a custom
799  * message to avoid creating translation problems.)
800  */
801  err = NULL;
802  errkind = false;
803  switch (pstate->p_expr_kind)
804  {
805  case EXPR_KIND_NONE:
806  Assert(false); /* can't happen */
807  break;
808  case EXPR_KIND_OTHER:
809  /* Accept window func here; caller must throw error if wanted */
810  break;
811  case EXPR_KIND_JOIN_ON:
813  err = _("window functions are not allowed in JOIN conditions");
814  break;
816  /* can't get here, but just in case, throw an error */
817  errkind = true;
818  break;
820  err = _("window functions are not allowed in functions in FROM");
821  break;
822  case EXPR_KIND_WHERE:
823  errkind = true;
824  break;
825  case EXPR_KIND_POLICY:
826  err = _("window functions are not allowed in policy expressions");
827  break;
828  case EXPR_KIND_HAVING:
829  errkind = true;
830  break;
831  case EXPR_KIND_FILTER:
832  errkind = true;
833  break;
838  err = _("window functions are not allowed in window definitions");
839  break;
841  /* okay */
842  break;
846  errkind = true;
847  break;
848  case EXPR_KIND_GROUP_BY:
849  errkind = true;
850  break;
851  case EXPR_KIND_ORDER_BY:
852  /* okay */
853  break;
855  /* okay */
856  break;
857  case EXPR_KIND_LIMIT:
858  case EXPR_KIND_OFFSET:
859  errkind = true;
860  break;
861  case EXPR_KIND_RETURNING:
862  errkind = true;
863  break;
864  case EXPR_KIND_VALUES:
866  errkind = true;
867  break;
870  err = _("window functions are not allowed in check constraints");
871  break;
874  err = _("window functions are not allowed in DEFAULT expressions");
875  break;
877  err = _("window functions are not allowed in index expressions");
878  break;
880  err = _("window functions are not allowed in index predicates");
881  break;
883  err = _("window functions are not allowed in transform expressions");
884  break;
886  err = _("window functions are not allowed in EXECUTE parameters");
887  break;
889  err = _("window functions are not allowed in trigger WHEN conditions");
890  break;
892  err = _("window functions are not allowed in partition key expression");
893  break;
894  case EXPR_KIND_CALL:
895  err = _("window functions are not allowed in CALL arguments");
896  break;
897 
898  /*
899  * There is intentionally no default: case here, so that the
900  * compiler will warn if we add a new ParseExprKind without
901  * extending this switch. If we do see an unrecognized value at
902  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
903  * which is sane anyway.
904  */
905  }
906  if (err)
907  ereport(ERROR,
908  (errcode(ERRCODE_WINDOWING_ERROR),
909  errmsg_internal("%s", err),
910  parser_errposition(pstate, wfunc->location)));
911  if (errkind)
912  ereport(ERROR,
913  (errcode(ERRCODE_WINDOWING_ERROR),
914  /* translator: %s is name of a SQL construct, eg GROUP BY */
915  errmsg("window functions are not allowed in %s",
916  ParseExprKindName(pstate->p_expr_kind)),
917  parser_errposition(pstate, wfunc->location)));
918 
919  /*
920  * If the OVER clause just specifies a window name, find that WINDOW
921  * clause (which had better be present). Otherwise, try to match all the
922  * properties of the OVER clause, and make a new entry in the p_windowdefs
923  * list if no luck.
924  */
925  if (windef->name)
926  {
927  Index winref = 0;
928  ListCell *lc;
929 
930  Assert(windef->refname == NULL &&
931  windef->partitionClause == NIL &&
932  windef->orderClause == NIL &&
934 
935  foreach(lc, pstate->p_windowdefs)
936  {
937  WindowDef *refwin = (WindowDef *) lfirst(lc);
938 
939  winref++;
940  if (refwin->name && strcmp(refwin->name, windef->name) == 0)
941  {
942  wfunc->winref = winref;
943  break;
944  }
945  }
946  if (lc == NULL) /* didn't find it? */
947  ereport(ERROR,
948  (errcode(ERRCODE_UNDEFINED_OBJECT),
949  errmsg("window \"%s\" does not exist", windef->name),
950  parser_errposition(pstate, windef->location)));
951  }
952  else
953  {
954  Index winref = 0;
955  ListCell *lc;
956 
957  foreach(lc, pstate->p_windowdefs)
958  {
959  WindowDef *refwin = (WindowDef *) lfirst(lc);
960 
961  winref++;
962  if (refwin->refname && windef->refname &&
963  strcmp(refwin->refname, windef->refname) == 0)
964  /* matched on refname */ ;
965  else if (!refwin->refname && !windef->refname)
966  /* matched, no refname */ ;
967  else
968  continue;
969  if (equal(refwin->partitionClause, windef->partitionClause) &&
970  equal(refwin->orderClause, windef->orderClause) &&
971  refwin->frameOptions == windef->frameOptions &&
972  equal(refwin->startOffset, windef->startOffset) &&
973  equal(refwin->endOffset, windef->endOffset))
974  {
975  /* found a duplicate window specification */
976  wfunc->winref = winref;
977  break;
978  }
979  }
980  if (lc == NULL) /* didn't find it? */
981  {
982  pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
983  wfunc->winref = list_length(pstate->p_windowdefs);
984  }
985  }
986 
987  pstate->p_hasWindowFuncs = true;
988 }
List * partitionClause
Definition: parsenodes.h:488
#define NIL
Definition: pg_list.h:69
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:524
List * args
Definition: primnodes.h:359
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2984
int frameOptions
Definition: parsenodes.h:490
char * name
Definition: parsenodes.h:486
Definition: nodes.h:512
int errcode(int sqlerrcode)
Definition: elog.c:575
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
Index winref
Definition: primnodes.h:361
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3399
bool p_hasWindowFuncs
Definition: parse_node.h:200
Node * startOffset
Definition: parsenodes.h:491
#define ERROR
Definition: elog.h:43
int location
Definition: parsenodes.h:493
List * p_windowdefs
Definition: parse_node.h:186
Node * endOffset
Definition: parsenodes.h:492
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
List * orderClause
Definition: parsenodes.h:489
unsigned int Index
Definition: c.h:413
ParseExprKind p_expr_kind
Definition: parse_node.h:187
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
int location
Definition: primnodes.h:364
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * refname
Definition: parsenodes.h:487
#define _(x)
Definition: elog.c:84
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197