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

2115{
2116 ListCell *lc;
2117
2118 foreach(lc, aggref->args)
2119 {
2123 Oid type = exprType((Node *) tle->expr);
2124
2125 /*
2126 * RECORD is a special case: it has typsend/typreceive functions, but
2127 * record_recv only works if passed the correct typmod to identify the
2128 * specific anonymous record type. array_agg_deserialize cannot do
2129 * that, so we have to disclaim support for the case.
2130 */
2131 if (type == RECORDOID)
2132 return false;
2133
2136 elog(ERROR, "cache lookup failed for type %u", type);
2137
2139
2140 if (!pt->typbyval &&
2141 (!OidIsValid(pt->typsend) || !OidIsValid(pt->typreceive)))
2142 {
2144 return false;
2145 }
2147 }
2148 return true;
2149}
#define OidIsValid(objectId)
Definition c.h:800
#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 2265 of file parse_agg.c.

2267{
2268 List *args;
2269 FuncExpr *fexpr;
2270
2271 /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2274
2275 fexpr = makeFuncExpr(deserialfn_oid,
2277 args,
2278 InvalidOid,
2279 InvalidOid,
2281 *deserialfnexpr = (Expr *) fexpr;
2282}
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:2329
#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 2289 of file parse_agg.c.

2296{
2297 List *args;
2298 int i;
2299
2300 /*
2301 * Build expr tree for final function
2302 */
2304
2305 /* finalfn may take additional args, which match agg's input types */
2306 for (i = 0; i < num_finalfn_inputs - 1; i++)
2307 {
2308 args = lappend(args,
2310 }
2311
2312 *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2314 args,
2315 InvalidOid,
2318 /* finalfn is currently never treated as variadic */
2319}
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 2242 of file parse_agg.c.

2244{
2245 List *args;
2246 FuncExpr *fexpr;
2247
2248 /* serialfn always takes INTERNAL and returns BYTEA */
2250
2251 fexpr = makeFuncExpr(serialfn_oid,
2252 BYTEAOID,
2253 args,
2254 InvalidOid,
2255 InvalidOid,
2257 *serialfnexpr = (Expr *) fexpr;
2258}

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

2191{
2192 List *args;
2193 FuncExpr *fexpr;
2194 int i;
2195
2196 /*
2197 * Build arg list to use in the transfn FuncExpr node.
2198 */
2200
2202 {
2203 args = lappend(args,
2205 }
2206
2207 fexpr = makeFuncExpr(transfn_oid,
2209 args,
2210 InvalidOid,
2213 fexpr->funcvariadic = agg_variadic;
2214 *transfnexpr = (Expr *) fexpr;
2215
2216 /*
2217 * Build invtransfn expression if requested, with same args as transfn
2218 */
2219 if (invtransfnexpr != NULL)
2220 {
2221 if (OidIsValid(invtransfn_oid))
2222 {
2223 fexpr = makeFuncExpr(invtransfn_oid,
2225 args,
2226 InvalidOid,
2229 fexpr->funcvariadic = agg_variadic;
2230 *invtransfnexpr = (Expr *) fexpr;
2231 }
2232 else
2234 }
2235}

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

1765{
1766 Var *var;
1768 ParseNamespaceColumn *nscol = grouping_nsitem->p_nscolumns + attnum - 1;
1769
1770 Assert(nscol->p_varno == grouping_nsitem->p_rtindex);
1771 Assert(nscol->p_varattno == attnum);
1772 var = makeVar(nscol->p_varno,
1773 nscol->p_varattno,
1774 nscol->p_vartype,
1775 nscol->p_vartypmod,
1776 nscol->p_varcollid,
1777 context->sublevels_up);
1778 /* makeVar doesn't offer parameters for these, so set by hand: */
1779 var->varnosyn = nscol->p_varnosyn;
1780 var->varattnosyn = nscol->p_varattnosyn;
1781
1782 if (context->qry->groupingSets &&
1783 !list_member_int(context->gset_common, ressortgroupref))
1784 var->varnullingrels =
1785 bms_add_member(var->varnullingrels, grouping_nsitem->p_rtindex);
1786
1787 return var;
1788}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
#define Assert(condition)
Definition c.h:885
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 645 of file parse_agg.c.

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

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

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

1906{
1907 int la = list_length((const List *) lfirst(a));
1908 int lb = list_length((const List *) lfirst(b));
1909
1910 return pg_cmp_s32(la, lb);
1911}
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 1915 of file parse_agg.c.

1916{
1917 int res = cmp_list_len_asc(a, b);
1918
1919 if (res == 0)
1920 {
1921 List *la = (List *) lfirst(a);
1922 List *lb = (List *) lfirst(b);
1923 ListCell *lca;
1924 ListCell *lcb;
1925
1926 forboth(lca, la, lcb, lb)
1927 {
1928 int va = lfirst_int(lca);
1929 int vb = lfirst_int(lcb);
1930
1931 if (va > vb)
1932 return 1;
1933 if (va < vb)
1934 return -1;
1935 }
1936 }
1937
1938 return res;
1939}
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:1905
#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 1949 of file parse_agg.c.

1950{
1952 List *result = NIL;
1953 double numsets = 1;
1954 ListCell *lc;
1955
1956 if (groupingSets == NIL)
1957 return NIL;
1958
1959 foreach(lc, groupingSets)
1960 {
1962 GroupingSet *gs = lfirst(lc);
1963
1965
1967
1968 numsets *= list_length(current_result);
1969
1970 if (limit >= 0 && numsets > limit)
1971 return NIL;
1972
1974 }
1975
1976 /*
1977 * Do cartesian product between sublists of expanded_groups. While at it,
1978 * remove any duplicate elements from individual grouping sets (we must
1979 * NOT change the number of sets though)
1980 */
1981
1982 foreach(lc, (List *) linitial(expanded_groups))
1983 {
1984 result = lappend(result, list_union_int(NIL, (List *) lfirst(lc)));
1985 }
1986
1988 {
1989 List *p = lfirst(lc);
1990 List *new_result = NIL;
1991 ListCell *lc2;
1992
1993 foreach(lc2, result)
1994 {
1995 List *q = lfirst(lc2);
1996 ListCell *lc3;
1997
1998 foreach(lc3, p)
1999 {
2001 list_union_int(q, (List *) lfirst(lc3)));
2002 }
2003 }
2004 result = new_result;
2005 }
2006
2007 /* Now sort the lists by length and deduplicate if necessary */
2008 if (!groupDistinct || list_length(result) < 2)
2009 list_sort(result, cmp_list_len_asc);
2010 else
2011 {
2012 ListCell *cell;
2013 List *prev;
2014
2015 /* Sort each groupset individually */
2016 foreach(cell, result)
2018
2019 /* Now sort the list of groupsets by length and contents */
2021
2022 /* Finally, remove duplicates */
2023 prev = linitial(result);
2024 for_each_from(cell, result, 1)
2025 {
2026 if (equal(lfirst(cell), prev))
2027 result = foreach_delete_current(result, cell);
2028 else
2029 prev = lfirst(cell);
2030 }
2031 }
2032
2033 return result;
2034}
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:1915
static List * expand_groupingset_node(GroupingSet *gs)
Definition parse_agg.c:1803
#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 1803 of file parse_agg.c.

1804{
1805 List *result = NIL;
1806
1807 switch (gs->kind)
1808 {
1809 case GROUPING_SET_EMPTY:
1810 result = list_make1(NIL);
1811 break;
1812
1814 result = list_make1(gs->content);
1815 break;
1816
1818 {
1819 List *rollup_val = gs->content;
1820 ListCell *lc;
1821 int curgroup_size = list_length(gs->content);
1822
1823 while (curgroup_size > 0)
1824 {
1826 int i = curgroup_size;
1827
1828 foreach(lc, rollup_val)
1829 {
1831
1833
1835 gs_current->content);
1836
1837 /* If we are done with making the current group, break */
1838 if (--i == 0)
1839 break;
1840 }
1841
1842 result = lappend(result, current_result);
1843 --curgroup_size;
1844 }
1845
1846 result = lappend(result, NIL);
1847 }
1848 break;
1849
1850 case GROUPING_SET_CUBE:
1851 {
1852 List *cube_list = gs->content;
1855 uint32 i;
1856
1857 /* parser should cap this much lower */
1858 Assert(number_bits < 31);
1859
1860 num_sets = (1U << number_bits);
1861
1862 for (i = 0; i < num_sets; i++)
1863 {
1865 ListCell *lc;
1866 uint32 mask = 1U;
1867
1868 foreach(lc, cube_list)
1869 {
1871
1873
1874 if (mask & i)
1876 gs_current->content);
1877
1878 mask <<= 1;
1879 }
1880
1881 result = lappend(result, current_result);
1882 }
1883 }
1884 break;
1885
1886 case GROUPING_SET_SETS:
1887 {
1888 ListCell *lc;
1889
1890 foreach(lc, gs->content)
1891 {
1893
1894 result = list_concat(result, current_result);
1895 }
1896 }
1897 break;
1898 }
1899
1900 return result;
1901}
uint32_t uint32
Definition c.h:558
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 1596 of file parse_agg.c.

1599{
1601
1602 context.pstate = pstate;
1603 context.qry = qry;
1604 context.hasJoinRTEs = hasJoinRTEs;
1605 context.groupClauses = groupClauses;
1606 context.groupClauseCommonVars = NIL;
1607 context.gset_common = NIL;
1608 context.have_non_var_grouping = have_non_var_grouping;
1609 context.func_grouped_rels = NULL;
1610 context.sublevels_up = 0;
1611 context.in_agg_direct_args = false;
1612 finalize_grouping_exprs_walker(node, &context);
1613}
static bool finalize_grouping_exprs_walker(Node *node, substitute_grouped_columns_context *context)
Definition parse_agg.c:1616

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

1618{
1619 ListCell *gl;
1620
1621 if (node == NULL)
1622 return false;
1623 if (IsA(node, Const) ||
1624 IsA(node, Param))
1625 return false; /* constants are always acceptable */
1626
1627 if (IsA(node, Aggref))
1628 {
1629 Aggref *agg = (Aggref *) node;
1630
1631 if ((int) agg->agglevelsup == context->sublevels_up)
1632 {
1633 /*
1634 * If we find an aggregate call of the original level, do not
1635 * recurse into its normal arguments, ORDER BY arguments, or
1636 * filter; GROUPING exprs of this level are not allowed there. But
1637 * check direct arguments as though they weren't in an aggregate.
1638 */
1639 bool result;
1640
1641 Assert(!context->in_agg_direct_args);
1642 context->in_agg_direct_args = true;
1643 result = finalize_grouping_exprs_walker((Node *) agg->aggdirectargs,
1644 context);
1645 context->in_agg_direct_args = false;
1646 return result;
1647 }
1648
1649 /*
1650 * We can skip recursing into aggregates of higher levels altogether,
1651 * since they could not possibly contain exprs of concern to us (see
1652 * transformAggregateCall). We do need to look at aggregates of lower
1653 * levels, however.
1654 */
1655 if ((int) agg->agglevelsup > context->sublevels_up)
1656 return false;
1657 }
1658
1659 if (IsA(node, GroupingFunc))
1660 {
1661 GroupingFunc *grp = (GroupingFunc *) node;
1662
1663 /*
1664 * We only need to check GroupingFunc nodes at the exact level to
1665 * which they belong, since they cannot mix levels in arguments.
1666 */
1667
1668 if ((int) grp->agglevelsup == context->sublevels_up)
1669 {
1670 ListCell *lc;
1671 List *ref_list = NIL;
1672
1673 foreach(lc, grp->args)
1674 {
1675 Node *expr = lfirst(lc);
1676 Index ref = 0;
1677
1678 if (context->hasJoinRTEs)
1679 expr = flatten_join_alias_vars(NULL, context->qry, expr);
1680
1681 /*
1682 * Each expression must match a grouping entry at the current
1683 * query level. Unlike the general expression case, we don't
1684 * allow functional dependencies or outer references.
1685 */
1686
1687 if (IsA(expr, Var))
1688 {
1689 Var *var = (Var *) expr;
1690
1691 if (var->varlevelsup == context->sublevels_up)
1692 {
1693 foreach(gl, context->groupClauses)
1694 {
1696 Var *gvar = (Var *) tle->expr;
1697
1698 if (IsA(gvar, Var) &&
1699 gvar->varno == var->varno &&
1700 gvar->varattno == var->varattno &&
1701 gvar->varlevelsup == 0)
1702 {
1703 ref = tle->ressortgroupref;
1704 break;
1705 }
1706 }
1707 }
1708 }
1709 else if (context->have_non_var_grouping &&
1710 context->sublevels_up == 0)
1711 {
1712 foreach(gl, context->groupClauses)
1713 {
1715
1716 if (equal(expr, tle->expr))
1717 {
1718 ref = tle->ressortgroupref;
1719 break;
1720 }
1721 }
1722 }
1723
1724 if (ref == 0)
1725 ereport(ERROR,
1727 errmsg("arguments to GROUPING must be grouping expressions of the associated query level"),
1728 parser_errposition(context->pstate,
1729 exprLocation(expr))));
1730
1732 }
1733
1734 grp->refs = ref_list;
1735 }
1736
1737 if ((int) grp->agglevelsup > context->sublevels_up)
1738 return false;
1739 }
1740
1741 if (IsA(node, Query))
1742 {
1743 /* Recurse into subselects */
1744 bool result;
1745
1746 context->sublevels_up++;
1747 result = query_tree_walker((Query *) node,
1749 context,
1750 0);
1751 context->sublevels_up--;
1752 return result;
1753 }
1755 context);
1756}
List * lappend_int(List *list, int datum)
Definition list.c:357
AttrNumber varattno
Definition primnodes.h:275
int varno
Definition primnodes.h:270
Index varlevelsup
Definition primnodes.h:295
Node * flatten_join_alias_vars(PlannerInfo *root, Query *query, Node *node)
Definition var.c:789

References Assert, equal(), ereport, errcode(), errmsg(), ERROR, expression_tree_walker, exprLocation(), fb(), finalize_grouping_exprs_walker(), flatten_join_alias_vars(), substitute_grouped_columns_context::groupClauses, substitute_grouped_columns_context::hasJoinRTEs, substitute_grouped_columns_context::have_non_var_grouping, substitute_grouped_columns_context::in_agg_direct_args, IsA, lappend_int(), lfirst, 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 2052 of file parse_agg.c.

2053{
2054 int numArguments = 0;
2055 ListCell *lc;
2056
2057 Assert(list_length(aggref->aggargtypes) <= FUNC_MAX_ARGS);
2058
2059 foreach(lc, aggref->aggargtypes)
2060 {
2061 inputTypes[numArguments++] = lfirst_oid(lc);
2062 }
2063
2064 return numArguments;
2065}
#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 2329 of file parse_agg.c.

2330{
2332
2333 argp->paramkind = PARAM_EXEC;
2334 argp->paramid = -1;
2335 argp->paramtype = argtype;
2336 argp->paramtypmod = -1;
2337 argp->paramcollid = argcollation;
2338 argp->location = -1;
2339 return (Node *) argp;
2340}
#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 1138 of file parse_agg.c.

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

2082{
2083 /* resolve actual type of transition state, if polymorphic */
2084 if (IsPolymorphicType(aggtranstype))
2085 {
2086 /* have to fetch the agg's declared input types... */
2088 int agg_nargs;
2089
2091
2092 /*
2093 * VARIADIC ANY aggs could have more actual than declared args, but
2094 * such extra args can't affect polymorphic type resolution.
2095 */
2096 Assert(agg_nargs <= numArguments);
2097
2100 agg_nargs,
2101 aggtranstype,
2102 false);
2104 }
2105 return aggtranstype;
2106}
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 1360 of file parse_agg.c.

1365{
1367
1368 context.pstate = pstate;
1369 context.qry = qry;
1370 context.hasJoinRTEs = false; /* assume caller flattened join Vars */
1371 context.groupClauses = groupClauses;
1372 context.groupClauseCommonVars = groupClauseCommonVars;
1373 context.gset_common = gset_common;
1374 context.have_non_var_grouping = have_non_var_grouping;
1375 context.func_grouped_rels = func_grouped_rels;
1376 context.sublevels_up = 0;
1377 context.in_agg_direct_args = false;
1378 return substitute_grouped_columns_mutator(node, &context);
1379}
static Node * substitute_grouped_columns_mutator(Node *node, substitute_grouped_columns_context *context)
Definition parse_agg.c:1382

References substitute_grouped_columns_context::func_grouped_rels, substitute_grouped_columns_context::groupClauseCommonVars, substitute_grouped_columns_context::groupClauses, 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, 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 1382 of file parse_agg.c.

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

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

269{
270 ListCell *lc;
271 List *args = p->args;
274
275 if (list_length(args) > 31)
278 errmsg("GROUPING must have fewer than 32 arguments"),
279 parser_errposition(pstate, p->location)));
280
281 foreach(lc, args)
282 {
284
285 current_result = transformExpr(pstate, (Node *) lfirst(lc), pstate->p_expr_kind);
286
287 /* acceptability of expressions is checked later */
288
290 }
291
292 result->args = result_list;
293 result->location = p->location;
294
295 check_agglevels_and_constraints(pstate, (Node *) result);
296
297 return (Node *) result;
298}
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 878 of file parse_agg.c.

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