PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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, int agglocation)
 
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 2163 of file parse_agg.c.

2164{
2165 ListCell *lc;
2166
2167 foreach(lc, aggref->args)
2168 {
2172 Oid type = exprType((Node *) tle->expr);
2173
2174 /*
2175 * RECORD is a special case: it has typsend/typreceive functions, but
2176 * record_recv only works if passed the correct typmod to identify the
2177 * specific anonymous record type. array_agg_deserialize cannot do
2178 * that, so we have to disclaim support for the case.
2179 */
2180 if (type == RECORDOID)
2181 return false;
2182
2185 elog(ERROR, "cache lookup failed for type %u", type);
2186
2188
2189 if (!pt->typbyval &&
2190 (!OidIsValid(pt->typsend) || !OidIsValid(pt->typreceive)))
2191 {
2193 return false;
2194 }
2196 }
2197 return true;
2198}
#define OidIsValid(objectId)
Definition c.h:821
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
#define lfirst(lc)
Definition pg_list.h:172
END_CATALOG_STRUCT typedef FormData_pg_type * Form_pg_type
Definition pg_type.h:265
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:262
unsigned int Oid
static int fb(int x)
List * args
Definition primnodes.h:488
Definition nodes.h:135
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:220
const char * type

References Aggref::args, elog, ERROR, exprType(), fb(), Form_pg_type, 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 2314 of file parse_agg.c.

2316{
2317 List *args;
2318 FuncExpr *fexpr;
2319
2320 /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2323
2324 fexpr = makeFuncExpr(deserialfn_oid,
2326 args,
2327 InvalidOid,
2328 InvalidOid,
2330 *deserialfnexpr = (Expr *) fexpr;
2331}
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition makefuncs.c:594
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition parse_agg.c:2378
#define list_make2(x1, x2)
Definition pg_list.h:214
#define InvalidOid
@ COERCE_EXPLICIT_CALL
Definition primnodes.h:767
Definition pg_list.h:54

References COERCE_EXPLICIT_CALL, fb(), 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 2338 of file parse_agg.c.

2345{
2346 List *args;
2347 int i;
2348
2349 /*
2350 * Build expr tree for final function
2351 */
2353
2354 /* finalfn may take additional args, which match agg's input types */
2355 for (i = 0; i < num_finalfn_inputs - 1; i++)
2356 {
2357 args = lappend(args,
2359 }
2360
2361 *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2363 args,
2364 InvalidOid,
2367 /* finalfn is currently never treated as variadic */
2368}
int i
Definition isn.c:77
List * lappend(List *list, void *datum)
Definition list.c:339
#define list_make1(x1)
Definition pg_list.h:212

References COERCE_EXPLICIT_CALL, fb(), 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 2291 of file parse_agg.c.

2293{
2294 List *args;
2295 FuncExpr *fexpr;
2296
2297 /* serialfn always takes INTERNAL and returns BYTEA */
2299
2300 fexpr = makeFuncExpr(serialfn_oid,
2301 BYTEAOID,
2302 args,
2303 InvalidOid,
2304 InvalidOid,
2306 *serialfnexpr = (Expr *) fexpr;
2307}

References COERCE_EXPLICIT_CALL, fb(), 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 2230 of file parse_agg.c.

2240{
2241 List *args;
2242 FuncExpr *fexpr;
2243 int i;
2244
2245 /*
2246 * Build arg list to use in the transfn FuncExpr node.
2247 */
2249
2251 {
2252 args = lappend(args,
2254 }
2255
2256 fexpr = makeFuncExpr(transfn_oid,
2258 args,
2259 InvalidOid,
2262 fexpr->funcvariadic = agg_variadic;
2263 *transfnexpr = (Expr *) fexpr;
2264
2265 /*
2266 * Build invtransfn expression if requested, with same args as transfn
2267 */
2268 if (invtransfnexpr != NULL)
2269 {
2270 if (OidIsValid(invtransfn_oid))
2271 {
2272 fexpr = makeFuncExpr(invtransfn_oid,
2274 args,
2275 InvalidOid,
2278 fexpr->funcvariadic = agg_variadic;
2279 *invtransfnexpr = (Expr *) fexpr;
2280 }
2281 else
2283 }
2284}

References COERCE_EXPLICIT_CALL, fb(), 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 1812 of file parse_agg.c.

1814{
1815 Var *var;
1817 ParseNamespaceColumn *nscol = grouping_nsitem->p_nscolumns + attnum - 1;
1818
1819 Assert(nscol->p_varno == grouping_nsitem->p_rtindex);
1820 Assert(nscol->p_varattno == attnum);
1821 var = makeVar(nscol->p_varno,
1822 nscol->p_varattno,
1823 nscol->p_vartype,
1824 nscol->p_vartypmod,
1825 nscol->p_varcollid,
1826 context->sublevels_up);
1827 /* makeVar doesn't offer parameters for these, so set by hand: */
1828 var->varnosyn = nscol->p_varnosyn;
1829 var->varattnosyn = nscol->p_varattnosyn;
1830
1831 if (context->qry->groupingSets &&
1832 !list_member_int(context->gset_common, ressortgroupref))
1833 var->varnullingrels =
1834 bms_add_member(var->varnullingrels, grouping_nsitem->p_rtindex);
1835
1836 return var;
1837}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
#define Assert(condition)
Definition c.h:906
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
ParseNamespaceItem * p_grouping_nsitem
Definition parse_node.h:207
List * groupingSets
Definition parsenodes.h:220

References Assert, attnum, bms_add_member(), fb(), Query::groupingSets, substitute_grouped_columns_context::gset_common, list_member_int(), makeVar(), ParseState::p_grouping_nsitem, substitute_grouped_columns_context::pstate, substitute_grouped_columns_context::qry, and substitute_grouped_columns_context::sublevels_up.

Referenced by substitute_grouped_columns_mutator().

◆ check_agg_arguments()

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

Definition at line 646 of file parse_agg.c.

651{
652 int agglevel;
654
655 context.pstate = pstate;
656 context.min_varlevel = -1; /* signifies nothing found yet */
657 context.min_agglevel = -1;
658 context.min_ctelevel = -1;
659 context.min_cte = NULL;
660 context.sublevels_up = 0;
661
662 (void) check_agg_arguments_walker((Node *) args, &context);
663 (void) check_agg_arguments_walker((Node *) filter, &context);
664
665 /*
666 * If we found no vars nor aggs at all, it's a level-zero aggregate;
667 * otherwise, its level is the minimum of vars or aggs.
668 */
669 if (context.min_varlevel < 0)
670 {
671 if (context.min_agglevel < 0)
672 agglevel = 0;
673 else
674 agglevel = context.min_agglevel;
675 }
676 else if (context.min_agglevel < 0)
677 agglevel = context.min_varlevel;
678 else
679 agglevel = Min(context.min_varlevel, context.min_agglevel);
680
681 /*
682 * If there's a nested aggregate of the same semantic level, complain.
683 */
684 if (agglevel == context.min_agglevel)
685 {
686 int aggloc;
687
689 if (aggloc < 0)
693 errmsg("aggregate function calls cannot be nested"),
694 parser_errposition(pstate, aggloc)));
695 }
696
697 /*
698 * If there's a non-local CTE that's below the aggregate's semantic level,
699 * complain. It's not quite clear what we should do to fix up such a case
700 * (treating the CTE reference like a Var seems wrong), and it's also
701 * unclear whether there is a real-world use for such cases.
702 */
703 if (context.min_ctelevel >= 0 && context.min_ctelevel < agglevel)
706 errmsg("outer-level aggregate cannot use a nested CTE"),
707 errdetail("CTE \"%s\" is below the aggregate's semantic level.",
708 context.min_cte->eref->aliasname),
710
711 /*
712 * Now check for vars/aggs in the direct arguments, and throw error if
713 * needed. Note that we allow a Var of the agg's semantic level, but not
714 * an Agg of that level. In principle such Aggs could probably be
715 * supported, but it would create an ordering dependency among the
716 * aggregates at execution time. Since the case appears neither to be
717 * required by spec nor particularly useful, we just treat it as a
718 * nested-aggregate situation.
719 */
720 if (directargs)
721 {
722 context.min_varlevel = -1;
723 context.min_agglevel = -1;
724 context.min_ctelevel = -1;
726 if (context.min_varlevel >= 0 && context.min_varlevel < agglevel)
729 errmsg("outer-level aggregate cannot contain a lower-level variable in its direct arguments"),
730 parser_errposition(pstate,
732 context.min_varlevel))));
733 if (context.min_agglevel >= 0 && context.min_agglevel <= agglevel)
736 errmsg("aggregate function calls cannot be nested"),
737 parser_errposition(pstate,
739 context.min_agglevel))));
740 if (context.min_ctelevel >= 0 && context.min_ctelevel < agglevel)
743 errmsg("outer-level aggregate cannot use a nested CTE"),
744 errdetail("CTE \"%s\" is below the aggregate's semantic level.",
745 context.min_cte->eref->aliasname),
747 }
748 return agglevel;
749}
#define Min(x, y)
Definition c.h:1054
int errcode(int sqlerrcode)
Definition elog.c:874
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define ereport(elevel,...)
Definition elog.h:150
static char * errmsg
static bool check_agg_arguments_walker(Node *node, check_agg_arguments_context *context)
Definition parse_agg.c:752
int parser_errposition(ParseState *pstate, int location)
Definition parse_node.c:106
int locate_agg_of_level(Node *node, int levelsup)
RangeTblEntry * min_cte
Definition parse_agg.c:42
int locate_var_of_level(Node *node, int levelsup)
Definition var.c:555

References check_agg_arguments_walker(), ereport, errcode(), errdetail(), errmsg, ERROR, fb(), locate_agg_of_level(), locate_var_of_level(), Min, check_agg_arguments_context::min_agglevel, check_agg_arguments_context::min_cte, check_agg_arguments_context::min_ctelevel, check_agg_arguments_context::min_varlevel, parser_errposition(), check_agg_arguments_context::pstate, and check_agg_arguments_context::sublevels_up.

Referenced by check_agglevels_and_constraints().

◆ check_agg_arguments_walker()

static bool check_agg_arguments_walker ( Node node,
check_agg_arguments_context context 
)
static

Definition at line 752 of file parse_agg.c.

754{
755 if (node == NULL)
756 return false;
757 if (IsA(node, Var))
758 {
759 int varlevelsup = ((Var *) node)->varlevelsup;
760
761 /* convert levelsup to frame of reference of original query */
762 varlevelsup -= context->sublevels_up;
763 /* ignore local vars of subqueries */
764 if (varlevelsup >= 0)
765 {
766 if (context->min_varlevel < 0 ||
767 context->min_varlevel > varlevelsup)
768 context->min_varlevel = varlevelsup;
769 }
770 return false;
771 }
772 if (IsA(node, Aggref))
773 {
774 int agglevelsup = ((Aggref *) node)->agglevelsup;
775
776 /* convert levelsup to frame of reference of original query */
777 agglevelsup -= context->sublevels_up;
778 /* ignore local aggs of subqueries */
779 if (agglevelsup >= 0)
780 {
781 if (context->min_agglevel < 0 ||
782 context->min_agglevel > agglevelsup)
783 context->min_agglevel = agglevelsup;
784 }
785 /* Continue and descend into subtree */
786 }
787 if (IsA(node, GroupingFunc))
788 {
789 int agglevelsup = ((GroupingFunc *) node)->agglevelsup;
790
791 /* convert levelsup to frame of reference of original query */
792 agglevelsup -= context->sublevels_up;
793 /* ignore local aggs of subqueries */
794 if (agglevelsup >= 0)
795 {
796 if (context->min_agglevel < 0 ||
797 context->min_agglevel > agglevelsup)
798 context->min_agglevel = agglevelsup;
799 }
800 /* Continue and descend into subtree */
801 }
802
803 /*
804 * SRFs and window functions can be rejected immediately, unless we are
805 * within a sub-select within the aggregate's arguments; in that case
806 * they're OK.
807 */
808 if (context->sublevels_up == 0)
809 {
810 if ((IsA(node, FuncExpr) && ((FuncExpr *) node)->funcretset) ||
811 (IsA(node, OpExpr) && ((OpExpr *) node)->opretset))
814 errmsg("aggregate function calls cannot contain set-returning function calls"),
815 errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
816 parser_errposition(context->pstate, exprLocation(node))));
817 if (IsA(node, WindowFunc))
820 errmsg("aggregate function calls cannot contain window function calls"),
821 parser_errposition(context->pstate,
822 ((WindowFunc *) node)->location)));
823 }
824
825 if (IsA(node, RangeTblEntry))
826 {
827 RangeTblEntry *rte = (RangeTblEntry *) node;
828
829 if (rte->rtekind == RTE_CTE)
830 {
831 int ctelevelsup = rte->ctelevelsup;
832
833 /* convert levelsup to frame of reference of original query */
834 ctelevelsup -= context->sublevels_up;
835 /* ignore local CTEs of subqueries */
836 if (ctelevelsup >= 0)
837 {
838 if (context->min_ctelevel < 0 ||
839 context->min_ctelevel > ctelevelsup)
840 {
841 context->min_ctelevel = ctelevelsup;
842 context->min_cte = rte;
843 }
844 }
845 }
846 return false; /* allow range_table_walker to continue */
847 }
848 if (IsA(node, Query))
849 {
850 /* Recurse into subselects */
851 bool result;
852
853 context->sublevels_up++;
854 result = query_tree_walker((Query *) node,
856 context,
858 context->sublevels_up--;
859 return result;
860 }
861
862 return expression_tree_walker(node,
864 context);
865}
int errhint(const char *fmt,...) pg_attribute_printf(1
int exprLocation(const Node *expr)
Definition nodeFuncs.c:1384
#define query_tree_walker(q, w, c, f)
Definition nodeFuncs.h:158
#define expression_tree_walker(n, w, c)
Definition nodeFuncs.h:153
#define QTW_EXAMINE_RTES_BEFORE
Definition nodeFuncs.h:27
#define IsA(nodeptr, _type_)
Definition nodes.h:164
@ RTE_CTE

References check_agg_arguments_walker(), ereport, errcode(), errhint(), errmsg, ERROR, expression_tree_walker, exprLocation(), fb(), IsA, check_agg_arguments_context::min_agglevel, check_agg_arguments_context::min_cte, check_agg_arguments_context::min_ctelevel, check_agg_arguments_context::min_varlevel, parser_errposition(), check_agg_arguments_context::pstate, QTW_EXAMINE_RTES_BEFORE, query_tree_walker, RTE_CTE, and check_agg_arguments_context::sublevels_up.

Referenced by check_agg_arguments(), and check_agg_arguments_walker().

◆ check_agglevels_and_constraints()

static void check_agglevels_and_constraints ( ParseState pstate,
Node expr 
)
static

Definition at line 308 of file parse_agg.c.

309{
311 List *args = NIL;
312 Expr *filter = NULL;
313 int min_varlevel;
314 int location = -1;
316 const char *err;
317 bool errkind;
318 bool isAgg = IsA(expr, Aggref);
319
320 if (isAgg)
321 {
322 Aggref *agg = (Aggref *) expr;
323
325 args = agg->args;
326 filter = agg->aggfilter;
327 location = agg->location;
328 p_levelsup = &agg->agglevelsup;
329 }
330 else
331 {
332 GroupingFunc *grp = (GroupingFunc *) expr;
333
334 args = grp->args;
335 location = grp->location;
336 p_levelsup = &grp->agglevelsup;
337 }
338
339 /*
340 * Check the arguments to compute the aggregate's level and detect
341 * improper nesting.
342 */
343 min_varlevel = check_agg_arguments(pstate,
345 args,
346 filter,
347 location);
348
349 *p_levelsup = min_varlevel;
350
351 /* Mark the correct pstate level as having aggregates */
352 while (min_varlevel-- > 0)
353 pstate = pstate->parentParseState;
354 pstate->p_hasAggs = true;
355
356 /*
357 * Check to see if the aggregate function is in an invalid place within
358 * its aggregation query.
359 *
360 * For brevity we support two schemes for reporting an error here: set
361 * "err" to a custom message, or set "errkind" true if the error context
362 * is sufficiently identified by what ParseExprKindName will return, *and*
363 * what it will return is just a SQL keyword. (Otherwise, use a custom
364 * message to avoid creating translation problems.)
365 */
366 err = NULL;
367 errkind = false;
368 switch (pstate->p_expr_kind)
369 {
370 case EXPR_KIND_NONE:
371 Assert(false); /* can't happen */
372 break;
373 case EXPR_KIND_OTHER:
374
375 /*
376 * Accept aggregate/grouping here; caller must throw error if
377 * wanted
378 */
379 break;
382 if (isAgg)
383 err = _("aggregate functions are not allowed in JOIN conditions");
384 else
385 err = _("grouping operations are not allowed in JOIN conditions");
386
387 break;
389
390 /*
391 * Aggregate/grouping scope rules make it worth being explicit
392 * here
393 */
394 if (isAgg)
395 err = _("aggregate functions are not allowed in FROM clause of their own query level");
396 else
397 err = _("grouping operations are not allowed in FROM clause of their own query level");
398
399 break;
401 if (isAgg)
402 err = _("aggregate functions are not allowed in functions in FROM");
403 else
404 err = _("grouping operations are not allowed in functions in FROM");
405
406 break;
407 case EXPR_KIND_WHERE:
408 errkind = true;
409 break;
410 case EXPR_KIND_POLICY:
411 if (isAgg)
412 err = _("aggregate functions are not allowed in policy expressions");
413 else
414 err = _("grouping operations are not allowed in policy expressions");
415
416 break;
417 case EXPR_KIND_HAVING:
418 /* okay */
419 break;
420 case EXPR_KIND_FILTER:
421 errkind = true;
422 break;
424 /* okay */
425 break;
427 /* okay */
428 break;
430 if (isAgg)
431 err = _("aggregate functions are not allowed in window RANGE");
432 else
433 err = _("grouping operations are not allowed in window RANGE");
434
435 break;
437 if (isAgg)
438 err = _("aggregate functions are not allowed in window ROWS");
439 else
440 err = _("grouping operations are not allowed in window ROWS");
441
442 break;
444 if (isAgg)
445 err = _("aggregate functions are not allowed in window GROUPS");
446 else
447 err = _("grouping operations are not allowed in window GROUPS");
448
449 break;
451 /* okay */
452 break;
456 errkind = true;
457 break;
459 if (isAgg)
460 err = _("aggregate functions are not allowed in MERGE WHEN conditions");
461 else
462 err = _("grouping operations are not allowed in MERGE WHEN conditions");
463
464 break;
466 errkind = true;
467 break;
469 /* okay */
470 break;
472 /* okay */
473 break;
474 case EXPR_KIND_LIMIT:
475 case EXPR_KIND_OFFSET:
476 errkind = true;
477 break;
480 errkind = true;
481 break;
482 case EXPR_KIND_VALUES:
484 errkind = true;
485 break;
488 if (isAgg)
489 err = _("aggregate functions are not allowed in check constraints");
490 else
491 err = _("grouping operations are not allowed in check constraints");
492
493 break;
496
497 if (isAgg)
498 err = _("aggregate functions are not allowed in DEFAULT expressions");
499 else
500 err = _("grouping operations are not allowed in DEFAULT expressions");
501
502 break;
504 if (isAgg)
505 err = _("aggregate functions are not allowed in index expressions");
506 else
507 err = _("grouping operations are not allowed in index expressions");
508
509 break;
511 if (isAgg)
512 err = _("aggregate functions are not allowed in index predicates");
513 else
514 err = _("grouping operations are not allowed in index predicates");
515
516 break;
518 if (isAgg)
519 err = _("aggregate functions are not allowed in statistics expressions");
520 else
521 err = _("grouping operations are not allowed in statistics expressions");
522
523 break;
525 if (isAgg)
526 err = _("aggregate functions are not allowed in transform expressions");
527 else
528 err = _("grouping operations are not allowed in transform expressions");
529
530 break;
532 if (isAgg)
533 err = _("aggregate functions are not allowed in EXECUTE parameters");
534 else
535 err = _("grouping operations are not allowed in EXECUTE parameters");
536
537 break;
539 if (isAgg)
540 err = _("aggregate functions are not allowed in trigger WHEN conditions");
541 else
542 err = _("grouping operations are not allowed in trigger WHEN conditions");
543
544 break;
546 if (isAgg)
547 err = _("aggregate functions are not allowed in partition bound");
548 else
549 err = _("grouping operations are not allowed in partition bound");
550
551 break;
553 if (isAgg)
554 err = _("aggregate functions are not allowed in partition key expressions");
555 else
556 err = _("grouping operations are not allowed in partition key expressions");
557
558 break;
560
561 if (isAgg)
562 err = _("aggregate functions are not allowed in column generation expressions");
563 else
564 err = _("grouping operations are not allowed in column generation expressions");
565
566 break;
567
569 if (isAgg)
570 err = _("aggregate functions are not allowed in CALL arguments");
571 else
572 err = _("grouping operations are not allowed in CALL arguments");
573
574 break;
575
577 if (isAgg)
578 err = _("aggregate functions are not allowed in COPY FROM WHERE conditions");
579 else
580 err = _("grouping operations are not allowed in COPY FROM WHERE conditions");
581
582 break;
583
585 errkind = true;
586 break;
587
588 /*
589 * There is intentionally no default: case here, so that the
590 * compiler will warn if we add a new ParseExprKind without
591 * extending this switch. If we do see an unrecognized value at
592 * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
593 * which is sane anyway.
594 */
595 }
596
597 if (err)
600 errmsg_internal("%s", err),
601 parser_errposition(pstate, location)));
602
603 if (errkind)
604 {
605 if (isAgg)
606 /* translator: %s is name of a SQL construct, eg GROUP BY */
607 err = _("aggregate functions are not allowed in %s");
608 else
609 /* translator: %s is name of a SQL construct, eg GROUP BY */
610 err = _("grouping operations are not allowed in %s");
611
616 parser_errposition(pstate, location)));
617 }
618}
unsigned int Index
Definition c.h:661
#define _(x)
Definition elog.c:95
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
void err(int eval, const char *fmt,...)
Definition err.c:43
static int check_agg_arguments(ParseState *pstate, List *directargs, List *args, Expr *filter, int agglocation)
Definition parse_agg.c:646
const char * ParseExprKindName(ParseExprKind exprKind)
@ 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:485
ParseState * parentParseState
Definition parse_node.h:190
ParseExprKind p_expr_kind
Definition parse_node.h:209
bool p_hasAggs
Definition parse_node.h:221

References _, 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, fb(), IsA, 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 1954 of file parse_agg.c.

1955{
1956 int la = list_length((const List *) lfirst(a));
1957 int lb = list_length((const List *) lfirst(b));
1958
1959 return pg_cmp_s32(la, lb);
1960}
static int pg_cmp_s32(int32 a, int32 b)
Definition int.h:713
int b
Definition isn.c:74
int a
Definition isn.c:73
static int list_length(const List *l)
Definition pg_list.h:152

References a, b, fb(), 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 1964 of file parse_agg.c.

1965{
1966 int res = cmp_list_len_asc(a, b);
1967
1968 if (res == 0)
1969 {
1970 List *la = (List *) lfirst(a);
1971 List *lb = (List *) lfirst(b);
1972 ListCell *lca;
1973 ListCell *lcb;
1974
1975 forboth(lca, la, lcb, lb)
1976 {
1977 int va = lfirst_int(lca);
1978 int vb = lfirst_int(lcb);
1979
1980 if (va > vb)
1981 return 1;
1982 if (va < vb)
1983 return -1;
1984 }
1985 }
1986
1987 return res;
1988}
Datum lca(PG_FUNCTION_ARGS)
Definition ltree_op.c:563
static int cmp_list_len_asc(const ListCell *a, const ListCell *b)
Definition parse_agg.c:1954
#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(), fb(), forboth, lca(), lfirst, and lfirst_int.

Referenced by expand_grouping_sets().

◆ expand_grouping_sets()

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

Definition at line 1998 of file parse_agg.c.

1999{
2001 List *result = NIL;
2002 double numsets = 1;
2003 ListCell *lc;
2004
2005 if (groupingSets == NIL)
2006 return NIL;
2007
2008 foreach(lc, groupingSets)
2009 {
2011 GroupingSet *gs = lfirst(lc);
2012
2014
2016
2017 numsets *= list_length(current_result);
2018
2019 if (limit >= 0 && numsets > limit)
2020 return NIL;
2021
2023 }
2024
2025 /*
2026 * Do cartesian product between sublists of expanded_groups. While at it,
2027 * remove any duplicate elements from individual grouping sets (we must
2028 * NOT change the number of sets though)
2029 */
2030
2031 foreach(lc, (List *) linitial(expanded_groups))
2032 {
2033 result = lappend(result, list_union_int(NIL, (List *) lfirst(lc)));
2034 }
2035
2037 {
2038 List *p = lfirst(lc);
2039 List *new_result = NIL;
2040 ListCell *lc2;
2041
2042 foreach(lc2, result)
2043 {
2044 List *q = lfirst(lc2);
2045 ListCell *lc3;
2046
2047 foreach(lc3, p)
2048 {
2050 list_union_int(q, (List *) lfirst(lc3)));
2051 }
2052 }
2053 result = new_result;
2054 }
2055
2056 /* Now sort the lists by length and deduplicate if necessary */
2057 if (!groupDistinct || list_length(result) < 2)
2058 list_sort(result, cmp_list_len_asc);
2059 else
2060 {
2061 ListCell *cell;
2062 List *prev;
2063
2064 /* Sort each groupset individually */
2065 foreach(cell, result)
2067
2068 /* Now sort the list of groupsets by length and contents */
2070
2071 /* Finally, remove duplicates */
2072 prev = linitial(result);
2073 for_each_from(cell, result, 1)
2074 {
2075 if (equal(lfirst(cell), prev))
2076 result = foreach_delete_current(result, cell);
2077 else
2078 prev = lfirst(cell);
2079 }
2080 }
2081
2082 return result;
2083}
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:1964
static List * expand_groupingset_node(GroupingSet *gs)
Definition parse_agg.c:1852
#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(), fb(), for_each_from, foreach_delete_current, lappend(), lfirst, linitial, list_int_cmp(), list_length(), list_sort(), list_union_int(), and NIL.

Referenced by parseCheckAggregates(), query_is_distinct_for(), and subquery_planner().

◆ expand_groupingset_node()

static List * expand_groupingset_node ( GroupingSet gs)
static

Definition at line 1852 of file parse_agg.c.

1853{
1854 List *result = NIL;
1855
1856 switch (gs->kind)
1857 {
1858 case GROUPING_SET_EMPTY:
1859 result = list_make1(NIL);
1860 break;
1861
1863 result = list_make1(gs->content);
1864 break;
1865
1867 {
1868 List *rollup_val = gs->content;
1869 ListCell *lc;
1870 int curgroup_size = list_length(gs->content);
1871
1872 while (curgroup_size > 0)
1873 {
1875 int i = curgroup_size;
1876
1877 foreach(lc, rollup_val)
1878 {
1880
1882
1884 gs_current->content);
1885
1886 /* If we are done with making the current group, break */
1887 if (--i == 0)
1888 break;
1889 }
1890
1891 result = lappend(result, current_result);
1892 --curgroup_size;
1893 }
1894
1895 result = lappend(result, NIL);
1896 }
1897 break;
1898
1899 case GROUPING_SET_CUBE:
1900 {
1901 List *cube_list = gs->content;
1904 uint32 i;
1905
1906 /* parser should cap this much lower */
1907 Assert(number_bits < 31);
1908
1909 num_sets = (1U << number_bits);
1910
1911 for (i = 0; i < num_sets; i++)
1912 {
1914 ListCell *lc;
1915 uint32 mask = 1U;
1916
1917 foreach(lc, cube_list)
1918 {
1920
1922
1923 if (mask & i)
1925 gs_current->content);
1926
1927 mask <<= 1;
1928 }
1929
1930 result = lappend(result, current_result);
1931 }
1932 }
1933 break;
1934
1935 case GROUPING_SET_SETS:
1936 {
1937 ListCell *lc;
1938
1939 foreach(lc, gs->content)
1940 {
1942
1943 result = list_concat(result, current_result);
1944 }
1945 }
1946 break;
1947 }
1948
1949 return result;
1950}
uint32_t uint32
Definition c.h:579
List * list_concat(List *list1, const List *list2)
Definition list.c:561
@ GROUPING_SET_CUBE
@ GROUPING_SET_SIMPLE
@ GROUPING_SET_ROLLUP
@ GROUPING_SET_SETS
@ GROUPING_SET_EMPTY

References Assert, expand_groupingset_node(), fb(), 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(), and expand_groupingset_node().

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

1616{
1618
1619 context.pstate = pstate;
1620 context.qry = qry;
1621 context.hasJoinRTEs = hasJoinRTEs;
1622 context.groupClauses = groupClauses;
1623 context.groupClauseCommonVars = NIL;
1624 context.groupClauseSubLevels = NIL;
1625 context.gset_common = NIL;
1626 context.have_non_var_grouping = have_non_var_grouping;
1627 context.func_grouped_rels = NULL;
1628 context.sublevels_up = 0;
1629 context.in_agg_direct_args = false;
1630 finalize_grouping_exprs_walker(node, &context);
1631}
static bool finalize_grouping_exprs_walker(Node *node, substitute_grouped_columns_context *context)
Definition parse_agg.c:1634

References fb(), finalize_grouping_exprs_walker(), substitute_grouped_columns_context::func_grouped_rels, substitute_grouped_columns_context::groupClauseCommonVars, substitute_grouped_columns_context::groupClauses, substitute_grouped_columns_context::groupClauseSubLevels, substitute_grouped_columns_context::gset_common, substitute_grouped_columns_context::hasJoinRTEs, substitute_grouped_columns_context::have_non_var_grouping, substitute_grouped_columns_context::in_agg_direct_args, NIL, substitute_grouped_columns_context::pstate, substitute_grouped_columns_context::qry, and substitute_grouped_columns_context::sublevels_up.

Referenced by parseCheckAggregates().

◆ finalize_grouping_exprs_walker()

static bool finalize_grouping_exprs_walker ( Node node,
substitute_grouped_columns_context context 
)
static

Definition at line 1634 of file parse_agg.c.

1636{
1637 ListCell *gl;
1638
1639 if (node == NULL)
1640 return false;
1641 if (IsA(node, Const) ||
1642 IsA(node, Param))
1643 return false; /* constants are always acceptable */
1644
1645 if (IsA(node, Aggref))
1646 {
1647 Aggref *agg = (Aggref *) node;
1648
1649 if ((int) agg->agglevelsup == context->sublevels_up)
1650 {
1651 /*
1652 * If we find an aggregate call of the original level, do not
1653 * recurse into its normal arguments, ORDER BY arguments, or
1654 * filter; GROUPING exprs of this level are not allowed there. But
1655 * check direct arguments as though they weren't in an aggregate.
1656 */
1657 bool result;
1658
1659 Assert(!context->in_agg_direct_args);
1660 context->in_agg_direct_args = true;
1661 result = finalize_grouping_exprs_walker((Node *) agg->aggdirectargs,
1662 context);
1663 context->in_agg_direct_args = false;
1664 return result;
1665 }
1666
1667 /*
1668 * We can skip recursing into aggregates of higher levels altogether,
1669 * since they could not possibly contain exprs of concern to us (see
1670 * transformAggregateCall). We do need to look at aggregates of lower
1671 * levels, however.
1672 */
1673 if ((int) agg->agglevelsup > context->sublevels_up)
1674 return false;
1675 }
1676
1677 if (IsA(node, GroupingFunc))
1678 {
1679 GroupingFunc *grp = (GroupingFunc *) node;
1680
1681 /*
1682 * We only need to check GroupingFunc nodes at the exact level to
1683 * which they belong, since they cannot mix levels in arguments.
1684 */
1685
1686 if ((int) grp->agglevelsup == context->sublevels_up)
1687 {
1688 ListCell *lc;
1689 List *ref_list = NIL;
1690
1691 foreach(lc, grp->args)
1692 {
1693 Node *expr = lfirst(lc);
1694 Index ref = 0;
1695
1696 if (context->hasJoinRTEs)
1697 expr = flatten_join_alias_for_parser(context->qry,
1698 expr,
1699 context->sublevels_up);
1700
1701 /*
1702 * Each expression must match a grouping entry at the current
1703 * query level. Unlike the general expression case, we don't
1704 * allow functional dependencies or outer references.
1705 */
1706
1707 if (IsA(expr, Var))
1708 {
1709 Var *var = (Var *) expr;
1710
1711 if (var->varlevelsup == context->sublevels_up)
1712 {
1713 foreach(gl, context->groupClauses)
1714 {
1716 Var *gvar = (Var *) tle->expr;
1717
1718 if (IsA(gvar, Var) &&
1719 gvar->varno == var->varno &&
1720 gvar->varattno == var->varattno &&
1721 gvar->varlevelsup == 0)
1722 {
1723 ref = tle->ressortgroupref;
1724 break;
1725 }
1726 }
1727 }
1728 }
1729 else if (context->have_non_var_grouping)
1730 {
1731 List *groupClauses;
1732
1733 /*
1734 * Within a subquery, we need a mutated version of the
1735 * groupClauses
1736 */
1737 if (context->sublevels_up == 0)
1738 groupClauses = context->groupClauses;
1739 else
1740 groupClauses = list_nth(context->groupClauseSubLevels,
1741 context->sublevels_up - 1);
1742
1743 foreach(gl, groupClauses)
1744 {
1746
1747 if (equal(expr, tle->expr))
1748 {
1749 ref = tle->ressortgroupref;
1750 break;
1751 }
1752 }
1753 }
1754
1755 if (ref == 0)
1756 ereport(ERROR,
1758 errmsg("arguments to GROUPING must be grouping expressions of the associated query level"),
1759 parser_errposition(context->pstate,
1760 exprLocation(expr))));
1761
1763 }
1764
1765 grp->refs = ref_list;
1766 }
1767
1768 if ((int) grp->agglevelsup > context->sublevels_up)
1769 return false;
1770 }
1771
1772 if (IsA(node, Query))
1773 {
1774 /* Recurse into subselects */
1775 bool result;
1776
1777 context->sublevels_up++;
1778
1779 /*
1780 * If we have non-Var grouping expressions, we'll need a copy of the
1781 * groupClauses list that's mutated to match this sublevels_up depth.
1782 * Build one if we've not yet visited a subquery at this depth.
1783 */
1784 if (context->have_non_var_grouping &&
1785 context->sublevels_up > list_length(context->groupClauseSubLevels))
1786 {
1788
1790 context->sublevels_up, 0);
1791 context->groupClauseSubLevels =
1793 Assert(context->sublevels_up == list_length(context->groupClauseSubLevels));
1794 }
1795
1796 result = query_tree_walker((Query *) node,
1798 context,
1799 0);
1800 context->sublevels_up--;
1801 return result;
1802 }
1804 context);
1805}
List * lappend_int(List *list, int datum)
Definition list.c:357
#define copyObject(obj)
Definition nodes.h:232
static void * list_nth(const List *list, int n)
Definition pg_list.h:299
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
AttrNumber varattno
Definition primnodes.h:275
int varno
Definition primnodes.h:270
Index varlevelsup
Definition primnodes.h:295
Node * flatten_join_alias_for_parser(Query *query, Node *node, int sublevels_up)
Definition var.c:819

References Assert, copyObject, equal(), ereport, errcode(), errmsg, ERROR, expression_tree_walker, exprLocation(), fb(), finalize_grouping_exprs_walker(), flatten_join_alias_for_parser(), substitute_grouped_columns_context::groupClauses, substitute_grouped_columns_context::groupClauseSubLevels, substitute_grouped_columns_context::hasJoinRTEs, substitute_grouped_columns_context::have_non_var_grouping, substitute_grouped_columns_context::in_agg_direct_args, IncrementVarSublevelsUp(), IsA, lappend(), lappend_int(), lfirst, list_length(), list_nth(), NIL, parser_errposition(), substitute_grouped_columns_context::pstate, substitute_grouped_columns_context::qry, query_tree_walker, substitute_grouped_columns_context::sublevels_up, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by finalize_grouping_exprs(), and finalize_grouping_exprs_walker().

◆ get_aggregate_argtypes()

int get_aggregate_argtypes ( Aggref aggref,
Oid inputTypes 
)

Definition at line 2101 of file parse_agg.c.

2102{
2103 int numArguments = 0;
2104 ListCell *lc;
2105
2106 Assert(list_length(aggref->aggargtypes) <= FUNC_MAX_ARGS);
2107
2108 foreach(lc, aggref->aggargtypes)
2109 {
2110 inputTypes[numArguments++] = lfirst_oid(lc);
2111 }
2112
2113 return numArguments;
2114}
#define FUNC_MAX_ARGS
#define lfirst_oid(lc)
Definition pg_list.h:174

References Assert, fb(), 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 2378 of file parse_agg.c.

2379{
2381
2382 argp->paramkind = PARAM_EXEC;
2383 argp->paramid = -1;
2384 argp->paramtype = argtype;
2385 argp->paramtypmod = -1;
2386 argp->paramcollid = argcollation;
2387 argp->location = -1;
2388 return (Node *) argp;
2389}
#define makeNode(_type_)
Definition nodes.h:161
@ PARAM_EXEC
Definition primnodes.h:386

References fb(), makeNode, and PARAM_EXEC.

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

1140{
1141 List *gset_common = NIL;
1142 List *groupClauses = NIL;
1143 List *groupClauseCommonVars = NIL;
1144 bool have_non_var_grouping;
1145 List *func_grouped_rels = NIL;
1146 ListCell *l;
1147 bool hasJoinRTEs;
1148 bool hasSelfRefRTEs;
1149 Node *clause;
1150
1151 /* This should only be called if we found aggregates or grouping */
1152 Assert(pstate->p_hasAggs || qry->groupClause || qry->havingQual || qry->groupingSets);
1153
1154 /*
1155 * If we have grouping sets, expand them and find the intersection of all
1156 * sets.
1157 */
1158 if (qry->groupingSets)
1159 {
1160 /*
1161 * The limit of 4096 is arbitrary and exists simply to avoid resource
1162 * issues from pathological constructs.
1163 */
1164 List *gsets = expand_grouping_sets(qry->groupingSets, qry->groupDistinct, 4096);
1165
1166 if (!gsets)
1167 ereport(ERROR,
1169 errmsg("too many grouping sets present (maximum 4096)"),
1170 parser_errposition(pstate,
1171 qry->groupClause
1172 ? exprLocation((Node *) qry->groupClause)
1173 : exprLocation((Node *) qry->groupingSets))));
1174
1175 /*
1176 * The intersection will often be empty, so help things along by
1177 * seeding the intersect with the smallest set.
1178 */
1179 gset_common = linitial(gsets);
1180
1181 if (gset_common)
1182 {
1183 for_each_from(l, gsets, 1)
1184 {
1185 gset_common = list_intersection_int(gset_common, lfirst(l));
1186 if (!gset_common)
1187 break;
1188 }
1189 }
1190
1191 /*
1192 * If there was only one grouping set in the expansion, AND if the
1193 * groupClause is non-empty (meaning that the grouping set is not
1194 * empty either), then we can ditch the grouping set and pretend we
1195 * just had a normal GROUP BY.
1196 */
1197 if (list_length(gsets) == 1 && qry->groupClause)
1198 qry->groupingSets = NIL;
1199 }
1200
1201 /*
1202 * Scan the range table to see if there are JOIN or self-reference CTE
1203 * entries. We'll need this info below.
1204 */
1205 hasJoinRTEs = hasSelfRefRTEs = false;
1206 foreach(l, pstate->p_rtable)
1207 {
1209
1210 if (rte->rtekind == RTE_JOIN)
1211 hasJoinRTEs = true;
1212 else if (rte->rtekind == RTE_CTE && rte->self_reference)
1213 hasSelfRefRTEs = true;
1214 }
1215
1216 /*
1217 * Build a list of the acceptable GROUP BY expressions to save in the
1218 * RTE_GROUP RTE, and for use by substitute_grouped_columns().
1219 *
1220 * We get the TLE, not just the expr, because GROUPING wants to know the
1221 * sortgroupref.
1222 */
1223 foreach(l, qry->groupClause)
1224 {
1226 TargetEntry *expr;
1227
1229 if (expr == NULL)
1230 continue; /* probably cannot happen */
1231
1232 groupClauses = lappend(groupClauses, expr);
1233 }
1234
1235 /*
1236 * If there are any acceptable GROUP BY expressions, build an RTE and
1237 * nsitem for the result of the grouping step. (It's important to do this
1238 * before flattening join alias vars in groupClauses, because the RTE
1239 * should preserve any alias vars that were in the input.)
1240 */
1241 if (groupClauses)
1242 {
1243 pstate->p_grouping_nsitem =
1244 addRangeTableEntryForGroup(pstate, groupClauses);
1245
1246 /* Set qry->rtable again in case it was previously NIL */
1247 qry->rtable = pstate->p_rtable;
1248 /* Mark the Query as having RTE_GROUP RTE */
1249 qry->hasGroupRTE = true;
1250 }
1251
1252 /*
1253 * If there are join alias vars involved, we have to flatten them to the
1254 * underlying vars, so that aliased and unaliased vars will be correctly
1255 * taken as equal. We can skip the expense of doing this if no rangetable
1256 * entries are RTE_JOIN kind.
1257 */
1258 if (hasJoinRTEs)
1259 groupClauses = (List *)
1260 flatten_join_alias_for_parser(qry, (Node *) groupClauses, 0);
1261
1262 /*
1263 * Detect whether any of the grouping expressions aren't simple Vars; if
1264 * they're all Vars then we don't have to work so hard in the recursive
1265 * scans. (Note we have to flatten aliases before this.)
1266 *
1267 * Track Vars that are included in all grouping sets separately in
1268 * groupClauseCommonVars, since these are the only ones we can use to
1269 * check for functional dependencies.
1270 */
1271 have_non_var_grouping = false;
1272 foreach(l, groupClauses)
1273 {
1274 TargetEntry *tle = lfirst(l);
1275
1276 if (!IsA(tle->expr, Var))
1277 {
1278 have_non_var_grouping = true;
1279 }
1280 else if (!qry->groupingSets ||
1281 list_member_int(gset_common, tle->ressortgroupref))
1282 {
1283 groupClauseCommonVars = lappend(groupClauseCommonVars, tle->expr);
1284 }
1285 }
1286
1287 /*
1288 * Replace grouped variables in the targetlist and HAVING clause with Vars
1289 * that reference the RTE_GROUP RTE. Emit an error message if we find any
1290 * ungrouped variables.
1291 *
1292 * Note: because we check resjunk tlist elements as well as regular ones,
1293 * this will also find ungrouped variables that came from ORDER BY and
1294 * WINDOW clauses. For that matter, it's also going to examine the
1295 * grouping expressions themselves --- but they'll all pass the test ...
1296 *
1297 * We also finalize GROUPING expressions, but for that we need to traverse
1298 * the original (unflattened) clause in order to modify nodes.
1299 */
1300 clause = (Node *) qry->targetList;
1301 finalize_grouping_exprs(clause, pstate, qry,
1302 groupClauses, hasJoinRTEs,
1303 have_non_var_grouping);
1304 if (hasJoinRTEs)
1305 clause = flatten_join_alias_for_parser(qry, clause, 0);
1306 qry->targetList = (List *)
1307 substitute_grouped_columns(clause, pstate, qry,
1308 groupClauses, groupClauseCommonVars,
1309 gset_common,
1310 have_non_var_grouping,
1311 &func_grouped_rels);
1312
1313 clause = (Node *) qry->havingQual;
1314 finalize_grouping_exprs(clause, pstate, qry,
1315 groupClauses, hasJoinRTEs,
1316 have_non_var_grouping);
1317 if (hasJoinRTEs)
1318 clause = flatten_join_alias_for_parser(qry, clause, 0);
1319 qry->havingQual =
1320 substitute_grouped_columns(clause, pstate, qry,
1321 groupClauses, groupClauseCommonVars,
1322 gset_common,
1323 have_non_var_grouping,
1324 &func_grouped_rels);
1325
1326 /*
1327 * Per spec, aggregates can't appear in a recursive term.
1328 */
1329 if (pstate->p_hasAggs && hasSelfRefRTEs)
1330 ereport(ERROR,
1332 errmsg("aggregate functions are not allowed in a recursive query's recursive term"),
1333 parser_errposition(pstate,
1334 locate_agg_of_level((Node *) qry, 0))));
1335}
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:1613
List * expand_grouping_sets(List *groupingSets, bool groupDistinct, int limit)
Definition parse_agg.c:1998
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:1350
ParseNamespaceItem * addRangeTableEntryForGroup(ParseState *pstate, List *groupClauses)
@ RTE_JOIN
List * p_rtable
Definition parse_node.h:192
bool groupDistinct
Definition parsenodes.h:217
List * groupClause
Definition parsenodes.h:216
Node * havingQual
Definition parsenodes.h:222
List * rtable
Definition parsenodes.h:175
List * targetList
Definition parsenodes.h:198
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition tlist.c:376

References addRangeTableEntryForGroup(), Assert, ereport, errcode(), errmsg, ERROR, expand_grouping_sets(), exprLocation(), fb(), finalize_grouping_exprs(), flatten_join_alias_for_parser(), 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(), Query::rtable, RTE_CTE, RTE_JOIN, substitute_grouped_columns(), and Query::targetList.

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

◆ resolve_aggregate_transtype()

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

Definition at line 2127 of file parse_agg.c.

2131{
2132 /* resolve actual type of transition state, if polymorphic */
2133 if (IsPolymorphicType(aggtranstype))
2134 {
2135 /* have to fetch the agg's declared input types... */
2137 int agg_nargs;
2138
2140
2141 /*
2142 * VARIADIC ANY aggs could have more actual than declared args, but
2143 * such extra args can't affect polymorphic type resolution.
2144 */
2145 Assert(agg_nargs <= numArguments);
2146
2149 agg_nargs,
2150 aggtranstype,
2151 false);
2153 }
2154 return aggtranstype;
2155}
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition lsyscache.c:1846
void pfree(void *pointer)
Definition mcxt.c:1616
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(), fb(), 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 1350 of file parse_agg.c.

1355{
1357
1358 context.pstate = pstate;
1359 context.qry = qry;
1360 context.hasJoinRTEs = false; /* assume caller flattened join Vars */
1361 context.groupClauses = groupClauses;
1362 context.groupClauseCommonVars = groupClauseCommonVars;
1363 context.groupClauseSubLevels = NIL;
1364 context.gset_common = gset_common;
1365 context.have_non_var_grouping = have_non_var_grouping;
1366 context.func_grouped_rels = func_grouped_rels;
1367 context.sublevels_up = 0;
1368 context.in_agg_direct_args = false;
1369 return substitute_grouped_columns_mutator(node, &context);
1370}
static Node * substitute_grouped_columns_mutator(Node *node, substitute_grouped_columns_context *context)
Definition parse_agg.c:1373

References substitute_grouped_columns_context::func_grouped_rels, substitute_grouped_columns_context::groupClauseCommonVars, substitute_grouped_columns_context::groupClauses, substitute_grouped_columns_context::groupClauseSubLevels, substitute_grouped_columns_context::gset_common, substitute_grouped_columns_context::hasJoinRTEs, substitute_grouped_columns_context::have_non_var_grouping, substitute_grouped_columns_context::in_agg_direct_args, NIL, substitute_grouped_columns_context::pstate, substitute_grouped_columns_context::qry, substitute_grouped_columns_context::sublevels_up, 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 1373 of file parse_agg.c.

1375{
1376 ListCell *gl;
1377
1378 if (node == NULL)
1379 return NULL;
1380
1381 if (IsA(node, Aggref))
1382 {
1383 Aggref *agg = (Aggref *) node;
1384
1385 if ((int) agg->agglevelsup == context->sublevels_up)
1386 {
1387 /*
1388 * If we find an aggregate call of the original level, do not
1389 * recurse into its normal arguments, ORDER BY arguments, or
1390 * filter; grouped vars there do not need to be replaced and
1391 * ungrouped vars there are not an error. But we should check
1392 * direct arguments as though they weren't in an aggregate. We
1393 * set a special flag in the context to help produce a useful
1394 * error message for ungrouped vars in direct arguments.
1395 */
1396 agg = copyObject(agg);
1397
1398 Assert(!context->in_agg_direct_args);
1399 context->in_agg_direct_args = true;
1400 agg->aggdirectargs = (List *)
1401 substitute_grouped_columns_mutator((Node *) agg->aggdirectargs,
1402 context);
1403 context->in_agg_direct_args = false;
1404 return (Node *) agg;
1405 }
1406
1407 /*
1408 * We can skip recursing into aggregates of higher levels altogether,
1409 * since they could not possibly contain Vars of concern to us (see
1410 * transformAggregateCall). We do need to look at aggregates of lower
1411 * levels, however.
1412 */
1413 if ((int) agg->agglevelsup > context->sublevels_up)
1414 return node;
1415 }
1416
1417 if (IsA(node, GroupingFunc))
1418 {
1419 GroupingFunc *grp = (GroupingFunc *) node;
1420
1421 /* handled GroupingFunc separately, no need to recheck at this level */
1422
1423 if ((int) grp->agglevelsup >= context->sublevels_up)
1424 return node;
1425 }
1426
1427 /*
1428 * If we have any GROUP BY items that are not simple Vars, check to see if
1429 * subexpression as a whole matches any GROUP BY item. We need to do this
1430 * at every recursion level so that we recognize GROUPed-BY expressions
1431 * before reaching variables within them. (Since this approach is pretty
1432 * expensive, we don't do it this way if the items are all simple Vars.)
1433 */
1434 if (context->have_non_var_grouping)
1435 {
1436 List *groupClauses;
1437 int attnum = 0;
1438
1439 /* Within a subquery, we need a mutated version of the groupClauses */
1440 if (context->sublevels_up == 0)
1441 groupClauses = context->groupClauses;
1442 else
1443 groupClauses = list_nth(context->groupClauseSubLevels,
1444 context->sublevels_up - 1);
1445
1446 foreach(gl, groupClauses)
1447 {
1449
1450 attnum++;
1451 if (equal(node, tle->expr))
1452 {
1453 /* acceptable, replace it with a GROUP Var */
1454 return (Node *) buildGroupedVar(attnum,
1455 tle->ressortgroupref,
1456 context);
1457 }
1458 }
1459 }
1460
1461 /*
1462 * Constants are always acceptable. We have to do this after we checked
1463 * the subexpression as a whole for a match, because it is possible that
1464 * we have GROUP BY items that are constants, and the constants would
1465 * become not so constant after the grouping step.
1466 */
1467 if (IsA(node, Const) ||
1468 IsA(node, Param))
1469 return node;
1470
1471 /*
1472 * If we have an ungrouped Var of the original query level, we have a
1473 * failure. Vars below the original query level are not a problem, and
1474 * neither are Vars from above it. (If such Vars are ungrouped as far as
1475 * their own query level is concerned, that's someone else's problem...)
1476 */
1477 if (IsA(node, Var))
1478 {
1479 Var *var = (Var *) node;
1481 char *attname;
1482
1483 if (var->varlevelsup != context->sublevels_up)
1484 return node; /* it's not local to my query, ignore */
1485
1486 /*
1487 * Check for a match, if we didn't do it above.
1488 */
1489 if (!context->have_non_var_grouping)
1490 {
1491 int attnum = 0;
1492
1493 foreach(gl, context->groupClauses)
1494 {
1496 Var *gvar = (Var *) tle->expr;
1497
1498 attnum++;
1499 if (IsA(gvar, Var) &&
1500 gvar->varno == var->varno &&
1501 gvar->varattno == var->varattno &&
1502 gvar->varlevelsup == 0)
1503 {
1504 /* acceptable, replace it with a GROUP Var */
1505 return (Node *) buildGroupedVar(attnum,
1506 tle->ressortgroupref,
1507 context);
1508 }
1509 }
1510 }
1511
1512 /*
1513 * Check whether the Var is known functionally dependent on the GROUP
1514 * BY columns. If so, we can allow the Var to be used, because the
1515 * grouping is really a no-op for this table. However, this deduction
1516 * depends on one or more constraints of the table, so we have to add
1517 * those constraints to the query's constraintDeps list, because it's
1518 * not semantically valid anymore if the constraint(s) get dropped.
1519 * (Therefore, this check must be the last-ditch effort before raising
1520 * error: we don't want to add dependencies unnecessarily.)
1521 *
1522 * Because this is a pretty expensive check, and will have the same
1523 * outcome for all columns of a table, we remember which RTEs we've
1524 * already proven functional dependency for in the func_grouped_rels
1525 * list. This test also prevents us from adding duplicate entries to
1526 * the constraintDeps list.
1527 */
1528 if (list_member_int(*context->func_grouped_rels, var->varno))
1529 return node; /* previously proven acceptable */
1530
1531 Assert(var->varno > 0 &&
1532 (int) var->varno <= list_length(context->pstate->p_rtable));
1533 rte = rt_fetch(var->varno, context->pstate->p_rtable);
1534 if (rte->rtekind == RTE_RELATION)
1535 {
1536 if (check_functional_grouping(rte->relid,
1537 var->varno,
1538 0,
1539 context->groupClauseCommonVars,
1540 &context->qry->constraintDeps))
1541 {
1542 *context->func_grouped_rels =
1543 lappend_int(*context->func_grouped_rels, var->varno);
1544 return node; /* acceptable */
1545 }
1546 }
1547
1548 /* Found an ungrouped local variable; generate error message */
1550 if (context->sublevels_up == 0)
1551 ereport(ERROR,
1553 errmsg("column \"%s.%s\" must appear in the GROUP BY clause or be used in an aggregate function",
1554 rte->eref->aliasname, attname),
1555 context->in_agg_direct_args ?
1556 errdetail("Direct arguments of an ordered-set aggregate must use only grouped columns.") : 0,
1557 parser_errposition(context->pstate, var->location)));
1558 else
1559 ereport(ERROR,
1561 errmsg("subquery uses ungrouped column \"%s.%s\" from outer query",
1562 rte->eref->aliasname, attname),
1563 parser_errposition(context->pstate, var->location)));
1564 }
1565
1566 if (IsA(node, Query))
1567 {
1568 /* Recurse into subselects */
1569 Query *newnode;
1570
1571 context->sublevels_up++;
1572
1573 /*
1574 * If we have non-Var grouping expressions, we'll need a copy of the
1575 * groupClauses list that's mutated to match this sublevels_up depth.
1576 * Build one if we've not yet visited a subquery at this depth.
1577 */
1578 if (context->have_non_var_grouping &&
1579 context->sublevels_up > list_length(context->groupClauseSubLevels))
1580 {
1582
1584 context->sublevels_up, 0);
1585 context->groupClauseSubLevels =
1587 Assert(context->sublevels_up == list_length(context->groupClauseSubLevels));
1588 }
1589
1590 newnode = query_tree_mutator((Query *) node,
1592 context,
1593 0);
1594 context->sublevels_up--;
1595 return (Node *) newnode;
1596 }
1598 context);
1599}
#define expression_tree_mutator(n, m, c)
Definition nodeFuncs.h:155
#define query_tree_mutator(q, m, c, f)
Definition nodeFuncs.h:160
static Var * buildGroupedVar(int attnum, Index ressortgroupref, substitute_grouped_columns_context *context)
Definition parse_agg.c:1812
char * get_rte_attribute_name(RangeTblEntry *rte, AttrNumber attnum)
@ RTE_RELATION
#define rt_fetch(rangetable_index, rangetable)
Definition parsetree.h:31
NameData attname
bool check_functional_grouping(Oid relid, Index varno, Index varlevelsup, List *grouping_columns, List **constraintDeps)
ParseLoc location
Definition primnodes.h:311

References Assert, attname, attnum, buildGroupedVar(), check_functional_grouping(), copyObject, equal(), ereport, errcode(), errdetail(), errmsg, ERROR, expression_tree_mutator, fb(), substitute_grouped_columns_context::func_grouped_rels, get_rte_attribute_name(), substitute_grouped_columns_context::groupClauseCommonVars, substitute_grouped_columns_context::groupClauses, substitute_grouped_columns_context::groupClauseSubLevels, substitute_grouped_columns_context::have_non_var_grouping, substitute_grouped_columns_context::in_agg_direct_args, IncrementVarSublevelsUp(), IsA, lappend(), lappend_int(), lfirst, list_length(), list_member_int(), list_nth(), Var::location, ParseState::p_rtable, parser_errposition(), substitute_grouped_columns_context::pstate, substitute_grouped_columns_context::qry, query_tree_mutator, rt_fetch, RTE_RELATION, substitute_grouped_columns_context::sublevels_up, substitute_grouped_columns_mutator(), Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by substitute_grouped_columns(), and substitute_grouped_columns_mutator().

◆ transformAggregateCall()

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

Definition at line 113 of file parse_agg.c.

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

References addTargetToSortList(), arg, Assert, check_agglevels_and_constraints(), ereport, errcode(), errdetail(), errmsg, ERROR, EXPR_KIND_ORDER_BY, exprLocation(), exprType(), fb(), 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(), transformDistinctClause(), and transformSortClause().

Referenced by ParseFuncOrColumn(), and transformJsonAggConstructor().

◆ transformGroupingFunc()

Node * transformGroupingFunc ( ParseState pstate,
GroupingFunc p 
)

Definition at line 269 of file parse_agg.c.

270{
271 ListCell *lc;
272 List *args = p->args;
275
276 if (list_length(args) > 31)
279 errmsg("GROUPING must have fewer than 32 arguments"),
280 parser_errposition(pstate, p->location)));
281
282 foreach(lc, args)
283 {
285
286 current_result = transformExpr(pstate, (Node *) lfirst(lc), pstate->p_expr_kind);
287
288 /* acceptability of expressions is checked later */
289
291 }
292
293 result->args = result_list;
294 result->location = p->location;
295
296 check_agglevels_and_constraints(pstate, (Node *) result);
297
298 return (Node *) result;
299}
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition parse_expr.c:120
ParseLoc location
Definition primnodes.h:574

References check_agglevels_and_constraints(), ereport, errcode(), errmsg, ERROR, fb(), 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 879 of file parse_agg.c.

881{
882 const char *err;
883 bool errkind;
884
885 /*
886 * A window function call can't contain another one (but aggs are OK). XXX
887 * is this required by spec, or just an unimplemented feature?
888 *
889 * Note: we don't need to check the filter expression here, because the
890 * context checks done below and in transformAggregateCall would have
891 * already rejected any window funcs or aggs within the filter.
892 */
893 if (pstate->p_hasWindowFuncs &&
894 contain_windowfuncs((Node *) wfunc->args))
897 errmsg("window function calls cannot be nested"),
898 parser_errposition(pstate,
899 locate_windowfunc((Node *) wfunc->args))));
900
901 /*
902 * Check to see if the window function is in an invalid place within the
903 * query.
904 *
905 * For brevity we support two schemes for reporting an error here: set
906 * "err" to a custom message, or set "errkind" true if the error context
907 * is sufficiently identified by what ParseExprKindName will return, *and*
908 * what it will return is just a SQL keyword. (Otherwise, use a custom
909 * message to avoid creating translation problems.)
910 */
911 err = NULL;
912 errkind = false;
913 switch (pstate->p_expr_kind)
914 {
915 case EXPR_KIND_NONE:
916 Assert(false); /* can't happen */
917 break;
918 case EXPR_KIND_OTHER:
919 /* Accept window func here; caller must throw error if wanted */
920 break;
923 err = _("window functions are not allowed in JOIN conditions");
924 break;
926 /* can't get here, but just in case, throw an error */
927 errkind = true;
928 break;
930 err = _("window functions are not allowed in functions in FROM");
931 break;
932 case EXPR_KIND_WHERE:
933 errkind = true;
934 break;
935 case EXPR_KIND_POLICY:
936 err = _("window functions are not allowed in policy expressions");
937 break;
938 case EXPR_KIND_HAVING:
939 errkind = true;
940 break;
941 case EXPR_KIND_FILTER:
942 errkind = true;
943 break;
949 err = _("window functions are not allowed in window definitions");
950 break;
952 /* okay */
953 break;
957 errkind = true;
958 break;
960 err = _("window functions are not allowed in MERGE WHEN conditions");
961 break;
963 errkind = true;
964 break;
966 /* okay */
967 break;
969 /* okay */
970 break;
971 case EXPR_KIND_LIMIT:
972 case EXPR_KIND_OFFSET:
973 errkind = true;
974 break;
977 errkind = true;
978 break;
979 case EXPR_KIND_VALUES:
981 errkind = true;
982 break;
985 err = _("window functions are not allowed in check constraints");
986 break;
989 err = _("window functions are not allowed in DEFAULT expressions");
990 break;
992 err = _("window functions are not allowed in index expressions");
993 break;
995 err = _("window functions are not allowed in statistics expressions");
996 break;
998 err = _("window functions are not allowed in index predicates");
999 break;
1001 err = _("window functions are not allowed in transform expressions");
1002 break;
1004 err = _("window functions are not allowed in EXECUTE parameters");
1005 break;
1007 err = _("window functions are not allowed in trigger WHEN conditions");
1008 break;
1010 err = _("window functions are not allowed in partition bound");
1011 break;
1013 err = _("window functions are not allowed in partition key expressions");
1014 break;
1016 err = _("window functions are not allowed in CALL arguments");
1017 break;
1019 err = _("window functions are not allowed in COPY FROM WHERE conditions");
1020 break;
1022 err = _("window functions are not allowed in column generation expressions");
1023 break;
1025 errkind = true;
1026 break;
1027
1028 /*
1029 * There is intentionally no default: case here, so that the
1030 * compiler will warn if we add a new ParseExprKind without
1031 * extending this switch. If we do see an unrecognized value at
1032 * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
1033 * which is sane anyway.
1034 */
1035 }
1036 if (err)
1037 ereport(ERROR,
1039 errmsg_internal("%s", err),
1040 parser_errposition(pstate, wfunc->location)));
1041 if (errkind)
1042 ereport(ERROR,
1044 /* translator: %s is name of a SQL construct, eg GROUP BY */
1045 errmsg("window functions are not allowed in %s",
1047 parser_errposition(pstate, wfunc->location)));
1048
1049 /*
1050 * If the OVER clause just specifies a window name, find that WINDOW
1051 * clause (which had better be present). Otherwise, try to match all the
1052 * properties of the OVER clause, and make a new entry in the p_windowdefs
1053 * list if no luck.
1054 */
1055 if (windef->name)
1056 {
1057 Index winref = 0;
1058 ListCell *lc;
1059
1060 Assert(windef->refname == NULL &&
1061 windef->partitionClause == NIL &&
1062 windef->orderClause == NIL &&
1063 windef->frameOptions == FRAMEOPTION_DEFAULTS);
1064
1065 foreach(lc, pstate->p_windowdefs)
1066 {
1068
1069 winref++;
1070 if (refwin->name && strcmp(refwin->name, windef->name) == 0)
1071 {
1072 wfunc->winref = winref;
1073 break;
1074 }
1075 }
1076 if (lc == NULL) /* didn't find it? */
1077 ereport(ERROR,
1079 errmsg("window \"%s\" does not exist", windef->name),
1080 parser_errposition(pstate, windef->location)));
1081 }
1082 else
1083 {
1084 Index winref = 0;
1085 ListCell *lc;
1086
1087 foreach(lc, pstate->p_windowdefs)
1088 {
1090
1091 winref++;
1092 if (refwin->refname && windef->refname &&
1093 strcmp(refwin->refname, windef->refname) == 0)
1094 /* matched on refname */ ;
1095 else if (!refwin->refname && !windef->refname)
1096 /* matched, no refname */ ;
1097 else
1098 continue;
1099
1100 /*
1101 * Also see similar de-duplication code in optimize_window_clauses
1102 */
1103 if (equal(refwin->partitionClause, windef->partitionClause) &&
1104 equal(refwin->orderClause, windef->orderClause) &&
1105 refwin->frameOptions == windef->frameOptions &&
1106 equal(refwin->startOffset, windef->startOffset) &&
1107 equal(refwin->endOffset, windef->endOffset))
1108 {
1109 /* found a duplicate window specification */
1110 wfunc->winref = winref;
1111 break;
1112 }
1113 }
1114 if (lc == NULL) /* didn't find it? */
1115 {
1116 pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
1117 wfunc->winref = list_length(pstate->p_windowdefs);
1118 }
1119 }
1120
1121 pstate->p_hasWindowFuncs = true;
1122}
#define FRAMEOPTION_DEFAULTS
Definition parsenodes.h:636
bool contain_windowfuncs(Node *node)
int locate_windowfunc(Node *node)
bool p_hasWindowFuncs
Definition parse_node.h:222
List * p_windowdefs
Definition parse_node.h:208
List * args
Definition primnodes.h:606
Index winref
Definition primnodes.h:612
ParseLoc location
Definition primnodes.h:620

References _, WindowFunc::args, Assert, contain_windowfuncs(), 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, fb(), FRAMEOPTION_DEFAULTS, lappend(), lfirst, list_length(), locate_windowfunc(), WindowFunc::location, NIL, ParseState::p_expr_kind, ParseState::p_hasWindowFuncs, ParseState::p_windowdefs, ParseExprKindName(), parser_errposition(), and WindowFunc::winref.

Referenced by ParseFuncOrColumn(), and transformJsonAggConstructor().