PostgreSQL Source Code  git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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  substitute_grouped_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 Nodesubstitute_grouped_columns (Node *node, ParseState *pstate, Query *qry, List *groupClauses, List *groupClauseCommonVars, List *gset_common, bool have_non_var_grouping, List **func_grouped_rels)
 
static Nodesubstitute_grouped_columns_mutator (Node *node, substitute_grouped_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, substitute_grouped_columns_context *context)
 
static VarbuildGroupedVar (int attnum, Index ressortgroupref, substitute_grouped_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)
 
bool agg_args_support_sendreceive (Aggref *aggref)
 
void build_aggregate_transfn_expr (Oid *agg_input_types, int agg_num_inputs, int agg_num_direct_inputs, bool agg_variadic, Oid agg_state_type, Oid agg_input_collation, Oid transfn_oid, Oid invtransfn_oid, Expr **transfnexpr, Expr **invtransfnexpr)
 
void build_aggregate_serialfn_expr (Oid serialfn_oid, Expr **serialfnexpr)
 
void build_aggregate_deserialfn_expr (Oid deserialfn_oid, Expr **deserialfnexpr)
 
void build_aggregate_finalfn_expr (Oid *agg_input_types, int num_finalfn_inputs, Oid agg_state_type, Oid agg_result_type, Oid agg_input_collation, Oid finalfn_oid, Expr **finalfnexpr)
 

Function Documentation

◆ agg_args_support_sendreceive()

bool agg_args_support_sendreceive ( Aggref aggref)

Definition at line 2059 of file parse_agg.c.

2060 {
2061  ListCell *lc;
2062 
2063  foreach(lc, aggref->args)
2064  {
2065  HeapTuple typeTuple;
2066  Form_pg_type pt;
2067  TargetEntry *tle = (TargetEntry *) lfirst(lc);
2068  Oid type = exprType((Node *) tle->expr);
2069 
2070  typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type));
2071  if (!HeapTupleIsValid(typeTuple))
2072  elog(ERROR, "cache lookup failed for type %u", type);
2073 
2074  pt = (Form_pg_type) GETSTRUCT(typeTuple);
2075 
2076  if (!pt->typbyval &&
2077  (!OidIsValid(pt->typsend) || !OidIsValid(pt->typreceive)))
2078  {
2079  ReleaseSysCache(typeTuple);
2080  return false;
2081  }
2082  ReleaseSysCache(typeTuple);
2083  }
2084  return true;
2085 }
#define OidIsValid(objectId)
Definition: c.h:754
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
#define lfirst(lc)
Definition: pg_list.h:172
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
unsigned int Oid
Definition: postgres_ext.h:31
List * args
Definition: primnodes.h:468
Definition: nodes.h:129
Expr * expr
Definition: primnodes.h:2190
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221
const char * type

References Aggref::args, elog, ERROR, TargetEntry::expr, exprType(), GETSTRUCT, HeapTupleIsValid, lfirst, ObjectIdGetDatum(), OidIsValid, ReleaseSysCache(), SearchSysCache1(), and type.

Referenced by preprocess_aggref().

◆ build_aggregate_deserialfn_expr()

void build_aggregate_deserialfn_expr ( Oid  deserialfn_oid,
Expr **  deserialfnexpr 
)

Definition at line 2201 of file parse_agg.c.

2203 {
2204  List *args;
2205  FuncExpr *fexpr;
2206 
2207  /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2208  args = list_make2(make_agg_arg(BYTEAOID, InvalidOid),
2209  make_agg_arg(INTERNALOID, InvalidOid));
2210 
2211  fexpr = makeFuncExpr(deserialfn_oid,
2212  INTERNALOID,
2213  args,
2214  InvalidOid,
2215  InvalidOid,
2217  *deserialfnexpr = (Expr *) fexpr;
2218 }
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:544
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2265
#define list_make2(x1, x2)
Definition: pg_list.h:214
#define InvalidOid
Definition: postgres_ext.h:36
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:734
Definition: pg_list.h:54

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

Referenced by build_pertrans_for_aggref().

◆ build_aggregate_finalfn_expr()

void build_aggregate_finalfn_expr ( Oid agg_input_types,
int  num_finalfn_inputs,
Oid  agg_state_type,
Oid  agg_result_type,
Oid  agg_input_collation,
Oid  finalfn_oid,
Expr **  finalfnexpr 
)

Definition at line 2225 of file parse_agg.c.

2232 {
2233  List *args;
2234  int i;
2235 
2236  /*
2237  * Build expr tree for final function
2238  */
2239  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2240 
2241  /* finalfn may take additional args, which match agg's input types */
2242  for (i = 0; i < num_finalfn_inputs - 1; i++)
2243  {
2244  args = lappend(args,
2245  make_agg_arg(agg_input_types[i], agg_input_collation));
2246  }
2247 
2248  *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2249  agg_result_type,
2250  args,
2251  InvalidOid,
2252  agg_input_collation,
2254  /* finalfn is currently never treated as variadic */
2255 }
int i
Definition: isn.c:72
List * lappend(List *list, void *datum)
Definition: list.c:339
#define list_make1(x1)
Definition: pg_list.h:212

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

Referenced by ExecInitAgg(), and initialize_peragg().

◆ build_aggregate_serialfn_expr()

void build_aggregate_serialfn_expr ( Oid  serialfn_oid,
Expr **  serialfnexpr 
)

Definition at line 2178 of file parse_agg.c.

2180 {
2181  List *args;
2182  FuncExpr *fexpr;
2183 
2184  /* serialfn always takes INTERNAL and returns BYTEA */
2185  args = list_make1(make_agg_arg(INTERNALOID, InvalidOid));
2186 
2187  fexpr = makeFuncExpr(serialfn_oid,
2188  BYTEAOID,
2189  args,
2190  InvalidOid,
2191  InvalidOid,
2193  *serialfnexpr = (Expr *) fexpr;
2194 }

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

Referenced by build_pertrans_for_aggref().

◆ build_aggregate_transfn_expr()

void build_aggregate_transfn_expr ( Oid agg_input_types,
int  agg_num_inputs,
int  agg_num_direct_inputs,
bool  agg_variadic,
Oid  agg_state_type,
Oid  agg_input_collation,
Oid  transfn_oid,
Oid  invtransfn_oid,
Expr **  transfnexpr,
Expr **  invtransfnexpr 
)

Definition at line 2117 of file parse_agg.c.

2127 {
2128  List *args;
2129  FuncExpr *fexpr;
2130  int i;
2131 
2132  /*
2133  * Build arg list to use in the transfn FuncExpr node.
2134  */
2135  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2136 
2137  for (i = agg_num_direct_inputs; i < agg_num_inputs; i++)
2138  {
2139  args = lappend(args,
2140  make_agg_arg(agg_input_types[i], agg_input_collation));
2141  }
2142 
2143  fexpr = makeFuncExpr(transfn_oid,
2144  agg_state_type,
2145  args,
2146  InvalidOid,
2147  agg_input_collation,
2149  fexpr->funcvariadic = agg_variadic;
2150  *transfnexpr = (Expr *) fexpr;
2151 
2152  /*
2153  * Build invtransfn expression if requested, with same args as transfn
2154  */
2155  if (invtransfnexpr != NULL)
2156  {
2157  if (OidIsValid(invtransfn_oid))
2158  {
2159  fexpr = makeFuncExpr(invtransfn_oid,
2160  agg_state_type,
2161  args,
2162  InvalidOid,
2163  agg_input_collation,
2165  fexpr->funcvariadic = agg_variadic;
2166  *invtransfnexpr = (Expr *) fexpr;
2167  }
2168  else
2169  *invtransfnexpr = NULL;
2170  }
2171 }

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

Referenced by build_pertrans_for_aggref(), and initialize_peragg().

◆ buildGroupedVar()

static Var * buildGroupedVar ( int  attnum,
Index  ressortgroupref,
substitute_grouped_columns_context context 
)
static

Definition at line 1708 of file parse_agg.c.

1710 {
1711  Var *var;
1712  ParseNamespaceItem *grouping_nsitem = context->pstate->p_grouping_nsitem;
1713  ParseNamespaceColumn *nscol = grouping_nsitem->p_nscolumns + attnum - 1;
1714 
1715  Assert(nscol->p_varno == grouping_nsitem->p_rtindex);
1716  Assert(nscol->p_varattno == attnum);
1717  var = makeVar(nscol->p_varno,
1718  nscol->p_varattno,
1719  nscol->p_vartype,
1720  nscol->p_vartypmod,
1721  nscol->p_varcollid,
1722  context->sublevels_up);
1723  /* makeVar doesn't offer parameters for these, so set by hand: */
1724  var->varnosyn = nscol->p_varnosyn;
1725  var->varattnosyn = nscol->p_varattnosyn;
1726 
1727  if (context->qry->groupingSets &&
1728  !list_member_int(context->gset_common, ressortgroupref))
1729  var->varnullingrels =
1730  bms_add_member(var->varnullingrels, grouping_nsitem->p_rtindex);
1731 
1732  return var;
1733 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define Assert(condition)
Definition: c.h:837
bool list_member_int(const List *list, int datum)
Definition: list.c:702
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
int16 attnum
Definition: pg_attribute.h:74
tree context
Definition: radixtree.h:1835
AttrNumber p_varattno
Definition: parse_node.h:341
AttrNumber p_varattnosyn
Definition: parse_node.h:346
ParseNamespaceColumn * p_nscolumns
Definition: parse_node.h:310
Definition: primnodes.h:248

References Assert, attnum, bms_add_member(), context, list_member_int(), makeVar(), ParseNamespaceItem::p_nscolumns, ParseNamespaceItem::p_rtindex, ParseNamespaceColumn::p_varattno, ParseNamespaceColumn::p_varattnosyn, ParseNamespaceColumn::p_varcollid, ParseNamespaceColumn::p_varno, ParseNamespaceColumn::p_varnosyn, ParseNamespaceColumn::p_vartype, and ParseNamespaceColumn::p_vartypmod.

Referenced by substitute_grouped_columns_mutator().

◆ check_agg_arguments()

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

Definition at line 641 of file parse_agg.c.

645 {
646  int agglevel;
648 
649  context.pstate = pstate;
650  context.min_varlevel = -1; /* signifies nothing found yet */
651  context.min_agglevel = -1;
652  context.sublevels_up = 0;
653 
655  (void) check_agg_arguments_walker((Node *) filter, &context);
656 
657  /*
658  * If we found no vars nor aggs at all, it's a level-zero aggregate;
659  * otherwise, its level is the minimum of vars or aggs.
660  */
661  if (context.min_varlevel < 0)
662  {
663  if (context.min_agglevel < 0)
664  agglevel = 0;
665  else
666  agglevel = context.min_agglevel;
667  }
668  else if (context.min_agglevel < 0)
669  agglevel = context.min_varlevel;
670  else
671  agglevel = Min(context.min_varlevel, context.min_agglevel);
672 
673  /*
674  * If there's a nested aggregate of the same semantic level, complain.
675  */
676  if (agglevel == context.min_agglevel)
677  {
678  int aggloc;
679 
680  aggloc = locate_agg_of_level((Node *) args, agglevel);
681  if (aggloc < 0)
682  aggloc = locate_agg_of_level((Node *) filter, agglevel);
683  ereport(ERROR,
684  (errcode(ERRCODE_GROUPING_ERROR),
685  errmsg("aggregate function calls cannot be nested"),
686  parser_errposition(pstate, aggloc)));
687  }
688 
689  /*
690  * Now check for vars/aggs in the direct arguments, and throw error if
691  * needed. Note that we allow a Var of the agg's semantic level, but not
692  * an Agg of that level. In principle such Aggs could probably be
693  * supported, but it would create an ordering dependency among the
694  * aggregates at execution time. Since the case appears neither to be
695  * required by spec nor particularly useful, we just treat it as a
696  * nested-aggregate situation.
697  */
698  if (directargs)
699  {
700  context.min_varlevel = -1;
701  context.min_agglevel = -1;
702  (void) check_agg_arguments_walker((Node *) directargs, &context);
703  if (context.min_varlevel >= 0 && context.min_varlevel < agglevel)
704  ereport(ERROR,
705  (errcode(ERRCODE_GROUPING_ERROR),
706  errmsg("outer-level aggregate cannot contain a lower-level variable in its direct arguments"),
707  parser_errposition(pstate,
708  locate_var_of_level((Node *) directargs,
709  context.min_varlevel))));
710  if (context.min_agglevel >= 0 && context.min_agglevel <= agglevel)
711  ereport(ERROR,
712  (errcode(ERRCODE_GROUPING_ERROR),
713  errmsg("aggregate function calls cannot be nested"),
714  parser_errposition(pstate,
715  locate_agg_of_level((Node *) directargs,
716  context.min_agglevel))));
717  }
718  return agglevel;
719 }
#define Min(x, y)
Definition: c.h:983
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ereport(elevel,...)
Definition: elog.h:149
static bool check_agg_arguments_walker(Node *node, check_agg_arguments_context *context)
Definition: parse_agg.c:722
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:149
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:511

References generate_unaccent_rules::args, check_agg_arguments_walker(), context, ereport, errcode(), errmsg(), ERROR, locate_agg_of_level(), locate_var_of_level(), Min, and parser_errposition().

Referenced by check_agglevels_and_constraints().

◆ check_agg_arguments_walker()

static bool check_agg_arguments_walker ( Node node,
check_agg_arguments_context context 
)
static

Definition at line 722 of file parse_agg.c.

724 {
725  if (node == NULL)
726  return false;
727  if (IsA(node, Var))
728  {
729  int varlevelsup = ((Var *) node)->varlevelsup;
730 
731  /* convert levelsup to frame of reference of original query */
732  varlevelsup -= context->sublevels_up;
733  /* ignore local vars of subqueries */
734  if (varlevelsup >= 0)
735  {
736  if (context->min_varlevel < 0 ||
737  context->min_varlevel > varlevelsup)
738  context->min_varlevel = varlevelsup;
739  }
740  return false;
741  }
742  if (IsA(node, Aggref))
743  {
744  int agglevelsup = ((Aggref *) node)->agglevelsup;
745 
746  /* convert levelsup to frame of reference of original query */
747  agglevelsup -= context->sublevels_up;
748  /* ignore local aggs of subqueries */
749  if (agglevelsup >= 0)
750  {
751  if (context->min_agglevel < 0 ||
752  context->min_agglevel > agglevelsup)
753  context->min_agglevel = agglevelsup;
754  }
755  /* Continue and descend into subtree */
756  }
757  if (IsA(node, GroupingFunc))
758  {
759  int agglevelsup = ((GroupingFunc *) node)->agglevelsup;
760 
761  /* convert levelsup to frame of reference of original query */
762  agglevelsup -= context->sublevels_up;
763  /* ignore local aggs of subqueries */
764  if (agglevelsup >= 0)
765  {
766  if (context->min_agglevel < 0 ||
767  context->min_agglevel > agglevelsup)
768  context->min_agglevel = agglevelsup;
769  }
770  /* Continue and descend into subtree */
771  }
772 
773  /*
774  * SRFs and window functions can be rejected immediately, unless we are
775  * within a sub-select within the aggregate's arguments; in that case
776  * they're OK.
777  */
778  if (context->sublevels_up == 0)
779  {
780  if ((IsA(node, FuncExpr) && ((FuncExpr *) node)->funcretset) ||
781  (IsA(node, OpExpr) && ((OpExpr *) node)->opretset))
782  ereport(ERROR,
783  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
784  errmsg("aggregate function calls cannot contain set-returning function calls"),
785  errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
786  parser_errposition(context->pstate, exprLocation(node))));
787  if (IsA(node, WindowFunc))
788  ereport(ERROR,
789  (errcode(ERRCODE_GROUPING_ERROR),
790  errmsg("aggregate function calls cannot contain window function calls"),
791  parser_errposition(context->pstate,
792  ((WindowFunc *) node)->location)));
793  }
794  if (IsA(node, Query))
795  {
796  /* Recurse into subselects */
797  bool result;
798 
799  context->sublevels_up++;
800  result = query_tree_walker((Query *) node,
802  context,
803  0);
804  context->sublevels_up--;
805  return result;
806  }
807 
808  return expression_tree_walker(node,
810  context);
811 }
int errhint(const char *fmt,...)
Definition: elog.c:1317
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1380
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:158
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:153
#define IsA(nodeptr, _type_)
Definition: nodes.h:158

References context, ereport, errcode(), errhint(), errmsg(), ERROR, expression_tree_walker, exprLocation(), IsA, parser_errposition(), and query_tree_walker.

Referenced by check_agg_arguments().

◆ check_agglevels_and_constraints()

static void check_agglevels_and_constraints ( ParseState pstate,
Node expr 
)
static

Definition at line 304 of file parse_agg.c.

305 {
306  List *directargs = NIL;
307  List *args = NIL;
308  Expr *filter = NULL;
309  int min_varlevel;
310  int location = -1;
311  Index *p_levelsup;
312  const char *err;
313  bool errkind;
314  bool isAgg = IsA(expr, Aggref);
315 
316  if (isAgg)
317  {
318  Aggref *agg = (Aggref *) expr;
319 
320  directargs = agg->aggdirectargs;
321  args = agg->args;
322  filter = agg->aggfilter;
323  location = agg->location;
324  p_levelsup = &agg->agglevelsup;
325  }
326  else
327  {
328  GroupingFunc *grp = (GroupingFunc *) expr;
329 
330  args = grp->args;
331  location = grp->location;
332  p_levelsup = &grp->agglevelsup;
333  }
334 
335  /*
336  * Check the arguments to compute the aggregate's level and detect
337  * improper nesting.
338  */
339  min_varlevel = check_agg_arguments(pstate,
340  directargs,
341  args,
342  filter);
343 
344  *p_levelsup = min_varlevel;
345 
346  /* Mark the correct pstate level as having aggregates */
347  while (min_varlevel-- > 0)
348  pstate = pstate->parentParseState;
349  pstate->p_hasAggs = true;
350 
351  /*
352  * Check to see if the aggregate function is in an invalid place within
353  * its aggregation query.
354  *
355  * For brevity we support two schemes for reporting an error here: set
356  * "err" to a custom message, or set "errkind" true if the error context
357  * is sufficiently identified by what ParseExprKindName will return, *and*
358  * what it will return is just a SQL keyword. (Otherwise, use a custom
359  * message to avoid creating translation problems.)
360  */
361  err = NULL;
362  errkind = false;
363  switch (pstate->p_expr_kind)
364  {
365  case EXPR_KIND_NONE:
366  Assert(false); /* can't happen */
367  break;
368  case EXPR_KIND_OTHER:
369 
370  /*
371  * Accept aggregate/grouping here; caller must throw error if
372  * wanted
373  */
374  break;
375  case EXPR_KIND_JOIN_ON:
377  if (isAgg)
378  err = _("aggregate functions are not allowed in JOIN conditions");
379  else
380  err = _("grouping operations are not allowed in JOIN conditions");
381 
382  break;
384 
385  /*
386  * Aggregate/grouping scope rules make it worth being explicit
387  * here
388  */
389  if (isAgg)
390  err = _("aggregate functions are not allowed in FROM clause of their own query level");
391  else
392  err = _("grouping operations are not allowed in FROM clause of their own query level");
393 
394  break;
396  if (isAgg)
397  err = _("aggregate functions are not allowed in functions in FROM");
398  else
399  err = _("grouping operations are not allowed in functions in FROM");
400 
401  break;
402  case EXPR_KIND_WHERE:
403  errkind = true;
404  break;
405  case EXPR_KIND_POLICY:
406  if (isAgg)
407  err = _("aggregate functions are not allowed in policy expressions");
408  else
409  err = _("grouping operations are not allowed in policy expressions");
410 
411  break;
412  case EXPR_KIND_HAVING:
413  /* okay */
414  break;
415  case EXPR_KIND_FILTER:
416  errkind = true;
417  break;
419  /* okay */
420  break;
422  /* okay */
423  break;
425  if (isAgg)
426  err = _("aggregate functions are not allowed in window RANGE");
427  else
428  err = _("grouping operations are not allowed in window RANGE");
429 
430  break;
432  if (isAgg)
433  err = _("aggregate functions are not allowed in window ROWS");
434  else
435  err = _("grouping operations are not allowed in window ROWS");
436 
437  break;
439  if (isAgg)
440  err = _("aggregate functions are not allowed in window GROUPS");
441  else
442  err = _("grouping operations are not allowed in window GROUPS");
443 
444  break;
446  /* okay */
447  break;
451  errkind = true;
452  break;
454  if (isAgg)
455  err = _("aggregate functions are not allowed in MERGE WHEN conditions");
456  else
457  err = _("grouping operations are not allowed in MERGE WHEN conditions");
458 
459  break;
460  case EXPR_KIND_GROUP_BY:
461  errkind = true;
462  break;
463  case EXPR_KIND_ORDER_BY:
464  /* okay */
465  break;
467  /* okay */
468  break;
469  case EXPR_KIND_LIMIT:
470  case EXPR_KIND_OFFSET:
471  errkind = true;
472  break;
473  case EXPR_KIND_RETURNING:
475  errkind = true;
476  break;
477  case EXPR_KIND_VALUES:
479  errkind = true;
480  break;
483  if (isAgg)
484  err = _("aggregate functions are not allowed in check constraints");
485  else
486  err = _("grouping operations are not allowed in check constraints");
487 
488  break;
491 
492  if (isAgg)
493  err = _("aggregate functions are not allowed in DEFAULT expressions");
494  else
495  err = _("grouping operations are not allowed in DEFAULT expressions");
496 
497  break;
499  if (isAgg)
500  err = _("aggregate functions are not allowed in index expressions");
501  else
502  err = _("grouping operations are not allowed in index expressions");
503 
504  break;
506  if (isAgg)
507  err = _("aggregate functions are not allowed in index predicates");
508  else
509  err = _("grouping operations are not allowed in index predicates");
510 
511  break;
513  if (isAgg)
514  err = _("aggregate functions are not allowed in statistics expressions");
515  else
516  err = _("grouping operations are not allowed in statistics expressions");
517 
518  break;
520  if (isAgg)
521  err = _("aggregate functions are not allowed in transform expressions");
522  else
523  err = _("grouping operations are not allowed in transform expressions");
524 
525  break;
527  if (isAgg)
528  err = _("aggregate functions are not allowed in EXECUTE parameters");
529  else
530  err = _("grouping operations are not allowed in EXECUTE parameters");
531 
532  break;
534  if (isAgg)
535  err = _("aggregate functions are not allowed in trigger WHEN conditions");
536  else
537  err = _("grouping operations are not allowed in trigger WHEN conditions");
538 
539  break;
541  if (isAgg)
542  err = _("aggregate functions are not allowed in partition bound");
543  else
544  err = _("grouping operations are not allowed in partition bound");
545 
546  break;
548  if (isAgg)
549  err = _("aggregate functions are not allowed in partition key expressions");
550  else
551  err = _("grouping operations are not allowed in partition key expressions");
552 
553  break;
555 
556  if (isAgg)
557  err = _("aggregate functions are not allowed in column generation expressions");
558  else
559  err = _("grouping operations are not allowed in column generation expressions");
560 
561  break;
562 
564  if (isAgg)
565  err = _("aggregate functions are not allowed in CALL arguments");
566  else
567  err = _("grouping operations are not allowed in CALL arguments");
568 
569  break;
570 
572  if (isAgg)
573  err = _("aggregate functions are not allowed in COPY FROM WHERE conditions");
574  else
575  err = _("grouping operations are not allowed in COPY FROM WHERE conditions");
576 
577  break;
578 
580  errkind = true;
581  break;
582 
583  /*
584  * There is intentionally no default: case here, so that the
585  * compiler will warn if we add a new ParseExprKind without
586  * extending this switch. If we do see an unrecognized value at
587  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
588  * which is sane anyway.
589  */
590  }
591 
592  if (err)
593  ereport(ERROR,
594  (errcode(ERRCODE_GROUPING_ERROR),
595  errmsg_internal("%s", err),
596  parser_errposition(pstate, location)));
597 
598  if (errkind)
599  {
600  if (isAgg)
601  /* translator: %s is name of a SQL construct, eg GROUP BY */
602  err = _("aggregate functions are not allowed in %s");
603  else
604  /* translator: %s is name of a SQL construct, eg GROUP BY */
605  err = _("grouping operations are not allowed in %s");
606 
607  ereport(ERROR,
608  (errcode(ERRCODE_GROUPING_ERROR),
610  ParseExprKindName(pstate->p_expr_kind)),
611  parser_errposition(pstate, location)));
612  }
613 }
unsigned int Index
Definition: c.h:593
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
#define _(x)
Definition: elog.c:90
void err(int eval, const char *fmt,...)
Definition: err.c:43
static int check_agg_arguments(ParseState *pstate, List *directargs, List *args, Expr *filter)
Definition: parse_agg.c:641
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3111
@ EXPR_KIND_EXECUTE_PARAMETER
Definition: parse_node.h:76
@ EXPR_KIND_DOMAIN_CHECK
Definition: parse_node.h:69
@ EXPR_KIND_COPY_WHERE
Definition: parse_node.h:82
@ EXPR_KIND_COLUMN_DEFAULT
Definition: parse_node.h:70
@ EXPR_KIND_DISTINCT_ON
Definition: parse_node.h:61
@ EXPR_KIND_MERGE_WHEN
Definition: parse_node.h:58
@ EXPR_KIND_STATS_EXPRESSION
Definition: parse_node.h:74
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:72
@ EXPR_KIND_MERGE_RETURNING
Definition: parse_node.h:65
@ EXPR_KIND_PARTITION_BOUND
Definition: parse_node.h:79
@ EXPR_KIND_FUNCTION_DEFAULT
Definition: parse_node.h:71
@ EXPR_KIND_WINDOW_FRAME_RANGE
Definition: parse_node.h:51
@ EXPR_KIND_VALUES
Definition: parse_node.h:66
@ EXPR_KIND_FROM_SUBSELECT
Definition: parse_node.h:44
@ EXPR_KIND_POLICY
Definition: parse_node.h:78
@ EXPR_KIND_WINDOW_FRAME_GROUPS
Definition: parse_node.h:53
@ EXPR_KIND_PARTITION_EXPRESSION
Definition: parse_node.h:80
@ EXPR_KIND_JOIN_USING
Definition: parse_node.h:43
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:73
@ EXPR_KIND_ORDER_BY
Definition: parse_node.h:60
@ EXPR_KIND_OFFSET
Definition: parse_node.h:63
@ EXPR_KIND_JOIN_ON
Definition: parse_node.h:42
@ EXPR_KIND_HAVING
Definition: parse_node.h:47
@ EXPR_KIND_INSERT_TARGET
Definition: parse_node.h:55
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition: parse_node.h:75
@ EXPR_KIND_LIMIT
Definition: parse_node.h:62
@ EXPR_KIND_WHERE
Definition: parse_node.h:46
@ EXPR_KIND_UPDATE_TARGET
Definition: parse_node.h:57
@ EXPR_KIND_SELECT_TARGET
Definition: parse_node.h:54
@ EXPR_KIND_RETURNING
Definition: parse_node.h:64
@ EXPR_KIND_GENERATED_COLUMN
Definition: parse_node.h:83
@ EXPR_KIND_NONE
Definition: parse_node.h:40
@ EXPR_KIND_CALL_ARGUMENT
Definition: parse_node.h:81
@ EXPR_KIND_GROUP_BY
Definition: parse_node.h:59
@ EXPR_KIND_OTHER
Definition: parse_node.h:41
@ EXPR_KIND_FROM_FUNCTION
Definition: parse_node.h:45
@ EXPR_KIND_TRIGGER_WHEN
Definition: parse_node.h:77
@ EXPR_KIND_FILTER
Definition: parse_node.h:48
@ EXPR_KIND_UPDATE_SOURCE
Definition: parse_node.h:56
@ EXPR_KIND_CHECK_CONSTRAINT
Definition: parse_node.h:68
@ EXPR_KIND_WINDOW_PARTITION
Definition: parse_node.h:49
@ EXPR_KIND_CYCLE_MARK
Definition: parse_node.h:84
@ EXPR_KIND_WINDOW_FRAME_ROWS
Definition: parse_node.h:52
@ EXPR_KIND_WINDOW_ORDER
Definition: parse_node.h:50
@ EXPR_KIND_VALUES_SINGLE
Definition: parse_node.h:67
#define NIL
Definition: pg_list.h:68
List * aggdirectargs
Definition: primnodes.h:465
Expr * aggfilter
Definition: primnodes.h:477
ParseLoc location
Definition: primnodes.h:507
Index agglevelsup
Definition: primnodes.h:551
ParseLoc location
Definition: primnodes.h:554
ParseState * parentParseState
Definition: parse_node.h:208
ParseExprKind p_expr_kind
Definition: parse_node.h:230
bool p_hasAggs
Definition: parse_node.h:242

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

Referenced by transformAggregateCall(), and transformGroupingFunc().

◆ cmp_list_len_asc()

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

Definition at line 1850 of file parse_agg.c.

1851 {
1852  int la = list_length((const List *) lfirst(a));
1853  int lb = list_length((const List *) lfirst(b));
1854 
1855  return pg_cmp_s32(la, lb);
1856 }
static int pg_cmp_s32(int32 a, int32 b)
Definition: int.h:598
int b
Definition: isn.c:69
int a
Definition: isn.c:68
static int list_length(const List *l)
Definition: pg_list.h:152

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

Referenced by cmp_list_len_contents_asc(), and expand_grouping_sets().

◆ cmp_list_len_contents_asc()

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

Definition at line 1860 of file parse_agg.c.

1861 {
1862  int res = cmp_list_len_asc(a, b);
1863 
1864  if (res == 0)
1865  {
1866  List *la = (List *) lfirst(a);
1867  List *lb = (List *) lfirst(b);
1868  ListCell *lca;
1869  ListCell *lcb;
1870 
1871  forboth(lca, la, lcb, lb)
1872  {
1873  int va = lfirst_int(lca);
1874  int vb = lfirst_int(lcb);
1875 
1876  if (va > vb)
1877  return 1;
1878  if (va < vb)
1879  return -1;
1880  }
1881  }
1882 
1883  return res;
1884 }
Datum lca(PG_FUNCTION_ARGS)
Definition: ltree_op.c:568
static int cmp_list_len_asc(const ListCell *a, const ListCell *b)
Definition: parse_agg.c:1850
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
#define lfirst_int(lc)
Definition: pg_list.h:173

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

Referenced by expand_grouping_sets().

◆ expand_grouping_sets()

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

Definition at line 1894 of file parse_agg.c.

1895 {
1896  List *expanded_groups = NIL;
1897  List *result = NIL;
1898  double numsets = 1;
1899  ListCell *lc;
1900 
1901  if (groupingSets == NIL)
1902  return NIL;
1903 
1904  foreach(lc, groupingSets)
1905  {
1906  List *current_result = NIL;
1907  GroupingSet *gs = lfirst(lc);
1908 
1909  current_result = expand_groupingset_node(gs);
1910 
1911  Assert(current_result != NIL);
1912 
1913  numsets *= list_length(current_result);
1914 
1915  if (limit >= 0 && numsets > limit)
1916  return NIL;
1917 
1918  expanded_groups = lappend(expanded_groups, current_result);
1919  }
1920 
1921  /*
1922  * Do cartesian product between sublists of expanded_groups. While at it,
1923  * remove any duplicate elements from individual grouping sets (we must
1924  * NOT change the number of sets though)
1925  */
1926 
1927  foreach(lc, (List *) linitial(expanded_groups))
1928  {
1929  result = lappend(result, list_union_int(NIL, (List *) lfirst(lc)));
1930  }
1931 
1932  for_each_from(lc, expanded_groups, 1)
1933  {
1934  List *p = lfirst(lc);
1935  List *new_result = NIL;
1936  ListCell *lc2;
1937 
1938  foreach(lc2, result)
1939  {
1940  List *q = lfirst(lc2);
1941  ListCell *lc3;
1942 
1943  foreach(lc3, p)
1944  {
1945  new_result = lappend(new_result,
1946  list_union_int(q, (List *) lfirst(lc3)));
1947  }
1948  }
1949  result = new_result;
1950  }
1951 
1952  /* Now sort the lists by length and deduplicate if necessary */
1953  if (!groupDistinct || list_length(result) < 2)
1954  list_sort(result, cmp_list_len_asc);
1955  else
1956  {
1957  ListCell *cell;
1958  List *prev;
1959 
1960  /* Sort each groupset individually */
1961  foreach(cell, result)
1962  list_sort(lfirst(cell), list_int_cmp);
1963 
1964  /* Now sort the list of groupsets by length and contents */
1966 
1967  /* Finally, remove duplicates */
1968  prev = linitial(result);
1969  for_each_from(cell, result, 1)
1970  {
1971  if (equal(lfirst(cell), prev))
1972  result = foreach_delete_current(result, cell);
1973  else
1974  prev = lfirst(cell);
1975  }
1976  }
1977 
1978  return result;
1979 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
void list_sort(List *list, list_sort_comparator cmp)
Definition: list.c:1674
int list_int_cmp(const ListCell *p1, const ListCell *p2)
Definition: list.c:1691
List * list_union_int(const List *list1, const List *list2)
Definition: list.c:1113
static int cmp_list_len_contents_asc(const ListCell *a, const ListCell *b)
Definition: parse_agg.c:1860
static List * expand_groupingset_node(GroupingSet *gs)
Definition: parse_agg.c:1748
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
#define for_each_from(cell, lst, N)
Definition: pg_list.h:414
#define linitial(l)
Definition: pg_list.h:178

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

Referenced by parseCheckAggregates(), and preprocess_grouping_sets().

◆ expand_groupingset_node()

static List * expand_groupingset_node ( GroupingSet gs)
static

Definition at line 1748 of file parse_agg.c.

1749 {
1750  List *result = NIL;
1751 
1752  switch (gs->kind)
1753  {
1754  case GROUPING_SET_EMPTY:
1755  result = list_make1(NIL);
1756  break;
1757 
1758  case GROUPING_SET_SIMPLE:
1759  result = list_make1(gs->content);
1760  break;
1761 
1762  case GROUPING_SET_ROLLUP:
1763  {
1764  List *rollup_val = gs->content;
1765  ListCell *lc;
1766  int curgroup_size = list_length(gs->content);
1767 
1768  while (curgroup_size > 0)
1769  {
1770  List *current_result = NIL;
1771  int i = curgroup_size;
1772 
1773  foreach(lc, rollup_val)
1774  {
1775  GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
1776 
1777  Assert(gs_current->kind == GROUPING_SET_SIMPLE);
1778 
1779  current_result = list_concat(current_result,
1780  gs_current->content);
1781 
1782  /* If we are done with making the current group, break */
1783  if (--i == 0)
1784  break;
1785  }
1786 
1787  result = lappend(result, current_result);
1788  --curgroup_size;
1789  }
1790 
1791  result = lappend(result, NIL);
1792  }
1793  break;
1794 
1795  case GROUPING_SET_CUBE:
1796  {
1797  List *cube_list = gs->content;
1798  int number_bits = list_length(cube_list);
1799  uint32 num_sets;
1800  uint32 i;
1801 
1802  /* parser should cap this much lower */
1803  Assert(number_bits < 31);
1804 
1805  num_sets = (1U << number_bits);
1806 
1807  for (i = 0; i < num_sets; i++)
1808  {
1809  List *current_result = NIL;
1810  ListCell *lc;
1811  uint32 mask = 1U;
1812 
1813  foreach(lc, cube_list)
1814  {
1815  GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
1816 
1817  Assert(gs_current->kind == GROUPING_SET_SIMPLE);
1818 
1819  if (mask & i)
1820  current_result = list_concat(current_result,
1821  gs_current->content);
1822 
1823  mask <<= 1;
1824  }
1825 
1826  result = lappend(result, current_result);
1827  }
1828  }
1829  break;
1830 
1831  case GROUPING_SET_SETS:
1832  {
1833  ListCell *lc;
1834 
1835  foreach(lc, gs->content)
1836  {
1837  List *current_result = expand_groupingset_node(lfirst(lc));
1838 
1839  result = list_concat(result, current_result);
1840  }
1841  }
1842  break;
1843  }
1844 
1845  return result;
1846 }
unsigned int uint32
Definition: c.h:492
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
@ GROUPING_SET_CUBE
Definition: parsenodes.h:1502
@ GROUPING_SET_SIMPLE
Definition: parsenodes.h:1500
@ GROUPING_SET_ROLLUP
Definition: parsenodes.h:1501
@ GROUPING_SET_SETS
Definition: parsenodes.h:1503
@ GROUPING_SET_EMPTY
Definition: parsenodes.h:1499
List * content
Definition: parsenodes.h:1510

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

Referenced by expand_grouping_sets().

◆ finalize_grouping_exprs()

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

Definition at line 1541 of file parse_agg.c.

1544 {
1546 
1547  context.pstate = pstate;
1548  context.qry = qry;
1549  context.hasJoinRTEs = hasJoinRTEs;
1550  context.groupClauses = groupClauses;
1551  context.groupClauseCommonVars = NIL;
1552  context.gset_common = NIL;
1553  context.have_non_var_grouping = have_non_var_grouping;
1554  context.func_grouped_rels = NULL;
1555  context.sublevels_up = 0;
1556  context.in_agg_direct_args = false;
1558 }
static bool finalize_grouping_exprs_walker(Node *node, substitute_grouped_columns_context *context)
Definition: parse_agg.c:1561

References context, finalize_grouping_exprs_walker(), and NIL.

Referenced by parseCheckAggregates().

◆ finalize_grouping_exprs_walker()

static bool finalize_grouping_exprs_walker ( Node node,
substitute_grouped_columns_context context 
)
static

Definition at line 1561 of file parse_agg.c.

1563 {
1564  ListCell *gl;
1565 
1566  if (node == NULL)
1567  return false;
1568  if (IsA(node, Const) ||
1569  IsA(node, Param))
1570  return false; /* constants are always acceptable */
1571 
1572  if (IsA(node, Aggref))
1573  {
1574  Aggref *agg = (Aggref *) node;
1575 
1576  if ((int) agg->agglevelsup == context->sublevels_up)
1577  {
1578  /*
1579  * If we find an aggregate call of the original level, do not
1580  * recurse into its normal arguments, ORDER BY arguments, or
1581  * filter; GROUPING exprs of this level are not allowed there. But
1582  * check direct arguments as though they weren't in an aggregate.
1583  */
1584  bool result;
1585 
1586  Assert(!context->in_agg_direct_args);
1587  context->in_agg_direct_args = true;
1589  context);
1590  context->in_agg_direct_args = false;
1591  return result;
1592  }
1593 
1594  /*
1595  * We can skip recursing into aggregates of higher levels altogether,
1596  * since they could not possibly contain exprs of concern to us (see
1597  * transformAggregateCall). We do need to look at aggregates of lower
1598  * levels, however.
1599  */
1600  if ((int) agg->agglevelsup > context->sublevels_up)
1601  return false;
1602  }
1603 
1604  if (IsA(node, GroupingFunc))
1605  {
1606  GroupingFunc *grp = (GroupingFunc *) node;
1607 
1608  /*
1609  * We only need to check GroupingFunc nodes at the exact level to
1610  * which they belong, since they cannot mix levels in arguments.
1611  */
1612 
1613  if ((int) grp->agglevelsup == context->sublevels_up)
1614  {
1615  ListCell *lc;
1616  List *ref_list = NIL;
1617 
1618  foreach(lc, grp->args)
1619  {
1620  Node *expr = lfirst(lc);
1621  Index ref = 0;
1622 
1623  if (context->hasJoinRTEs)
1624  expr = flatten_join_alias_vars(NULL, context->qry, expr);
1625 
1626  /*
1627  * Each expression must match a grouping entry at the current
1628  * query level. Unlike the general expression case, we don't
1629  * allow functional dependencies or outer references.
1630  */
1631 
1632  if (IsA(expr, Var))
1633  {
1634  Var *var = (Var *) expr;
1635 
1636  if (var->varlevelsup == context->sublevels_up)
1637  {
1638  foreach(gl, context->groupClauses)
1639  {
1640  TargetEntry *tle = lfirst(gl);
1641  Var *gvar = (Var *) tle->expr;
1642 
1643  if (IsA(gvar, Var) &&
1644  gvar->varno == var->varno &&
1645  gvar->varattno == var->varattno &&
1646  gvar->varlevelsup == 0)
1647  {
1648  ref = tle->ressortgroupref;
1649  break;
1650  }
1651  }
1652  }
1653  }
1654  else if (context->have_non_var_grouping &&
1655  context->sublevels_up == 0)
1656  {
1657  foreach(gl, context->groupClauses)
1658  {
1659  TargetEntry *tle = lfirst(gl);
1660 
1661  if (equal(expr, tle->expr))
1662  {
1663  ref = tle->ressortgroupref;
1664  break;
1665  }
1666  }
1667  }
1668 
1669  if (ref == 0)
1670  ereport(ERROR,
1671  (errcode(ERRCODE_GROUPING_ERROR),
1672  errmsg("arguments to GROUPING must be grouping expressions of the associated query level"),
1673  parser_errposition(context->pstate,
1674  exprLocation(expr))));
1675 
1676  ref_list = lappend_int(ref_list, ref);
1677  }
1678 
1679  grp->refs = ref_list;
1680  }
1681 
1682  if ((int) grp->agglevelsup > context->sublevels_up)
1683  return false;
1684  }
1685 
1686  if (IsA(node, Query))
1687  {
1688  /* Recurse into subselects */
1689  bool result;
1690 
1691  context->sublevels_up++;
1692  result = query_tree_walker((Query *) node,
1694  context,
1695  0);
1696  context->sublevels_up--;
1697  return result;
1698  }
1700  context);
1701 }
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:76
List * lappend_int(List *list, int datum)
Definition: list.c:357
Index ressortgroupref
Definition: primnodes.h:2196
AttrNumber varattno
Definition: primnodes.h:260
int varno
Definition: primnodes.h:255
Index varlevelsup
Definition: primnodes.h:280
Node * flatten_join_alias_vars(PlannerInfo *root, Query *query, Node *node)
Definition: var.c:745

References Aggref::aggdirectargs, GroupingFunc::agglevelsup, Assert, context, equal(), ereport, errcode(), errmsg(), ERROR, TargetEntry::expr, expression_tree_walker, exprLocation(), flatten_join_alias_vars(), if(), IsA, lappend_int(), lfirst, NIL, parser_errposition(), query_tree_walker, TargetEntry::ressortgroupref, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by finalize_grouping_exprs().

◆ get_aggregate_argtypes()

int get_aggregate_argtypes ( Aggref aggref,
Oid inputTypes 
)

Definition at line 1997 of file parse_agg.c.

1998 {
1999  int numArguments = 0;
2000  ListCell *lc;
2001 
2002  Assert(list_length(aggref->aggargtypes) <= FUNC_MAX_ARGS);
2003 
2004  foreach(lc, aggref->aggargtypes)
2005  {
2006  inputTypes[numArguments++] = lfirst_oid(lc);
2007  }
2008 
2009  return numArguments;
2010 }
#define FUNC_MAX_ARGS
#define lfirst_oid(lc)
Definition: pg_list.h:174

References Assert, FUNC_MAX_ARGS, lfirst_oid, and list_length().

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

◆ make_agg_arg()

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

Definition at line 2265 of file parse_agg.c.

2266 {
2267  Param *argp = makeNode(Param);
2268 
2269  argp->paramkind = PARAM_EXEC;
2270  argp->paramid = -1;
2271  argp->paramtype = argtype;
2272  argp->paramtypmod = -1;
2273  argp->paramcollid = argcollation;
2274  argp->location = -1;
2275  return (Node *) argp;
2276 }
#define makeNode(_type_)
Definition: nodes.h:155
@ PARAM_EXEC
Definition: primnodes.h:368
ParseLoc location
Definition: primnodes.h:384
int paramid
Definition: primnodes.h:377
Oid paramtype
Definition: primnodes.h:378
ParamKind paramkind
Definition: primnodes.h:376

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

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

◆ parseCheckAggregates()

void parseCheckAggregates ( ParseState pstate,
Query qry 
)

Definition at line 1085 of file parse_agg.c.

1086 {
1087  List *gset_common = NIL;
1088  List *groupClauses = NIL;
1089  List *groupClauseCommonVars = NIL;
1090  bool have_non_var_grouping;
1091  List *func_grouped_rels = NIL;
1092  ListCell *l;
1093  bool hasJoinRTEs;
1094  bool hasSelfRefRTEs;
1095  Node *clause;
1096 
1097  /* This should only be called if we found aggregates or grouping */
1098  Assert(pstate->p_hasAggs || qry->groupClause || qry->havingQual || qry->groupingSets);
1099 
1100  /*
1101  * If we have grouping sets, expand them and find the intersection of all
1102  * sets.
1103  */
1104  if (qry->groupingSets)
1105  {
1106  /*
1107  * The limit of 4096 is arbitrary and exists simply to avoid resource
1108  * issues from pathological constructs.
1109  */
1110  List *gsets = expand_grouping_sets(qry->groupingSets, qry->groupDistinct, 4096);
1111 
1112  if (!gsets)
1113  ereport(ERROR,
1114  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
1115  errmsg("too many grouping sets present (maximum 4096)"),
1116  parser_errposition(pstate,
1117  qry->groupClause
1118  ? exprLocation((Node *) qry->groupClause)
1119  : exprLocation((Node *) qry->groupingSets))));
1120 
1121  /*
1122  * The intersection will often be empty, so help things along by
1123  * seeding the intersect with the smallest set.
1124  */
1125  gset_common = linitial(gsets);
1126 
1127  if (gset_common)
1128  {
1129  for_each_from(l, gsets, 1)
1130  {
1131  gset_common = list_intersection_int(gset_common, lfirst(l));
1132  if (!gset_common)
1133  break;
1134  }
1135  }
1136 
1137  /*
1138  * If there was only one grouping set in the expansion, AND if the
1139  * groupClause is non-empty (meaning that the grouping set is not
1140  * empty either), then we can ditch the grouping set and pretend we
1141  * just had a normal GROUP BY.
1142  */
1143  if (list_length(gsets) == 1 && qry->groupClause)
1144  qry->groupingSets = NIL;
1145  }
1146 
1147  /*
1148  * Scan the range table to see if there are JOIN or self-reference CTE
1149  * entries. We'll need this info below.
1150  */
1151  hasJoinRTEs = hasSelfRefRTEs = false;
1152  foreach(l, pstate->p_rtable)
1153  {
1154  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
1155 
1156  if (rte->rtekind == RTE_JOIN)
1157  hasJoinRTEs = true;
1158  else if (rte->rtekind == RTE_CTE && rte->self_reference)
1159  hasSelfRefRTEs = true;
1160  }
1161 
1162  /*
1163  * Build a list of the acceptable GROUP BY expressions for use by
1164  * substitute_grouped_columns().
1165  *
1166  * We get the TLE, not just the expr, because GROUPING wants to know the
1167  * sortgroupref.
1168  */
1169  foreach(l, qry->groupClause)
1170  {
1171  SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
1172  TargetEntry *expr;
1173 
1174  expr = get_sortgroupclause_tle(grpcl, qry->targetList);
1175  if (expr == NULL)
1176  continue; /* probably cannot happen */
1177 
1178  groupClauses = lappend(groupClauses, expr);
1179  }
1180 
1181  /*
1182  * If there are join alias vars involved, we have to flatten them to the
1183  * underlying vars, so that aliased and unaliased vars will be correctly
1184  * taken as equal. We can skip the expense of doing this if no rangetable
1185  * entries are RTE_JOIN kind.
1186  */
1187  if (hasJoinRTEs)
1188  groupClauses = (List *) flatten_join_alias_vars(NULL, qry,
1189  (Node *) groupClauses);
1190 
1191  /*
1192  * Detect whether any of the grouping expressions aren't simple Vars; if
1193  * they're all Vars then we don't have to work so hard in the recursive
1194  * scans. (Note we have to flatten aliases before this.)
1195  *
1196  * Track Vars that are included in all grouping sets separately in
1197  * groupClauseCommonVars, since these are the only ones we can use to
1198  * check for functional dependencies.
1199  */
1200  have_non_var_grouping = false;
1201  foreach(l, groupClauses)
1202  {
1203  TargetEntry *tle = lfirst(l);
1204 
1205  if (!IsA(tle->expr, Var))
1206  {
1207  have_non_var_grouping = true;
1208  }
1209  else if (!qry->groupingSets ||
1210  list_member_int(gset_common, tle->ressortgroupref))
1211  {
1212  groupClauseCommonVars = lappend(groupClauseCommonVars, tle->expr);
1213  }
1214  }
1215 
1216  /*
1217  * If there are any acceptable GROUP BY expressions, build an RTE and
1218  * nsitem for the result of the grouping step.
1219  */
1220  if (groupClauses)
1221  {
1222  pstate->p_grouping_nsitem =
1223  addRangeTableEntryForGroup(pstate, groupClauses);
1224 
1225  /* Set qry->rtable again in case it was previously NIL */
1226  qry->rtable = pstate->p_rtable;
1227  /* Mark the Query as having RTE_GROUP RTE */
1228  qry->hasGroupRTE = true;
1229  }
1230 
1231  /*
1232  * Replace grouped variables in the targetlist and HAVING clause with Vars
1233  * that reference the RTE_GROUP RTE. Emit an error message if we find any
1234  * ungrouped variables.
1235  *
1236  * Note: because we check resjunk tlist elements as well as regular ones,
1237  * this will also find ungrouped variables that came from ORDER BY and
1238  * WINDOW clauses. For that matter, it's also going to examine the
1239  * grouping expressions themselves --- but they'll all pass the test ...
1240  *
1241  * We also finalize GROUPING expressions, but for that we need to traverse
1242  * the original (unflattened) clause in order to modify nodes.
1243  */
1244  clause = (Node *) qry->targetList;
1245  finalize_grouping_exprs(clause, pstate, qry,
1246  groupClauses, hasJoinRTEs,
1247  have_non_var_grouping);
1248  if (hasJoinRTEs)
1249  clause = flatten_join_alias_vars(NULL, qry, clause);
1250  qry->targetList = (List *)
1251  substitute_grouped_columns(clause, pstate, qry,
1252  groupClauses, groupClauseCommonVars,
1253  gset_common,
1254  have_non_var_grouping,
1255  &func_grouped_rels);
1256 
1257  clause = (Node *) qry->havingQual;
1258  finalize_grouping_exprs(clause, pstate, qry,
1259  groupClauses, hasJoinRTEs,
1260  have_non_var_grouping);
1261  if (hasJoinRTEs)
1262  clause = flatten_join_alias_vars(NULL, qry, clause);
1263  qry->havingQual =
1264  substitute_grouped_columns(clause, pstate, qry,
1265  groupClauses, groupClauseCommonVars,
1266  gset_common,
1267  have_non_var_grouping,
1268  &func_grouped_rels);
1269 
1270  /*
1271  * Per spec, aggregates can't appear in a recursive term.
1272  */
1273  if (pstate->p_hasAggs && hasSelfRefRTEs)
1274  ereport(ERROR,
1275  (errcode(ERRCODE_INVALID_RECURSION),
1276  errmsg("aggregate functions are not allowed in a recursive query's recursive term"),
1277  parser_errposition(pstate,
1278  locate_agg_of_level((Node *) qry, 0))));
1279 }
List * list_intersection_int(const List *list1, const List *list2)
Definition: list.c:1200
static void finalize_grouping_exprs(Node *node, ParseState *pstate, Query *qry, List *groupClauses, bool hasJoinRTEs, bool have_non_var_grouping)
Definition: parse_agg.c:1541
List * expand_grouping_sets(List *groupingSets, bool groupDistinct, int limit)
Definition: parse_agg.c:1894
static Node * substitute_grouped_columns(Node *node, ParseState *pstate, Query *qry, List *groupClauses, List *groupClauseCommonVars, List *gset_common, bool have_non_var_grouping, List **func_grouped_rels)
Definition: parse_agg.c:1305
ParseNamespaceItem * addRangeTableEntryForGroup(ParseState *pstate, List *groupClauses)
@ RTE_JOIN
Definition: parsenodes.h:1019
@ RTE_CTE
Definition: parsenodes.h:1023
ParseNamespaceItem * p_grouping_nsitem
Definition: parse_node.h:227
List * p_rtable
Definition: parse_node.h:212
bool groupDistinct
Definition: parsenodes.h:203
List * groupClause
Definition: parsenodes.h:202
Node * havingQual
Definition: parsenodes.h:207
List * rtable
Definition: parsenodes.h:170
List * targetList
Definition: parsenodes.h:193
List * groupingSets
Definition: parsenodes.h:205
RTEKind rtekind
Definition: parsenodes.h:1047
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:367

References addRangeTableEntryForGroup(), Assert, 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_grouping_nsitem, ParseState::p_hasAggs, ParseState::p_rtable, parser_errposition(), TargetEntry::ressortgroupref, Query::rtable, RTE_CTE, RTE_JOIN, RangeTblEntry::rtekind, substitute_grouped_columns(), and Query::targetList.

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

◆ resolve_aggregate_transtype()

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

Definition at line 2023 of file parse_agg.c.

2027 {
2028  /* resolve actual type of transition state, if polymorphic */
2029  if (IsPolymorphicType(aggtranstype))
2030  {
2031  /* have to fetch the agg's declared input types... */
2032  Oid *declaredArgTypes;
2033  int agg_nargs;
2034 
2035  (void) get_func_signature(aggfuncid, &declaredArgTypes, &agg_nargs);
2036 
2037  /*
2038  * VARIADIC ANY aggs could have more actual than declared args, but
2039  * such extra args can't affect polymorphic type resolution.
2040  */
2041  Assert(agg_nargs <= numArguments);
2042 
2043  aggtranstype = enforce_generic_type_consistency(inputTypes,
2044  declaredArgTypes,
2045  agg_nargs,
2046  aggtranstype,
2047  false);
2048  pfree(declaredArgTypes);
2049  }
2050  return aggtranstype;
2051 }
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition: lsyscache.c:1696
void pfree(void *pointer)
Definition: mcxt.c:1521
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)

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

Referenced by initialize_peragg(), and preprocess_aggref().

◆ substitute_grouped_columns()

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

Definition at line 1305 of file parse_agg.c.

1310 {
1312 
1313  context.pstate = pstate;
1314  context.qry = qry;
1315  context.hasJoinRTEs = false; /* assume caller flattened join Vars */
1316  context.groupClauses = groupClauses;
1317  context.groupClauseCommonVars = groupClauseCommonVars;
1318  context.gset_common = gset_common;
1319  context.have_non_var_grouping = have_non_var_grouping;
1320  context.func_grouped_rels = func_grouped_rels;
1321  context.sublevels_up = 0;
1322  context.in_agg_direct_args = false;
1324 }
static Node * substitute_grouped_columns_mutator(Node *node, substitute_grouped_columns_context *context)
Definition: parse_agg.c:1327

References context, and substitute_grouped_columns_mutator().

Referenced by parseCheckAggregates().

◆ substitute_grouped_columns_mutator()

static Node * substitute_grouped_columns_mutator ( Node node,
substitute_grouped_columns_context context 
)
static

Definition at line 1327 of file parse_agg.c.

1329 {
1330  ListCell *gl;
1331 
1332  if (node == NULL)
1333  return NULL;
1334 
1335  if (IsA(node, Aggref))
1336  {
1337  Aggref *agg = (Aggref *) node;
1338 
1339  if ((int) agg->agglevelsup == context->sublevels_up)
1340  {
1341  /*
1342  * If we find an aggregate call of the original level, do not
1343  * recurse into its normal arguments, ORDER BY arguments, or
1344  * filter; grouped vars there do not need to be replaced and
1345  * ungrouped vars there are not an error. But we should check
1346  * direct arguments as though they weren't in an aggregate. We
1347  * set a special flag in the context to help produce a useful
1348  * error message for ungrouped vars in direct arguments.
1349  */
1350  agg = copyObject(agg);
1351 
1352  Assert(!context->in_agg_direct_args);
1353  context->in_agg_direct_args = true;
1354  agg->aggdirectargs = (List *)
1356  context);
1357  context->in_agg_direct_args = false;
1358  return (Node *) agg;
1359  }
1360 
1361  /*
1362  * We can skip recursing into aggregates of higher levels altogether,
1363  * since they could not possibly contain Vars of concern to us (see
1364  * transformAggregateCall). We do need to look at aggregates of lower
1365  * levels, however.
1366  */
1367  if ((int) agg->agglevelsup > context->sublevels_up)
1368  return node;
1369  }
1370 
1371  if (IsA(node, GroupingFunc))
1372  {
1373  GroupingFunc *grp = (GroupingFunc *) node;
1374 
1375  /* handled GroupingFunc separately, no need to recheck at this level */
1376 
1377  if ((int) grp->agglevelsup >= context->sublevels_up)
1378  return node;
1379  }
1380 
1381  /*
1382  * If we have any GROUP BY items that are not simple Vars, check to see if
1383  * subexpression as a whole matches any GROUP BY item. We need to do this
1384  * at every recursion level so that we recognize GROUPed-BY expressions
1385  * before reaching variables within them. But this only works at the outer
1386  * query level, as noted above.
1387  */
1388  if (context->have_non_var_grouping && context->sublevels_up == 0)
1389  {
1390  int attnum = 0;
1391 
1392  foreach(gl, context->groupClauses)
1393  {
1394  TargetEntry *tle = (TargetEntry *) lfirst(gl);
1395 
1396  attnum++;
1397  if (equal(node, tle->expr))
1398  {
1399  /* acceptable, replace it with a GROUP Var */
1400  return (Node *) buildGroupedVar(attnum,
1401  tle->ressortgroupref,
1402  context);
1403  }
1404  }
1405  }
1406 
1407  /*
1408  * Constants are always acceptable. We have to do this after we checked
1409  * the subexpression as a whole for a match, because it is possible that
1410  * we have GROUP BY items that are constants, and the constants would
1411  * become not so constant after the grouping step.
1412  */
1413  if (IsA(node, Const) ||
1414  IsA(node, Param))
1415  return node;
1416 
1417  /*
1418  * If we have an ungrouped Var of the original query level, we have a
1419  * failure. Vars below the original query level are not a problem, and
1420  * neither are Vars from above it. (If such Vars are ungrouped as far as
1421  * their own query level is concerned, that's someone else's problem...)
1422  */
1423  if (IsA(node, Var))
1424  {
1425  Var *var = (Var *) node;
1426  RangeTblEntry *rte;
1427  char *attname;
1428 
1429  if (var->varlevelsup != context->sublevels_up)
1430  return node; /* it's not local to my query, ignore */
1431 
1432  /*
1433  * Check for a match, if we didn't do it above.
1434  */
1435  if (!context->have_non_var_grouping || context->sublevels_up != 0)
1436  {
1437  int attnum = 0;
1438 
1439  foreach(gl, context->groupClauses)
1440  {
1441  TargetEntry *tle = (TargetEntry *) lfirst(gl);
1442  Var *gvar = (Var *) tle->expr;
1443 
1444  attnum++;
1445  if (IsA(gvar, Var) &&
1446  gvar->varno == var->varno &&
1447  gvar->varattno == var->varattno &&
1448  gvar->varlevelsup == 0)
1449  {
1450  /* acceptable, replace it with a GROUP Var */
1451  return (Node *) buildGroupedVar(attnum,
1452  tle->ressortgroupref,
1453  context);
1454  }
1455  }
1456  }
1457 
1458  /*
1459  * Check whether the Var is known functionally dependent on the GROUP
1460  * BY columns. If so, we can allow the Var to be used, because the
1461  * grouping is really a no-op for this table. However, this deduction
1462  * depends on one or more constraints of the table, so we have to add
1463  * those constraints to the query's constraintDeps list, because it's
1464  * not semantically valid anymore if the constraint(s) get dropped.
1465  * (Therefore, this check must be the last-ditch effort before raising
1466  * error: we don't want to add dependencies unnecessarily.)
1467  *
1468  * Because this is a pretty expensive check, and will have the same
1469  * outcome for all columns of a table, we remember which RTEs we've
1470  * already proven functional dependency for in the func_grouped_rels
1471  * list. This test also prevents us from adding duplicate entries to
1472  * the constraintDeps list.
1473  */
1474  if (list_member_int(*context->func_grouped_rels, var->varno))
1475  return node; /* previously proven acceptable */
1476 
1477  Assert(var->varno > 0 &&
1478  (int) var->varno <= list_length(context->pstate->p_rtable));
1479  rte = rt_fetch(var->varno, context->pstate->p_rtable);
1480  if (rte->rtekind == RTE_RELATION)
1481  {
1483  var->varno,
1484  0,
1485  context->groupClauseCommonVars,
1486  &context->qry->constraintDeps))
1487  {
1488  *context->func_grouped_rels =
1489  lappend_int(*context->func_grouped_rels, var->varno);
1490  return node; /* acceptable */
1491  }
1492  }
1493 
1494  /* Found an ungrouped local variable; generate error message */
1496  if (context->sublevels_up == 0)
1497  ereport(ERROR,
1498  (errcode(ERRCODE_GROUPING_ERROR),
1499  errmsg("column \"%s.%s\" must appear in the GROUP BY clause or be used in an aggregate function",
1500  rte->eref->aliasname, attname),
1501  context->in_agg_direct_args ?
1502  errdetail("Direct arguments of an ordered-set aggregate must use only grouped columns.") : 0,
1503  parser_errposition(context->pstate, var->location)));
1504  else
1505  ereport(ERROR,
1506  (errcode(ERRCODE_GROUPING_ERROR),
1507  errmsg("subquery uses ungrouped column \"%s.%s\" from outer query",
1508  rte->eref->aliasname, attname),
1509  parser_errposition(context->pstate, var->location)));
1510  }
1511 
1512  if (IsA(node, Query))
1513  {
1514  /* Recurse into subselects */
1515  Query *newnode;
1516 
1517  context->sublevels_up++;
1518  newnode = query_tree_mutator((Query *) node,
1520  context,
1521  0);
1522  context->sublevels_up--;
1523  return (Node *) newnode;
1524  }
1526  context);
1527 }
int errdetail(const char *fmt,...)
Definition: elog.c:1203
#define expression_tree_mutator(n, m, c)
Definition: nodeFuncs.h:155
#define query_tree_mutator(q, m, c, f)
Definition: nodeFuncs.h:160
#define copyObject(obj)
Definition: nodes.h:224
static Var * buildGroupedVar(int attnum, Index ressortgroupref, substitute_grouped_columns_context *context)
Definition: parse_agg.c:1708
char * get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
@ RTE_RELATION
Definition: parsenodes.h:1017
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
NameData attname
Definition: pg_attribute.h:41
bool check_functional_grouping(Oid relid, Index varno, Index varlevelsup, List *grouping_columns, List **constraintDeps)
ParseLoc location
Definition: primnodes.h:293

References Aggref::aggdirectargs, GroupingFunc::agglevelsup, Assert, attname, attnum, buildGroupedVar(), check_functional_grouping(), context, copyObject, equal(), ereport, errcode(), errdetail(), errmsg(), ERROR, TargetEntry::expr, expression_tree_mutator, get_rte_attribute_name(), if(), IsA, lappend_int(), lfirst, list_length(), list_member_int(), Var::location, parser_errposition(), query_tree_mutator, RangeTblEntry::relid, TargetEntry::ressortgroupref, rt_fetch, RTE_RELATION, RangeTblEntry::rtekind, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by substitute_grouped_columns().

◆ transformAggregateCall()

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

Definition at line 109 of file parse_agg.c.

111 {
112  List *argtypes = NIL;
113  List *tlist = NIL;
114  List *torder = NIL;
115  List *tdistinct = NIL;
116  AttrNumber attno = 1;
117  int save_next_resno;
118  ListCell *lc;
119 
120  if (AGGKIND_IS_ORDERED_SET(agg->aggkind))
121  {
122  /*
123  * For an ordered-set agg, the args list includes direct args and
124  * aggregated args; we must split them apart.
125  */
126  int numDirectArgs = list_length(args) - list_length(aggorder);
127  List *aargs;
128  ListCell *lc2;
129 
130  Assert(numDirectArgs >= 0);
131 
132  aargs = list_copy_tail(args, numDirectArgs);
133  agg->aggdirectargs = list_truncate(args, numDirectArgs);
134 
135  /*
136  * Build a tlist from the aggregated args, and make a sortlist entry
137  * for each one. Note that the expressions in the SortBy nodes are
138  * ignored (they are the raw versions of the transformed args); we are
139  * just looking at the sort information in the SortBy nodes.
140  */
141  forboth(lc, aargs, lc2, aggorder)
142  {
143  Expr *arg = (Expr *) lfirst(lc);
144  SortBy *sortby = (SortBy *) lfirst(lc2);
145  TargetEntry *tle;
146 
147  /* We don't bother to assign column names to the entries */
148  tle = makeTargetEntry(arg, attno++, NULL, false);
149  tlist = lappend(tlist, tle);
150 
151  torder = addTargetToSortList(pstate, tle,
152  torder, tlist, sortby);
153  }
154 
155  /* Never any DISTINCT in an ordered-set agg */
156  Assert(!agg_distinct);
157  }
158  else
159  {
160  /* Regular aggregate, so it has no direct args */
161  agg->aggdirectargs = NIL;
162 
163  /*
164  * Transform the plain list of Exprs into a targetlist.
165  */
166  foreach(lc, args)
167  {
168  Expr *arg = (Expr *) lfirst(lc);
169  TargetEntry *tle;
170 
171  /* We don't bother to assign column names to the entries */
172  tle = makeTargetEntry(arg, attno++, NULL, false);
173  tlist = lappend(tlist, tle);
174  }
175 
176  /*
177  * If we have an ORDER BY, transform it. This will add columns to the
178  * tlist if they appear in ORDER BY but weren't already in the arg
179  * list. They will be marked resjunk = true so we can tell them apart
180  * from regular aggregate arguments later.
181  *
182  * We need to mess with p_next_resno since it will be used to number
183  * any new targetlist entries.
184  */
185  save_next_resno = pstate->p_next_resno;
186  pstate->p_next_resno = attno;
187 
188  torder = transformSortClause(pstate,
189  aggorder,
190  &tlist,
192  true /* force SQL99 rules */ );
193 
194  /*
195  * If we have DISTINCT, transform that to produce a distinctList.
196  */
197  if (agg_distinct)
198  {
199  tdistinct = transformDistinctClause(pstate, &tlist, torder, true);
200 
201  /*
202  * Remove this check if executor support for hashed distinct for
203  * aggregates is ever added.
204  */
205  foreach(lc, tdistinct)
206  {
207  SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc);
208 
209  if (!OidIsValid(sortcl->sortop))
210  {
211  Node *expr = get_sortgroupclause_expr(sortcl, tlist);
212 
213  ereport(ERROR,
214  (errcode(ERRCODE_UNDEFINED_FUNCTION),
215  errmsg("could not identify an ordering operator for type %s",
216  format_type_be(exprType(expr))),
217  errdetail("Aggregates with DISTINCT must be able to sort their inputs."),
218  parser_errposition(pstate, exprLocation(expr))));
219  }
220  }
221  }
222 
223  pstate->p_next_resno = save_next_resno;
224  }
225 
226  /* Update the Aggref with the transformation results */
227  agg->args = tlist;
228  agg->aggorder = torder;
229  agg->aggdistinct = tdistinct;
230 
231  /*
232  * Now build the aggargtypes list with the type OIDs of the direct and
233  * aggregated args, ignoring any resjunk entries that might have been
234  * added by ORDER BY/DISTINCT processing. We can't do this earlier
235  * because said processing can modify some args' data types, in particular
236  * by resolving previously-unresolved "unknown" literals.
237  */
238  foreach(lc, agg->aggdirectargs)
239  {
240  Expr *arg = (Expr *) lfirst(lc);
241 
242  argtypes = lappend_oid(argtypes, exprType((Node *) arg));
243  }
244  foreach(lc, tlist)
245  {
246  TargetEntry *tle = (TargetEntry *) lfirst(lc);
247 
248  if (tle->resjunk)
249  continue; /* ignore junk */
250  argtypes = lappend_oid(argtypes, exprType((Node *) tle->expr));
251  }
252  agg->aggargtypes = argtypes;
253 
254  check_agglevels_and_constraints(pstate, (Node *) agg);
255 }
int16 AttrNumber
Definition: attnum.h:21
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
List * list_truncate(List *list, int new_size)
Definition: list.c:631
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1613
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:240
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition: parse_agg.c:304
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
List * transformDistinctClause(ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
void * arg
List * aggdistinct
Definition: primnodes.h:474
List * aggorder
Definition: primnodes.h:471
int p_next_resno
Definition: parse_node.h:231
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:379

References addTargetToSortList(), Aggref::aggdirectargs, Aggref::aggdistinct, Aggref::aggorder, arg, generate_unaccent_rules::args, Aggref::args, Assert, check_agglevels_and_constraints(), ereport, errcode(), errdetail(), errmsg(), ERROR, TargetEntry::expr, 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(), and transformJsonAggConstructor().

◆ transformGroupingFunc()

Node* transformGroupingFunc ( ParseState pstate,
GroupingFunc p 
)

Definition at line 265 of file parse_agg.c.

266 {
267  ListCell *lc;
268  List *args = p->args;
269  List *result_list = NIL;
271 
272  if (list_length(args) > 31)
273  ereport(ERROR,
274  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
275  errmsg("GROUPING must have fewer than 32 arguments"),
276  parser_errposition(pstate, p->location)));
277 
278  foreach(lc, args)
279  {
280  Node *current_result;
281 
282  current_result = transformExpr(pstate, (Node *) lfirst(lc), pstate->p_expr_kind);
283 
284  /* acceptability of expressions is checked later */
285 
286  result_list = lappend(result_list, current_result);
287  }
288 
289  result->args = result_list;
290  result->location = p->location;
291 
292  check_agglevels_and_constraints(pstate, (Node *) result);
293 
294  return (Node *) result;
295 }
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:118

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

Referenced by transformExprRecurse().

◆ transformWindowFuncCall()

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

Definition at line 825 of file parse_agg.c.

827 {
828  const char *err;
829  bool errkind;
830 
831  /*
832  * A window function call can't contain another one (but aggs are OK). XXX
833  * is this required by spec, or just an unimplemented feature?
834  *
835  * Note: we don't need to check the filter expression here, because the
836  * context checks done below and in transformAggregateCall would have
837  * already rejected any window funcs or aggs within the filter.
838  */
839  if (pstate->p_hasWindowFuncs &&
840  contain_windowfuncs((Node *) wfunc->args))
841  ereport(ERROR,
842  (errcode(ERRCODE_WINDOWING_ERROR),
843  errmsg("window function calls cannot be nested"),
844  parser_errposition(pstate,
845  locate_windowfunc((Node *) wfunc->args))));
846 
847  /*
848  * Check to see if the window function is in an invalid place within the
849  * query.
850  *
851  * For brevity we support two schemes for reporting an error here: set
852  * "err" to a custom message, or set "errkind" true if the error context
853  * is sufficiently identified by what ParseExprKindName will return, *and*
854  * what it will return is just a SQL keyword. (Otherwise, use a custom
855  * message to avoid creating translation problems.)
856  */
857  err = NULL;
858  errkind = false;
859  switch (pstate->p_expr_kind)
860  {
861  case EXPR_KIND_NONE:
862  Assert(false); /* can't happen */
863  break;
864  case EXPR_KIND_OTHER:
865  /* Accept window func here; caller must throw error if wanted */
866  break;
867  case EXPR_KIND_JOIN_ON:
869  err = _("window functions are not allowed in JOIN conditions");
870  break;
872  /* can't get here, but just in case, throw an error */
873  errkind = true;
874  break;
876  err = _("window functions are not allowed in functions in FROM");
877  break;
878  case EXPR_KIND_WHERE:
879  errkind = true;
880  break;
881  case EXPR_KIND_POLICY:
882  err = _("window functions are not allowed in policy expressions");
883  break;
884  case EXPR_KIND_HAVING:
885  errkind = true;
886  break;
887  case EXPR_KIND_FILTER:
888  errkind = true;
889  break;
895  err = _("window functions are not allowed in window definitions");
896  break;
898  /* okay */
899  break;
903  errkind = true;
904  break;
906  err = _("window functions are not allowed in MERGE WHEN conditions");
907  break;
908  case EXPR_KIND_GROUP_BY:
909  errkind = true;
910  break;
911  case EXPR_KIND_ORDER_BY:
912  /* okay */
913  break;
915  /* okay */
916  break;
917  case EXPR_KIND_LIMIT:
918  case EXPR_KIND_OFFSET:
919  errkind = true;
920  break;
921  case EXPR_KIND_RETURNING:
923  errkind = true;
924  break;
925  case EXPR_KIND_VALUES:
927  errkind = true;
928  break;
931  err = _("window functions are not allowed in check constraints");
932  break;
935  err = _("window functions are not allowed in DEFAULT expressions");
936  break;
938  err = _("window functions are not allowed in index expressions");
939  break;
941  err = _("window functions are not allowed in statistics expressions");
942  break;
944  err = _("window functions are not allowed in index predicates");
945  break;
947  err = _("window functions are not allowed in transform expressions");
948  break;
950  err = _("window functions are not allowed in EXECUTE parameters");
951  break;
953  err = _("window functions are not allowed in trigger WHEN conditions");
954  break;
956  err = _("window functions are not allowed in partition bound");
957  break;
959  err = _("window functions are not allowed in partition key expressions");
960  break;
962  err = _("window functions are not allowed in CALL arguments");
963  break;
965  err = _("window functions are not allowed in COPY FROM WHERE conditions");
966  break;
968  err = _("window functions are not allowed in column generation expressions");
969  break;
971  errkind = true;
972  break;
973 
974  /*
975  * There is intentionally no default: case here, so that the
976  * compiler will warn if we add a new ParseExprKind without
977  * extending this switch. If we do see an unrecognized value at
978  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
979  * which is sane anyway.
980  */
981  }
982  if (err)
983  ereport(ERROR,
984  (errcode(ERRCODE_WINDOWING_ERROR),
985  errmsg_internal("%s", err),
986  parser_errposition(pstate, wfunc->location)));
987  if (errkind)
988  ereport(ERROR,
989  (errcode(ERRCODE_WINDOWING_ERROR),
990  /* translator: %s is name of a SQL construct, eg GROUP BY */
991  errmsg("window functions are not allowed in %s",
992  ParseExprKindName(pstate->p_expr_kind)),
993  parser_errposition(pstate, wfunc->location)));
994 
995  /*
996  * If the OVER clause just specifies a window name, find that WINDOW
997  * clause (which had better be present). Otherwise, try to match all the
998  * properties of the OVER clause, and make a new entry in the p_windowdefs
999  * list if no luck.
1000  */
1001  if (windef->name)
1002  {
1003  Index winref = 0;
1004  ListCell *lc;
1005 
1006  Assert(windef->refname == NULL &&
1007  windef->partitionClause == NIL &&
1008  windef->orderClause == NIL &&
1009  windef->frameOptions == FRAMEOPTION_DEFAULTS);
1010 
1011  foreach(lc, pstate->p_windowdefs)
1012  {
1013  WindowDef *refwin = (WindowDef *) lfirst(lc);
1014 
1015  winref++;
1016  if (refwin->name && strcmp(refwin->name, windef->name) == 0)
1017  {
1018  wfunc->winref = winref;
1019  break;
1020  }
1021  }
1022  if (lc == NULL) /* didn't find it? */
1023  ereport(ERROR,
1024  (errcode(ERRCODE_UNDEFINED_OBJECT),
1025  errmsg("window \"%s\" does not exist", windef->name),
1026  parser_errposition(pstate, windef->location)));
1027  }
1028  else
1029  {
1030  Index winref = 0;
1031  ListCell *lc;
1032 
1033  foreach(lc, pstate->p_windowdefs)
1034  {
1035  WindowDef *refwin = (WindowDef *) lfirst(lc);
1036 
1037  winref++;
1038  if (refwin->refname && windef->refname &&
1039  strcmp(refwin->refname, windef->refname) == 0)
1040  /* matched on refname */ ;
1041  else if (!refwin->refname && !windef->refname)
1042  /* matched, no refname */ ;
1043  else
1044  continue;
1045 
1046  /*
1047  * Also see similar de-duplication code in optimize_window_clauses
1048  */
1049  if (equal(refwin->partitionClause, windef->partitionClause) &&
1050  equal(refwin->orderClause, windef->orderClause) &&
1051  refwin->frameOptions == windef->frameOptions &&
1052  equal(refwin->startOffset, windef->startOffset) &&
1053  equal(refwin->endOffset, windef->endOffset))
1054  {
1055  /* found a duplicate window specification */
1056  wfunc->winref = winref;
1057  break;
1058  }
1059  }
1060  if (lc == NULL) /* didn't find it? */
1061  {
1062  pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
1063  wfunc->winref = list_length(pstate->p_windowdefs);
1064  }
1065  }
1066 
1067  pstate->p_hasWindowFuncs = true;
1068 }
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:610
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:214
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:251
bool p_hasWindowFuncs
Definition: parse_node.h:243
List * p_windowdefs
Definition: parse_node.h:229
List * orderClause
Definition: parsenodes.h:569
ParseLoc location
Definition: parsenodes.h:573
List * partitionClause
Definition: parsenodes.h:568
Node * startOffset
Definition: parsenodes.h:571
char * refname
Definition: parsenodes.h:567
Node * endOffset
Definition: parsenodes.h:572
int frameOptions
Definition: parsenodes.h:570
char * name
Definition: parsenodes.h:566
List * args
Definition: primnodes.h:575
Index winref
Definition: primnodes.h:581
ParseLoc location
Definition: primnodes.h:587

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

Referenced by ParseFuncOrColumn(), and transformJsonAggConstructor().