LCOV - code coverage report
Current view: top level - src/backend/parser - parse_agg.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 578 764 75.7 %
Date: 2021-12-04 22:09:09 Functions: 22 22 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * parse_agg.c
       4             :  *    handle aggregates and window functions in parser
       5             :  *
       6             :  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/parser/parse_agg.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : #include "postgres.h"
      16             : 
      17             : #include "catalog/pg_aggregate.h"
      18             : #include "catalog/pg_constraint.h"
      19             : #include "catalog/pg_type.h"
      20             : #include "nodes/makefuncs.h"
      21             : #include "nodes/nodeFuncs.h"
      22             : #include "optimizer/optimizer.h"
      23             : #include "parser/parse_agg.h"
      24             : #include "parser/parse_clause.h"
      25             : #include "parser/parse_coerce.h"
      26             : #include "parser/parse_expr.h"
      27             : #include "parser/parsetree.h"
      28             : #include "rewrite/rewriteManip.h"
      29             : #include "utils/builtins.h"
      30             : #include "utils/lsyscache.h"
      31             : 
      32             : 
      33             : typedef struct
      34             : {
      35             :     ParseState *pstate;
      36             :     int         min_varlevel;
      37             :     int         min_agglevel;
      38             :     int         sublevels_up;
      39             : } check_agg_arguments_context;
      40             : 
      41             : typedef struct
      42             : {
      43             :     ParseState *pstate;
      44             :     Query      *qry;
      45             :     bool        hasJoinRTEs;
      46             :     List       *groupClauses;
      47             :     List       *groupClauseCommonVars;
      48             :     bool        have_non_var_grouping;
      49             :     List      **func_grouped_rels;
      50             :     int         sublevels_up;
      51             :     bool        in_agg_direct_args;
      52             : } check_ungrouped_columns_context;
      53             : 
      54             : static int  check_agg_arguments(ParseState *pstate,
      55             :                                 List *directargs,
      56             :                                 List *args,
      57             :                                 Expr *filter);
      58             : static bool check_agg_arguments_walker(Node *node,
      59             :                                        check_agg_arguments_context *context);
      60             : static void check_ungrouped_columns(Node *node, ParseState *pstate, Query *qry,
      61             :                                     List *groupClauses, List *groupClauseCommonVars,
      62             :                                     bool have_non_var_grouping,
      63             :                                     List **func_grouped_rels);
      64             : static bool check_ungrouped_columns_walker(Node *node,
      65             :                                            check_ungrouped_columns_context *context);
      66             : static void finalize_grouping_exprs(Node *node, ParseState *pstate, Query *qry,
      67             :                                     List *groupClauses, bool hasJoinRTEs,
      68             :                                     bool have_non_var_grouping);
      69             : static bool finalize_grouping_exprs_walker(Node *node,
      70             :                                            check_ungrouped_columns_context *context);
      71             : static void check_agglevels_and_constraints(ParseState *pstate, Node *expr);
      72             : static List *expand_groupingset_node(GroupingSet *gs);
      73             : static Node *make_agg_arg(Oid argtype, Oid argcollation);
      74             : 
      75             : 
      76             : /*
      77             :  * transformAggregateCall -
      78             :  *      Finish initial transformation of an aggregate call
      79             :  *
      80             :  * parse_func.c has recognized the function as an aggregate, and has set up
      81             :  * all the fields of the Aggref except aggargtypes, aggdirectargs, args,
      82             :  * aggorder, aggdistinct and agglevelsup.  The passed-in args list has been
      83             :  * through standard expression transformation and type coercion to match the
      84             :  * agg's declared arg types, while the passed-in aggorder list hasn't been
      85             :  * transformed at all.
      86             :  *
      87             :  * Here we separate the args list into direct and aggregated args, storing the
      88             :  * former in agg->aggdirectargs and the latter in agg->args.  The regular
      89             :  * args, but not the direct args, are converted into a targetlist by inserting
      90             :  * TargetEntry nodes.  We then transform the aggorder and agg_distinct
      91             :  * specifications to produce lists of SortGroupClause nodes for agg->aggorder
      92             :  * and agg->aggdistinct.  (For a regular aggregate, this might result in
      93             :  * adding resjunk expressions to the targetlist; but for ordered-set
      94             :  * aggregates the aggorder list will always be one-to-one with the aggregated
      95             :  * args.)
      96             :  *
      97             :  * We must also determine which query level the aggregate actually belongs to,
      98             :  * set agglevelsup accordingly, and mark p_hasAggs true in the corresponding
      99             :  * pstate level.
     100             :  */
     101             : void
     102       58838 : transformAggregateCall(ParseState *pstate, Aggref *agg,
     103             :                        List *args, List *aggorder, bool agg_distinct)
     104             : {
     105       58838 :     List       *argtypes = NIL;
     106       58838 :     List       *tlist = NIL;
     107       58838 :     List       *torder = NIL;
     108       58838 :     List       *tdistinct = NIL;
     109       58838 :     AttrNumber  attno = 1;
     110             :     int         save_next_resno;
     111             :     ListCell   *lc;
     112             : 
     113             :     /*
     114             :      * Before separating the args into direct and aggregated args, make a list
     115             :      * of their data type OIDs for use later.
     116             :      */
     117      111138 :     foreach(lc, args)
     118             :     {
     119       52300 :         Expr       *arg = (Expr *) lfirst(lc);
     120             : 
     121       52300 :         argtypes = lappend_oid(argtypes, exprType((Node *) arg));
     122             :     }
     123       58838 :     agg->aggargtypes = argtypes;
     124             : 
     125       58838 :     if (AGGKIND_IS_ORDERED_SET(agg->aggkind))
     126             :     {
     127             :         /*
     128             :          * For an ordered-set agg, the args list includes direct args and
     129             :          * aggregated args; we must split them apart.
     130             :          */
     131         220 :         int         numDirectArgs = list_length(args) - list_length(aggorder);
     132             :         List       *aargs;
     133             :         ListCell   *lc2;
     134             : 
     135             :         Assert(numDirectArgs >= 0);
     136             : 
     137         220 :         aargs = list_copy_tail(args, numDirectArgs);
     138         220 :         agg->aggdirectargs = list_truncate(args, numDirectArgs);
     139             : 
     140             :         /*
     141             :          * Build a tlist from the aggregated args, and make a sortlist entry
     142             :          * for each one.  Note that the expressions in the SortBy nodes are
     143             :          * ignored (they are the raw versions of the transformed args); we are
     144             :          * just looking at the sort information in the SortBy nodes.
     145             :          */
     146         478 :         forboth(lc, aargs, lc2, aggorder)
     147             :         {
     148         258 :             Expr       *arg = (Expr *) lfirst(lc);
     149         258 :             SortBy     *sortby = (SortBy *) lfirst(lc2);
     150             :             TargetEntry *tle;
     151             : 
     152             :             /* We don't bother to assign column names to the entries */
     153         258 :             tle = makeTargetEntry(arg, attno++, NULL, false);
     154         258 :             tlist = lappend(tlist, tle);
     155             : 
     156         258 :             torder = addTargetToSortList(pstate, tle,
     157             :                                          torder, tlist, sortby);
     158             :         }
     159             : 
     160             :         /* Never any DISTINCT in an ordered-set agg */
     161             :         Assert(!agg_distinct);
     162             :     }
     163             :     else
     164             :     {
     165             :         /* Regular aggregate, so it has no direct args */
     166       58618 :         agg->aggdirectargs = NIL;
     167             : 
     168             :         /*
     169             :          * Transform the plain list of Exprs into a targetlist.
     170             :          */
     171      110406 :         foreach(lc, args)
     172             :         {
     173       51788 :             Expr       *arg = (Expr *) lfirst(lc);
     174             :             TargetEntry *tle;
     175             : 
     176             :             /* We don't bother to assign column names to the entries */
     177       51788 :             tle = makeTargetEntry(arg, attno++, NULL, false);
     178       51788 :             tlist = lappend(tlist, tle);
     179             :         }
     180             : 
     181             :         /*
     182             :          * If we have an ORDER BY, transform it.  This will add columns to the
     183             :          * tlist if they appear in ORDER BY but weren't already in the arg
     184             :          * list.  They will be marked resjunk = true so we can tell them apart
     185             :          * from regular aggregate arguments later.
     186             :          *
     187             :          * We need to mess with p_next_resno since it will be used to number
     188             :          * any new targetlist entries.
     189             :          */
     190       58618 :         save_next_resno = pstate->p_next_resno;
     191       58618 :         pstate->p_next_resno = attno;
     192             : 
     193       58618 :         torder = transformSortClause(pstate,
     194             :                                      aggorder,
     195             :                                      &tlist,
     196             :                                      EXPR_KIND_ORDER_BY,
     197             :                                      true /* force SQL99 rules */ );
     198             : 
     199             :         /*
     200             :          * If we have DISTINCT, transform that to produce a distinctList.
     201             :          */
     202       58618 :         if (agg_distinct)
     203             :         {
     204         308 :             tdistinct = transformDistinctClause(pstate, &tlist, torder, true);
     205             : 
     206             :             /*
     207             :              * Remove this check if executor support for hashed distinct for
     208             :              * aggregates is ever added.
     209             :              */
     210         672 :             foreach(lc, tdistinct)
     211             :             {
     212         388 :                 SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc);
     213             : 
     214         388 :                 if (!OidIsValid(sortcl->sortop))
     215             :                 {
     216           0 :                     Node       *expr = get_sortgroupclause_expr(sortcl, tlist);
     217             : 
     218           0 :                     ereport(ERROR,
     219             :                             (errcode(ERRCODE_UNDEFINED_FUNCTION),
     220             :                              errmsg("could not identify an ordering operator for type %s",
     221             :                                     format_type_be(exprType(expr))),
     222             :                              errdetail("Aggregates with DISTINCT must be able to sort their inputs."),
     223             :                              parser_errposition(pstate, exprLocation(expr))));
     224             :                 }
     225             :             }
     226             :         }
     227             : 
     228       58594 :         pstate->p_next_resno = save_next_resno;
     229             :     }
     230             : 
     231             :     /* Update the Aggref with the transformation results */
     232       58814 :     agg->args = tlist;
     233       58814 :     agg->aggorder = torder;
     234       58814 :     agg->aggdistinct = tdistinct;
     235             : 
     236       58814 :     check_agglevels_and_constraints(pstate, (Node *) agg);
     237       58730 : }
     238             : 
     239             : /*
     240             :  * transformGroupingFunc
     241             :  *      Transform a GROUPING expression
     242             :  *
     243             :  * GROUPING() behaves very like an aggregate.  Processing of levels and nesting
     244             :  * is done as for aggregates.  We set p_hasAggs for these expressions too.
     245             :  */
     246             : Node *
     247         180 : transformGroupingFunc(ParseState *pstate, GroupingFunc *p)
     248             : {
     249             :     ListCell   *lc;
     250         180 :     List       *args = p->args;
     251         180 :     List       *result_list = NIL;
     252         180 :     GroupingFunc *result = makeNode(GroupingFunc);
     253             : 
     254         180 :     if (list_length(args) > 31)
     255           0 :         ereport(ERROR,
     256             :                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
     257             :                  errmsg("GROUPING must have fewer than 32 arguments"),
     258             :                  parser_errposition(pstate, p->location)));
     259             : 
     260         492 :     foreach(lc, args)
     261             :     {
     262             :         Node       *current_result;
     263             : 
     264         312 :         current_result = transformExpr(pstate, (Node *) lfirst(lc), pstate->p_expr_kind);
     265             : 
     266             :         /* acceptability of expressions is checked later */
     267             : 
     268         312 :         result_list = lappend(result_list, current_result);
     269             :     }
     270             : 
     271         180 :     result->args = result_list;
     272         180 :     result->location = p->location;
     273             : 
     274         180 :     check_agglevels_and_constraints(pstate, (Node *) result);
     275             : 
     276         180 :     return (Node *) result;
     277             : }
     278             : 
     279             : /*
     280             :  * Aggregate functions and grouping operations (which are combined in the spec
     281             :  * as <set function specification>) are very similar with regard to level and
     282             :  * nesting restrictions (though we allow a lot more things than the spec does).
     283             :  * Centralise those restrictions here.
     284             :  */
     285             : static void
     286       58994 : check_agglevels_and_constraints(ParseState *pstate, Node *expr)
     287             : {
     288       58994 :     List       *directargs = NIL;
     289       58994 :     List       *args = NIL;
     290       58994 :     Expr       *filter = NULL;
     291             :     int         min_varlevel;
     292       58994 :     int         location = -1;
     293             :     Index      *p_levelsup;
     294             :     const char *err;
     295             :     bool        errkind;
     296       58994 :     bool        isAgg = IsA(expr, Aggref);
     297             : 
     298       58994 :     if (isAgg)
     299             :     {
     300       58814 :         Aggref     *agg = (Aggref *) expr;
     301             : 
     302       58814 :         directargs = agg->aggdirectargs;
     303       58814 :         args = agg->args;
     304       58814 :         filter = agg->aggfilter;
     305       58814 :         location = agg->location;
     306       58814 :         p_levelsup = &agg->agglevelsup;
     307             :     }
     308             :     else
     309             :     {
     310         180 :         GroupingFunc *grp = (GroupingFunc *) expr;
     311             : 
     312         180 :         args = grp->args;
     313         180 :         location = grp->location;
     314         180 :         p_levelsup = &grp->agglevelsup;
     315             :     }
     316             : 
     317             :     /*
     318             :      * Check the arguments to compute the aggregate's level and detect
     319             :      * improper nesting.
     320             :      */
     321       58994 :     min_varlevel = check_agg_arguments(pstate,
     322             :                                        directargs,
     323             :                                        args,
     324             :                                        filter);
     325             : 
     326       58966 :     *p_levelsup = min_varlevel;
     327             : 
     328             :     /* Mark the correct pstate level as having aggregates */
     329       59056 :     while (min_varlevel-- > 0)
     330          90 :         pstate = pstate->parentParseState;
     331       58966 :     pstate->p_hasAggs = true;
     332             : 
     333             :     /*
     334             :      * Check to see if the aggregate function is in an invalid place within
     335             :      * its aggregation query.
     336             :      *
     337             :      * For brevity we support two schemes for reporting an error here: set
     338             :      * "err" to a custom message, or set "errkind" true if the error context
     339             :      * is sufficiently identified by what ParseExprKindName will return, *and*
     340             :      * what it will return is just a SQL keyword.  (Otherwise, use a custom
     341             :      * message to avoid creating translation problems.)
     342             :      */
     343       58966 :     err = NULL;
     344       58966 :     errkind = false;
     345       58966 :     switch (pstate->p_expr_kind)
     346             :     {
     347           0 :         case EXPR_KIND_NONE:
     348             :             Assert(false);      /* can't happen */
     349           0 :             break;
     350           0 :         case EXPR_KIND_OTHER:
     351             : 
     352             :             /*
     353             :              * Accept aggregate/grouping here; caller must throw error if
     354             :              * wanted
     355             :              */
     356           0 :             break;
     357           0 :         case EXPR_KIND_JOIN_ON:
     358             :         case EXPR_KIND_JOIN_USING:
     359           0 :             if (isAgg)
     360           0 :                 err = _("aggregate functions are not allowed in JOIN conditions");
     361             :             else
     362           0 :                 err = _("grouping operations are not allowed in JOIN conditions");
     363             : 
     364           0 :             break;
     365          16 :         case EXPR_KIND_FROM_SUBSELECT:
     366             :             /* Should only be possible in a LATERAL subquery */
     367             :             Assert(pstate->p_lateral_active);
     368             : 
     369             :             /*
     370             :              * Aggregate/grouping scope rules make it worth being explicit
     371             :              * here
     372             :              */
     373          16 :             if (isAgg)
     374          16 :                 err = _("aggregate functions are not allowed in FROM clause of their own query level");
     375             :             else
     376           0 :                 err = _("grouping operations are not allowed in FROM clause of their own query level");
     377             : 
     378          16 :             break;
     379           0 :         case EXPR_KIND_FROM_FUNCTION:
     380           0 :             if (isAgg)
     381           0 :                 err = _("aggregate functions are not allowed in functions in FROM");
     382             :             else
     383           0 :                 err = _("grouping operations are not allowed in functions in FROM");
     384             : 
     385           0 :             break;
     386           4 :         case EXPR_KIND_WHERE:
     387           4 :             errkind = true;
     388           4 :             break;
     389           4 :         case EXPR_KIND_POLICY:
     390           4 :             if (isAgg)
     391           4 :                 err = _("aggregate functions are not allowed in policy expressions");
     392             :             else
     393           0 :                 err = _("grouping operations are not allowed in policy expressions");
     394             : 
     395           4 :             break;
     396         382 :         case EXPR_KIND_HAVING:
     397             :             /* okay */
     398         382 :             break;
     399           8 :         case EXPR_KIND_FILTER:
     400           8 :             errkind = true;
     401           8 :             break;
     402           0 :         case EXPR_KIND_WINDOW_PARTITION:
     403             :             /* okay */
     404           0 :             break;
     405           8 :         case EXPR_KIND_WINDOW_ORDER:
     406             :             /* okay */
     407           8 :             break;
     408           0 :         case EXPR_KIND_WINDOW_FRAME_RANGE:
     409           0 :             if (isAgg)
     410           0 :                 err = _("aggregate functions are not allowed in window RANGE");
     411             :             else
     412           0 :                 err = _("grouping operations are not allowed in window RANGE");
     413             : 
     414           0 :             break;
     415           0 :         case EXPR_KIND_WINDOW_FRAME_ROWS:
     416           0 :             if (isAgg)
     417           0 :                 err = _("aggregate functions are not allowed in window ROWS");
     418             :             else
     419           0 :                 err = _("grouping operations are not allowed in window ROWS");
     420             : 
     421           0 :             break;
     422           0 :         case EXPR_KIND_WINDOW_FRAME_GROUPS:
     423           0 :             if (isAgg)
     424           0 :                 err = _("aggregate functions are not allowed in window GROUPS");
     425             :             else
     426           0 :                 err = _("grouping operations are not allowed in window GROUPS");
     427             : 
     428           0 :             break;
     429       58464 :         case EXPR_KIND_SELECT_TARGET:
     430             :             /* okay */
     431       58464 :             break;
     432           0 :         case EXPR_KIND_INSERT_TARGET:
     433             :         case EXPR_KIND_UPDATE_SOURCE:
     434             :         case EXPR_KIND_UPDATE_TARGET:
     435           0 :             errkind = true;
     436           0 :             break;
     437           0 :         case EXPR_KIND_GROUP_BY:
     438           0 :             errkind = true;
     439           0 :             break;
     440          56 :         case EXPR_KIND_ORDER_BY:
     441             :             /* okay */
     442          56 :             break;
     443           0 :         case EXPR_KIND_DISTINCT_ON:
     444             :             /* okay */
     445           0 :             break;
     446           0 :         case EXPR_KIND_LIMIT:
     447             :         case EXPR_KIND_OFFSET:
     448           0 :             errkind = true;
     449           0 :             break;
     450           0 :         case EXPR_KIND_RETURNING:
     451           0 :             errkind = true;
     452           0 :             break;
     453           0 :         case EXPR_KIND_VALUES:
     454             :         case EXPR_KIND_VALUES_SINGLE:
     455           0 :             errkind = true;
     456           0 :             break;
     457           0 :         case EXPR_KIND_CHECK_CONSTRAINT:
     458             :         case EXPR_KIND_DOMAIN_CHECK:
     459           0 :             if (isAgg)
     460           0 :                 err = _("aggregate functions are not allowed in check constraints");
     461             :             else
     462           0 :                 err = _("grouping operations are not allowed in check constraints");
     463             : 
     464           0 :             break;
     465           4 :         case EXPR_KIND_COLUMN_DEFAULT:
     466             :         case EXPR_KIND_FUNCTION_DEFAULT:
     467             : 
     468           4 :             if (isAgg)
     469           4 :                 err = _("aggregate functions are not allowed in DEFAULT expressions");
     470             :             else
     471           0 :                 err = _("grouping operations are not allowed in DEFAULT expressions");
     472             : 
     473           4 :             break;
     474           0 :         case EXPR_KIND_INDEX_EXPRESSION:
     475           0 :             if (isAgg)
     476           0 :                 err = _("aggregate functions are not allowed in index expressions");
     477             :             else
     478           0 :                 err = _("grouping operations are not allowed in index expressions");
     479             : 
     480           0 :             break;
     481           0 :         case EXPR_KIND_INDEX_PREDICATE:
     482           0 :             if (isAgg)
     483           0 :                 err = _("aggregate functions are not allowed in index predicates");
     484             :             else
     485           0 :                 err = _("grouping operations are not allowed in index predicates");
     486             : 
     487           0 :             break;
     488           0 :         case EXPR_KIND_STATS_EXPRESSION:
     489           0 :             if (isAgg)
     490           0 :                 err = _("aggregate functions are not allowed in statistics expressions");
     491             :             else
     492           0 :                 err = _("grouping operations are not allowed in statistics expressions");
     493             : 
     494           0 :             break;
     495           0 :         case EXPR_KIND_ALTER_COL_TRANSFORM:
     496           0 :             if (isAgg)
     497           0 :                 err = _("aggregate functions are not allowed in transform expressions");
     498             :             else
     499           0 :                 err = _("grouping operations are not allowed in transform expressions");
     500             : 
     501           0 :             break;
     502           0 :         case EXPR_KIND_EXECUTE_PARAMETER:
     503           0 :             if (isAgg)
     504           0 :                 err = _("aggregate functions are not allowed in EXECUTE parameters");
     505             :             else
     506           0 :                 err = _("grouping operations are not allowed in EXECUTE parameters");
     507             : 
     508           0 :             break;
     509           0 :         case EXPR_KIND_TRIGGER_WHEN:
     510           0 :             if (isAgg)
     511           0 :                 err = _("aggregate functions are not allowed in trigger WHEN conditions");
     512             :             else
     513           0 :                 err = _("grouping operations are not allowed in trigger WHEN conditions");
     514             : 
     515           0 :             break;
     516           8 :         case EXPR_KIND_PARTITION_BOUND:
     517           8 :             if (isAgg)
     518           8 :                 err = _("aggregate functions are not allowed in partition bound");
     519             :             else
     520           0 :                 err = _("grouping operations are not allowed in partition bound");
     521             : 
     522           8 :             break;
     523           4 :         case EXPR_KIND_PARTITION_EXPRESSION:
     524           4 :             if (isAgg)
     525           4 :                 err = _("aggregate functions are not allowed in partition key expressions");
     526             :             else
     527           0 :                 err = _("grouping operations are not allowed in partition key expressions");
     528             : 
     529           4 :             break;
     530           4 :         case EXPR_KIND_GENERATED_COLUMN:
     531             : 
     532           4 :             if (isAgg)
     533           4 :                 err = _("aggregate functions are not allowed in column generation expressions");
     534             :             else
     535           0 :                 err = _("grouping operations are not allowed in column generation expressions");
     536             : 
     537           4 :             break;
     538             : 
     539           0 :         case EXPR_KIND_CALL_ARGUMENT:
     540           0 :             if (isAgg)
     541           0 :                 err = _("aggregate functions are not allowed in CALL arguments");
     542             :             else
     543           0 :                 err = _("grouping operations are not allowed in CALL arguments");
     544             : 
     545           0 :             break;
     546             : 
     547           4 :         case EXPR_KIND_COPY_WHERE:
     548           4 :             if (isAgg)
     549           4 :                 err = _("aggregate functions are not allowed in COPY FROM WHERE conditions");
     550             :             else
     551           0 :                 err = _("grouping operations are not allowed in COPY FROM WHERE conditions");
     552             : 
     553           4 :             break;
     554             : 
     555           0 :         case EXPR_KIND_CYCLE_MARK:
     556           0 :             errkind = true;
     557           0 :             break;
     558             : 
     559             :             /*
     560             :              * There is intentionally no default: case here, so that the
     561             :              * compiler will warn if we add a new ParseExprKind without
     562             :              * extending this switch.  If we do see an unrecognized value at
     563             :              * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
     564             :              * which is sane anyway.
     565             :              */
     566             :     }
     567             : 
     568       58966 :     if (err)
     569          44 :         ereport(ERROR,
     570             :                 (errcode(ERRCODE_GROUPING_ERROR),
     571             :                  errmsg_internal("%s", err),
     572             :                  parser_errposition(pstate, location)));
     573             : 
     574       58922 :     if (errkind)
     575             :     {
     576          12 :         if (isAgg)
     577             :             /* translator: %s is name of a SQL construct, eg GROUP BY */
     578          12 :             err = _("aggregate functions are not allowed in %s");
     579             :         else
     580             :             /* translator: %s is name of a SQL construct, eg GROUP BY */
     581           0 :             err = _("grouping operations are not allowed in %s");
     582             : 
     583          12 :         ereport(ERROR,
     584             :                 (errcode(ERRCODE_GROUPING_ERROR),
     585             :                  errmsg_internal(err,
     586             :                                  ParseExprKindName(pstate->p_expr_kind)),
     587             :                  parser_errposition(pstate, location)));
     588             :     }
     589       58910 : }
     590             : 
     591             : /*
     592             :  * check_agg_arguments
     593             :  *    Scan the arguments of an aggregate function to determine the
     594             :  *    aggregate's semantic level (zero is the current select's level,
     595             :  *    one is its parent, etc).
     596             :  *
     597             :  * The aggregate's level is the same as the level of the lowest-level variable
     598             :  * or aggregate in its aggregated arguments (including any ORDER BY columns)
     599             :  * or filter expression; or if it contains no variables at all, we presume it
     600             :  * to be local.
     601             :  *
     602             :  * Vars/Aggs in direct arguments are *not* counted towards determining the
     603             :  * agg's level, as those arguments aren't evaluated per-row but only
     604             :  * per-group, and so in some sense aren't really agg arguments.  However,
     605             :  * this can mean that we decide an agg is upper-level even when its direct
     606             :  * args contain lower-level Vars/Aggs, and that case has to be disallowed.
     607             :  * (This is a little strange, but the SQL standard seems pretty definite that
     608             :  * direct args are not to be considered when setting the agg's level.)
     609             :  *
     610             :  * We also take this opportunity to detect any aggregates or window functions
     611             :  * nested within the arguments.  We can throw error immediately if we find
     612             :  * a window function.  Aggregates are a bit trickier because it's only an
     613             :  * error if the inner aggregate is of the same semantic level as the outer,
     614             :  * which we can't know until we finish scanning the arguments.
     615             :  */
     616             : static int
     617       58994 : check_agg_arguments(ParseState *pstate,
     618             :                     List *directargs,
     619             :                     List *args,
     620             :                     Expr *filter)
     621             : {
     622             :     int         agglevel;
     623             :     check_agg_arguments_context context;
     624             : 
     625       58994 :     context.pstate = pstate;
     626       58994 :     context.min_varlevel = -1;  /* signifies nothing found yet */
     627       58994 :     context.min_agglevel = -1;
     628       58994 :     context.sublevels_up = 0;
     629             : 
     630       58994 :     (void) check_agg_arguments_walker((Node *) args, &context);
     631       58990 :     (void) check_agg_arguments_walker((Node *) filter, &context);
     632             : 
     633             :     /*
     634             :      * If we found no vars nor aggs at all, it's a level-zero aggregate;
     635             :      * otherwise, its level is the minimum of vars or aggs.
     636             :      */
     637       58990 :     if (context.min_varlevel < 0)
     638             :     {
     639        8166 :         if (context.min_agglevel < 0)
     640        8158 :             agglevel = 0;
     641             :         else
     642           8 :             agglevel = context.min_agglevel;
     643             :     }
     644       50824 :     else if (context.min_agglevel < 0)
     645       50816 :         agglevel = context.min_varlevel;
     646             :     else
     647           8 :         agglevel = Min(context.min_varlevel, context.min_agglevel);
     648             : 
     649             :     /*
     650             :      * If there's a nested aggregate of the same semantic level, complain.
     651             :      */
     652       58990 :     if (agglevel == context.min_agglevel)
     653             :     {
     654             :         int         aggloc;
     655             : 
     656          16 :         aggloc = locate_agg_of_level((Node *) args, agglevel);
     657          16 :         if (aggloc < 0)
     658           8 :             aggloc = locate_agg_of_level((Node *) filter, agglevel);
     659          16 :         ereport(ERROR,
     660             :                 (errcode(ERRCODE_GROUPING_ERROR),
     661             :                  errmsg("aggregate function calls cannot be nested"),
     662             :                  parser_errposition(pstate, aggloc)));
     663             :     }
     664             : 
     665             :     /*
     666             :      * Now check for vars/aggs in the direct arguments, and throw error if
     667             :      * needed.  Note that we allow a Var of the agg's semantic level, but not
     668             :      * an Agg of that level.  In principle such Aggs could probably be
     669             :      * supported, but it would create an ordering dependency among the
     670             :      * aggregates at execution time.  Since the case appears neither to be
     671             :      * required by spec nor particularly useful, we just treat it as a
     672             :      * nested-aggregate situation.
     673             :      */
     674       58974 :     if (directargs)
     675             :     {
     676         216 :         context.min_varlevel = -1;
     677         216 :         context.min_agglevel = -1;
     678         216 :         (void) check_agg_arguments_walker((Node *) directargs, &context);
     679         216 :         if (context.min_varlevel >= 0 && context.min_varlevel < agglevel)
     680           4 :             ereport(ERROR,
     681             :                     (errcode(ERRCODE_GROUPING_ERROR),
     682             :                      errmsg("outer-level aggregate cannot contain a lower-level variable in its direct arguments"),
     683             :                      parser_errposition(pstate,
     684             :                                         locate_var_of_level((Node *) directargs,
     685             :                                                             context.min_varlevel))));
     686         212 :         if (context.min_agglevel >= 0 && context.min_agglevel <= agglevel)
     687           4 :             ereport(ERROR,
     688             :                     (errcode(ERRCODE_GROUPING_ERROR),
     689             :                      errmsg("aggregate function calls cannot be nested"),
     690             :                      parser_errposition(pstate,
     691             :                                         locate_agg_of_level((Node *) directargs,
     692             :                                                             context.min_agglevel))));
     693             :     }
     694       58966 :     return agglevel;
     695             : }
     696             : 
     697             : static bool
     698      273710 : check_agg_arguments_walker(Node *node,
     699             :                            check_agg_arguments_context *context)
     700             : {
     701      273710 :     if (node == NULL)
     702       66614 :         return false;
     703      207096 :     if (IsA(node, Var))
     704             :     {
     705       72064 :         int         varlevelsup = ((Var *) node)->varlevelsup;
     706             : 
     707             :         /* convert levelsup to frame of reference of original query */
     708       72064 :         varlevelsup -= context->sublevels_up;
     709             :         /* ignore local vars of subqueries */
     710       72064 :         if (varlevelsup >= 0)
     711             :         {
     712       72020 :             if (context->min_varlevel < 0 ||
     713       21154 :                 context->min_varlevel > varlevelsup)
     714       50886 :                 context->min_varlevel = varlevelsup;
     715             :         }
     716       72064 :         return false;
     717             :     }
     718      135032 :     if (IsA(node, Aggref))
     719             :     {
     720          20 :         int         agglevelsup = ((Aggref *) node)->agglevelsup;
     721             : 
     722             :         /* convert levelsup to frame of reference of original query */
     723          20 :         agglevelsup -= context->sublevels_up;
     724             :         /* ignore local aggs of subqueries */
     725          20 :         if (agglevelsup >= 0)
     726             :         {
     727          20 :             if (context->min_agglevel < 0 ||
     728           0 :                 context->min_agglevel > agglevelsup)
     729          20 :                 context->min_agglevel = agglevelsup;
     730             :         }
     731             :         /* no need to examine args of the inner aggregate */
     732          20 :         return false;
     733             :     }
     734      135012 :     if (IsA(node, GroupingFunc))
     735             :     {
     736           0 :         int         agglevelsup = ((GroupingFunc *) node)->agglevelsup;
     737             : 
     738             :         /* convert levelsup to frame of reference of original query */
     739           0 :         agglevelsup -= context->sublevels_up;
     740             :         /* ignore local aggs of subqueries */
     741           0 :         if (agglevelsup >= 0)
     742             :         {
     743           0 :             if (context->min_agglevel < 0 ||
     744           0 :                 context->min_agglevel > agglevelsup)
     745           0 :                 context->min_agglevel = agglevelsup;
     746             :         }
     747             :         /* Continue and descend into subtree */
     748             :     }
     749             : 
     750             :     /*
     751             :      * SRFs and window functions can be rejected immediately, unless we are
     752             :      * within a sub-select within the aggregate's arguments; in that case
     753             :      * they're OK.
     754             :      */
     755      135012 :     if (context->sublevels_up == 0)
     756             :     {
     757      134810 :         if ((IsA(node, FuncExpr) && ((FuncExpr *) node)->funcretset) ||
     758      134806 :             (IsA(node, OpExpr) && ((OpExpr *) node)->opretset))
     759           4 :             ereport(ERROR,
     760             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     761             :                      errmsg("aggregate function calls cannot contain set-returning function calls"),
     762             :                      errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
     763             :                      parser_errposition(context->pstate, exprLocation(node))));
     764      134806 :         if (IsA(node, WindowFunc))
     765           0 :             ereport(ERROR,
     766             :                     (errcode(ERRCODE_GROUPING_ERROR),
     767             :                      errmsg("aggregate function calls cannot contain window function calls"),
     768             :                      parser_errposition(context->pstate,
     769             :                                         ((WindowFunc *) node)->location)));
     770             :     }
     771      135008 :     if (IsA(node, Query))
     772             :     {
     773             :         /* Recurse into subselects */
     774             :         bool        result;
     775             : 
     776          30 :         context->sublevels_up++;
     777          30 :         result = query_tree_walker((Query *) node,
     778             :                                    check_agg_arguments_walker,
     779             :                                    (void *) context,
     780             :                                    0);
     781          30 :         context->sublevels_up--;
     782          30 :         return result;
     783             :     }
     784             : 
     785      134978 :     return expression_tree_walker(node,
     786             :                                   check_agg_arguments_walker,
     787             :                                   (void *) context);
     788             : }
     789             : 
     790             : /*
     791             :  * transformWindowFuncCall -
     792             :  *      Finish initial transformation of a window function call
     793             :  *
     794             :  * parse_func.c has recognized the function as a window function, and has set
     795             :  * up all the fields of the WindowFunc except winref.  Here we must (1) add
     796             :  * the WindowDef to the pstate (if not a duplicate of one already present) and
     797             :  * set winref to link to it; and (2) mark p_hasWindowFuncs true in the pstate.
     798             :  * Unlike aggregates, only the most closely nested pstate level need be
     799             :  * considered --- there are no "outer window functions" per SQL spec.
     800             :  */
     801             : void
     802        2098 : transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
     803             :                         WindowDef *windef)
     804             : {
     805             :     const char *err;
     806             :     bool        errkind;
     807             : 
     808             :     /*
     809             :      * A window function call can't contain another one (but aggs are OK). XXX
     810             :      * is this required by spec, or just an unimplemented feature?
     811             :      *
     812             :      * Note: we don't need to check the filter expression here, because the
     813             :      * context checks done below and in transformAggregateCall would have
     814             :      * already rejected any window funcs or aggs within the filter.
     815             :      */
     816        2446 :     if (pstate->p_hasWindowFuncs &&
     817         348 :         contain_windowfuncs((Node *) wfunc->args))
     818           0 :         ereport(ERROR,
     819             :                 (errcode(ERRCODE_WINDOWING_ERROR),
     820             :                  errmsg("window function calls cannot be nested"),
     821             :                  parser_errposition(pstate,
     822             :                                     locate_windowfunc((Node *) wfunc->args))));
     823             : 
     824             :     /*
     825             :      * Check to see if the window function is in an invalid place within the
     826             :      * query.
     827             :      *
     828             :      * For brevity we support two schemes for reporting an error here: set
     829             :      * "err" to a custom message, or set "errkind" true if the error context
     830             :      * is sufficiently identified by what ParseExprKindName will return, *and*
     831             :      * what it will return is just a SQL keyword.  (Otherwise, use a custom
     832             :      * message to avoid creating translation problems.)
     833             :      */
     834        2098 :     err = NULL;
     835        2098 :     errkind = false;
     836        2098 :     switch (pstate->p_expr_kind)
     837             :     {
     838           0 :         case EXPR_KIND_NONE:
     839             :             Assert(false);      /* can't happen */
     840           0 :             break;
     841           0 :         case EXPR_KIND_OTHER:
     842             :             /* Accept window func here; caller must throw error if wanted */
     843           0 :             break;
     844           4 :         case EXPR_KIND_JOIN_ON:
     845             :         case EXPR_KIND_JOIN_USING:
     846           4 :             err = _("window functions are not allowed in JOIN conditions");
     847           4 :             break;
     848           0 :         case EXPR_KIND_FROM_SUBSELECT:
     849             :             /* can't get here, but just in case, throw an error */
     850           0 :             errkind = true;
     851           0 :             break;
     852           0 :         case EXPR_KIND_FROM_FUNCTION:
     853           0 :             err = _("window functions are not allowed in functions in FROM");
     854           0 :             break;
     855           8 :         case EXPR_KIND_WHERE:
     856           8 :             errkind = true;
     857           8 :             break;
     858           0 :         case EXPR_KIND_POLICY:
     859           0 :             err = _("window functions are not allowed in policy expressions");
     860           0 :             break;
     861           0 :         case EXPR_KIND_HAVING:
     862           0 :             errkind = true;
     863           0 :             break;
     864           0 :         case EXPR_KIND_FILTER:
     865           0 :             errkind = true;
     866           0 :             break;
     867           4 :         case EXPR_KIND_WINDOW_PARTITION:
     868             :         case EXPR_KIND_WINDOW_ORDER:
     869             :         case EXPR_KIND_WINDOW_FRAME_RANGE:
     870             :         case EXPR_KIND_WINDOW_FRAME_ROWS:
     871             :         case EXPR_KIND_WINDOW_FRAME_GROUPS:
     872           4 :             err = _("window functions are not allowed in window definitions");
     873           4 :             break;
     874        2062 :         case EXPR_KIND_SELECT_TARGET:
     875             :             /* okay */
     876        2062 :             break;
     877           0 :         case EXPR_KIND_INSERT_TARGET:
     878             :         case EXPR_KIND_UPDATE_SOURCE:
     879             :         case EXPR_KIND_UPDATE_TARGET:
     880           0 :             errkind = true;
     881           0 :             break;
     882           0 :         case EXPR_KIND_GROUP_BY:
     883           0 :             errkind = true;
     884           0 :             break;
     885           4 :         case EXPR_KIND_ORDER_BY:
     886             :             /* okay */
     887           4 :             break;
     888           0 :         case EXPR_KIND_DISTINCT_ON:
     889             :             /* okay */
     890           0 :             break;
     891           0 :         case EXPR_KIND_LIMIT:
     892             :         case EXPR_KIND_OFFSET:
     893           0 :             errkind = true;
     894           0 :             break;
     895           4 :         case EXPR_KIND_RETURNING:
     896           4 :             errkind = true;
     897           4 :             break;
     898           0 :         case EXPR_KIND_VALUES:
     899             :         case EXPR_KIND_VALUES_SINGLE:
     900           0 :             errkind = true;
     901           0 :             break;
     902           0 :         case EXPR_KIND_CHECK_CONSTRAINT:
     903             :         case EXPR_KIND_DOMAIN_CHECK:
     904           0 :             err = _("window functions are not allowed in check constraints");
     905           0 :             break;
     906           0 :         case EXPR_KIND_COLUMN_DEFAULT:
     907             :         case EXPR_KIND_FUNCTION_DEFAULT:
     908           0 :             err = _("window functions are not allowed in DEFAULT expressions");
     909           0 :             break;
     910           0 :         case EXPR_KIND_INDEX_EXPRESSION:
     911           0 :             err = _("window functions are not allowed in index expressions");
     912           0 :             break;
     913           0 :         case EXPR_KIND_STATS_EXPRESSION:
     914           0 :             err = _("window functions are not allowed in statistics expressions");
     915           0 :             break;
     916           0 :         case EXPR_KIND_INDEX_PREDICATE:
     917           0 :             err = _("window functions are not allowed in index predicates");
     918           0 :             break;
     919           0 :         case EXPR_KIND_ALTER_COL_TRANSFORM:
     920           0 :             err = _("window functions are not allowed in transform expressions");
     921           0 :             break;
     922           0 :         case EXPR_KIND_EXECUTE_PARAMETER:
     923           0 :             err = _("window functions are not allowed in EXECUTE parameters");
     924           0 :             break;
     925           0 :         case EXPR_KIND_TRIGGER_WHEN:
     926           0 :             err = _("window functions are not allowed in trigger WHEN conditions");
     927           0 :             break;
     928           0 :         case EXPR_KIND_PARTITION_BOUND:
     929           0 :             err = _("window functions are not allowed in partition bound");
     930           0 :             break;
     931           4 :         case EXPR_KIND_PARTITION_EXPRESSION:
     932           4 :             err = _("window functions are not allowed in partition key expressions");
     933           4 :             break;
     934           0 :         case EXPR_KIND_CALL_ARGUMENT:
     935           0 :             err = _("window functions are not allowed in CALL arguments");
     936           0 :             break;
     937           4 :         case EXPR_KIND_COPY_WHERE:
     938           4 :             err = _("window functions are not allowed in COPY FROM WHERE conditions");
     939           4 :             break;
     940           4 :         case EXPR_KIND_GENERATED_COLUMN:
     941           4 :             err = _("window functions are not allowed in column generation expressions");
     942           4 :             break;
     943           0 :         case EXPR_KIND_CYCLE_MARK:
     944           0 :             errkind = true;
     945           0 :             break;
     946             : 
     947             :             /*
     948             :              * There is intentionally no default: case here, so that the
     949             :              * compiler will warn if we add a new ParseExprKind without
     950             :              * extending this switch.  If we do see an unrecognized value at
     951             :              * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
     952             :              * which is sane anyway.
     953             :              */
     954             :     }
     955        2098 :     if (err)
     956          20 :         ereport(ERROR,
     957             :                 (errcode(ERRCODE_WINDOWING_ERROR),
     958             :                  errmsg_internal("%s", err),
     959             :                  parser_errposition(pstate, wfunc->location)));
     960        2078 :     if (errkind)
     961          12 :         ereport(ERROR,
     962             :                 (errcode(ERRCODE_WINDOWING_ERROR),
     963             :         /* translator: %s is name of a SQL construct, eg GROUP BY */
     964             :                  errmsg("window functions are not allowed in %s",
     965             :                         ParseExprKindName(pstate->p_expr_kind)),
     966             :                  parser_errposition(pstate, wfunc->location)));
     967             : 
     968             :     /*
     969             :      * If the OVER clause just specifies a window name, find that WINDOW
     970             :      * clause (which had better be present).  Otherwise, try to match all the
     971             :      * properties of the OVER clause, and make a new entry in the p_windowdefs
     972             :      * list if no luck.
     973             :      */
     974        2066 :     if (windef->name)
     975             :     {
     976         428 :         Index       winref = 0;
     977             :         ListCell   *lc;
     978             : 
     979             :         Assert(windef->refname == NULL &&
     980             :                windef->partitionClause == NIL &&
     981             :                windef->orderClause == NIL &&
     982             :                windef->frameOptions == FRAMEOPTION_DEFAULTS);
     983             : 
     984         432 :         foreach(lc, pstate->p_windowdefs)
     985             :         {
     986         432 :             WindowDef  *refwin = (WindowDef *) lfirst(lc);
     987             : 
     988         432 :             winref++;
     989         432 :             if (refwin->name && strcmp(refwin->name, windef->name) == 0)
     990             :             {
     991         428 :                 wfunc->winref = winref;
     992         428 :                 break;
     993             :             }
     994             :         }
     995         428 :         if (lc == NULL)         /* didn't find it? */
     996           0 :             ereport(ERROR,
     997             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
     998             :                      errmsg("window \"%s\" does not exist", windef->name),
     999             :                      parser_errposition(pstate, windef->location)));
    1000             :     }
    1001             :     else
    1002             :     {
    1003        1638 :         Index       winref = 0;
    1004             :         ListCell   *lc;
    1005             : 
    1006        1718 :         foreach(lc, pstate->p_windowdefs)
    1007             :         {
    1008         176 :             WindowDef  *refwin = (WindowDef *) lfirst(lc);
    1009             : 
    1010         176 :             winref++;
    1011         176 :             if (refwin->refname && windef->refname &&
    1012           0 :                 strcmp(refwin->refname, windef->refname) == 0)
    1013             :                  /* matched on refname */ ;
    1014         176 :             else if (!refwin->refname && !windef->refname)
    1015             :                  /* matched, no refname */ ;
    1016             :             else
    1017          16 :                 continue;
    1018         300 :             if (equal(refwin->partitionClause, windef->partitionClause) &&
    1019         140 :                 equal(refwin->orderClause, windef->orderClause) &&
    1020         212 :                 refwin->frameOptions == windef->frameOptions &&
    1021         192 :                 equal(refwin->startOffset, windef->startOffset) &&
    1022          96 :                 equal(refwin->endOffset, windef->endOffset))
    1023             :             {
    1024             :                 /* found a duplicate window specification */
    1025          96 :                 wfunc->winref = winref;
    1026          96 :                 break;
    1027             :             }
    1028             :         }
    1029        1638 :         if (lc == NULL)         /* didn't find it? */
    1030             :         {
    1031        1542 :             pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
    1032        1542 :             wfunc->winref = list_length(pstate->p_windowdefs);
    1033             :         }
    1034             :     }
    1035             : 
    1036        2066 :     pstate->p_hasWindowFuncs = true;
    1037        2066 : }
    1038             : 
    1039             : /*
    1040             :  * parseCheckAggregates
    1041             :  *  Check for aggregates where they shouldn't be and improper grouping.
    1042             :  *  This function should be called after the target list and qualifications
    1043             :  *  are finalized.
    1044             :  *
    1045             :  *  Misplaced aggregates are now mostly detected in transformAggregateCall,
    1046             :  *  but it seems more robust to check for aggregates in recursive queries
    1047             :  *  only after everything is finalized.  In any case it's hard to detect
    1048             :  *  improper grouping on-the-fly, so we have to make another pass over the
    1049             :  *  query for that.
    1050             :  */
    1051             : void
    1052       53526 : parseCheckAggregates(ParseState *pstate, Query *qry)
    1053             : {
    1054       53526 :     List       *gset_common = NIL;
    1055       53526 :     List       *groupClauses = NIL;
    1056       53526 :     List       *groupClauseCommonVars = NIL;
    1057             :     bool        have_non_var_grouping;
    1058       53526 :     List       *func_grouped_rels = NIL;
    1059             :     ListCell   *l;
    1060             :     bool        hasJoinRTEs;
    1061             :     bool        hasSelfRefRTEs;
    1062             :     Node       *clause;
    1063             : 
    1064             :     /* This should only be called if we found aggregates or grouping */
    1065             :     Assert(pstate->p_hasAggs || qry->groupClause || qry->havingQual || qry->groupingSets);
    1066             : 
    1067             :     /*
    1068             :      * If we have grouping sets, expand them and find the intersection of all
    1069             :      * sets.
    1070             :      */
    1071       53526 :     if (qry->groupingSets)
    1072             :     {
    1073             :         /*
    1074             :          * The limit of 4096 is arbitrary and exists simply to avoid resource
    1075             :          * issues from pathological constructs.
    1076             :          */
    1077         508 :         List       *gsets = expand_grouping_sets(qry->groupingSets, qry->groupDistinct, 4096);
    1078             : 
    1079         508 :         if (!gsets)
    1080           0 :             ereport(ERROR,
    1081             :                     (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
    1082             :                      errmsg("too many grouping sets present (maximum 4096)"),
    1083             :                      parser_errposition(pstate,
    1084             :                                         qry->groupClause
    1085             :                                         ? exprLocation((Node *) qry->groupClause)
    1086             :                                         : exprLocation((Node *) qry->groupingSets))));
    1087             : 
    1088             :         /*
    1089             :          * The intersection will often be empty, so help things along by
    1090             :          * seeding the intersect with the smallest set.
    1091             :          */
    1092         508 :         gset_common = linitial(gsets);
    1093             : 
    1094         508 :         if (gset_common)
    1095             :         {
    1096         292 :             for_each_from(l, gsets, 1)
    1097             :             {
    1098         200 :                 gset_common = list_intersection_int(gset_common, lfirst(l));
    1099         200 :                 if (!gset_common)
    1100          92 :                     break;
    1101             :             }
    1102             :         }
    1103             : 
    1104             :         /*
    1105             :          * If there was only one grouping set in the expansion, AND if the
    1106             :          * groupClause is non-empty (meaning that the grouping set is not
    1107             :          * empty either), then we can ditch the grouping set and pretend we
    1108             :          * just had a normal GROUP BY.
    1109             :          */
    1110         508 :         if (list_length(gsets) == 1 && qry->groupClause)
    1111          16 :             qry->groupingSets = NIL;
    1112             :     }
    1113             : 
    1114             :     /*
    1115             :      * Scan the range table to see if there are JOIN or self-reference CTE
    1116             :      * entries.  We'll need this info below.
    1117             :      */
    1118       53526 :     hasJoinRTEs = hasSelfRefRTEs = false;
    1119      117414 :     foreach(l, pstate->p_rtable)
    1120             :     {
    1121       63888 :         RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
    1122             : 
    1123       63888 :         if (rte->rtekind == RTE_JOIN)
    1124        5092 :             hasJoinRTEs = true;
    1125       58796 :         else if (rte->rtekind == RTE_CTE && rte->self_reference)
    1126           8 :             hasSelfRefRTEs = true;
    1127             :     }
    1128             : 
    1129             :     /*
    1130             :      * Build a list of the acceptable GROUP BY expressions for use by
    1131             :      * check_ungrouped_columns().
    1132             :      *
    1133             :      * We get the TLE, not just the expr, because GROUPING wants to know the
    1134             :      * sortgroupref.
    1135             :      */
    1136       63058 :     foreach(l, qry->groupClause)
    1137             :     {
    1138        9532 :         SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
    1139             :         TargetEntry *expr;
    1140             : 
    1141        9532 :         expr = get_sortgroupclause_tle(grpcl, qry->targetList);
    1142        9532 :         if (expr == NULL)
    1143           0 :             continue;           /* probably cannot happen */
    1144             : 
    1145        9532 :         groupClauses = lappend(groupClauses, expr);
    1146             :     }
    1147             : 
    1148             :     /*
    1149             :      * If there are join alias vars involved, we have to flatten them to the
    1150             :      * underlying vars, so that aliased and unaliased vars will be correctly
    1151             :      * taken as equal.  We can skip the expense of doing this if no rangetable
    1152             :      * entries are RTE_JOIN kind.
    1153             :      */
    1154       53526 :     if (hasJoinRTEs)
    1155        2602 :         groupClauses = (List *) flatten_join_alias_vars(qry,
    1156             :                                                         (Node *) groupClauses);
    1157             : 
    1158             :     /*
    1159             :      * Detect whether any of the grouping expressions aren't simple Vars; if
    1160             :      * they're all Vars then we don't have to work so hard in the recursive
    1161             :      * scans.  (Note we have to flatten aliases before this.)
    1162             :      *
    1163             :      * Track Vars that are included in all grouping sets separately in
    1164             :      * groupClauseCommonVars, since these are the only ones we can use to
    1165             :      * check for functional dependencies.
    1166             :      */
    1167       53526 :     have_non_var_grouping = false;
    1168       63058 :     foreach(l, groupClauses)
    1169             :     {
    1170        9532 :         TargetEntry *tle = lfirst(l);
    1171             : 
    1172        9532 :         if (!IsA(tle->expr, Var))
    1173             :         {
    1174         840 :             have_non_var_grouping = true;
    1175             :         }
    1176        9648 :         else if (!qry->groupingSets ||
    1177         956 :                  list_member_int(gset_common, tle->ressortgroupref))
    1178             :         {
    1179        7812 :             groupClauseCommonVars = lappend(groupClauseCommonVars, tle->expr);
    1180             :         }
    1181             :     }
    1182             : 
    1183             :     /*
    1184             :      * Check the targetlist and HAVING clause for ungrouped variables.
    1185             :      *
    1186             :      * Note: because we check resjunk tlist elements as well as regular ones,
    1187             :      * this will also find ungrouped variables that came from ORDER BY and
    1188             :      * WINDOW clauses.  For that matter, it's also going to examine the
    1189             :      * grouping expressions themselves --- but they'll all pass the test ...
    1190             :      *
    1191             :      * We also finalize GROUPING expressions, but for that we need to traverse
    1192             :      * the original (unflattened) clause in order to modify nodes.
    1193             :      */
    1194       53526 :     clause = (Node *) qry->targetList;
    1195       53526 :     finalize_grouping_exprs(clause, pstate, qry,
    1196             :                             groupClauses, hasJoinRTEs,
    1197             :                             have_non_var_grouping);
    1198       53522 :     if (hasJoinRTEs)
    1199        2602 :         clause = flatten_join_alias_vars(qry, clause);
    1200       53522 :     check_ungrouped_columns(clause, pstate, qry,
    1201             :                             groupClauses, groupClauseCommonVars,
    1202             :                             have_non_var_grouping,
    1203             :                             &func_grouped_rels);
    1204             : 
    1205       53466 :     clause = (Node *) qry->havingQual;
    1206       53466 :     finalize_grouping_exprs(clause, pstate, qry,
    1207             :                             groupClauses, hasJoinRTEs,
    1208             :                             have_non_var_grouping);
    1209       53466 :     if (hasJoinRTEs)
    1210        2586 :         clause = flatten_join_alias_vars(qry, clause);
    1211       53466 :     check_ungrouped_columns(clause, pstate, qry,
    1212             :                             groupClauses, groupClauseCommonVars,
    1213             :                             have_non_var_grouping,
    1214             :                             &func_grouped_rels);
    1215             : 
    1216             :     /*
    1217             :      * Per spec, aggregates can't appear in a recursive term.
    1218             :      */
    1219       53462 :     if (pstate->p_hasAggs && hasSelfRefRTEs)
    1220           8 :         ereport(ERROR,
    1221             :                 (errcode(ERRCODE_INVALID_RECURSION),
    1222             :                  errmsg("aggregate functions are not allowed in a recursive query's recursive term"),
    1223             :                  parser_errposition(pstate,
    1224             :                                     locate_agg_of_level((Node *) qry, 0))));
    1225       53454 : }
    1226             : 
    1227             : /*
    1228             :  * check_ungrouped_columns -
    1229             :  *    Scan the given expression tree for ungrouped variables (variables
    1230             :  *    that are not listed in the groupClauses list and are not within
    1231             :  *    the arguments of aggregate functions).  Emit a suitable error message
    1232             :  *    if any are found.
    1233             :  *
    1234             :  * NOTE: we assume that the given clause has been transformed suitably for
    1235             :  * parser output.  This means we can use expression_tree_walker.
    1236             :  *
    1237             :  * NOTE: we recognize grouping expressions in the main query, but only
    1238             :  * grouping Vars in subqueries.  For example, this will be rejected,
    1239             :  * although it could be allowed:
    1240             :  *      SELECT
    1241             :  *          (SELECT x FROM bar where y = (foo.a + foo.b))
    1242             :  *      FROM foo
    1243             :  *      GROUP BY a + b;
    1244             :  * The difficulty is the need to account for different sublevels_up.
    1245             :  * This appears to require a whole custom version of equal(), which is
    1246             :  * way more pain than the feature seems worth.
    1247             :  */
    1248             : static void
    1249      106988 : check_ungrouped_columns(Node *node, ParseState *pstate, Query *qry,
    1250             :                         List *groupClauses, List *groupClauseCommonVars,
    1251             :                         bool have_non_var_grouping,
    1252             :                         List **func_grouped_rels)
    1253             : {
    1254             :     check_ungrouped_columns_context context;
    1255             : 
    1256      106988 :     context.pstate = pstate;
    1257      106988 :     context.qry = qry;
    1258      106988 :     context.hasJoinRTEs = false;    /* assume caller flattened join Vars */
    1259      106988 :     context.groupClauses = groupClauses;
    1260      106988 :     context.groupClauseCommonVars = groupClauseCommonVars;
    1261      106988 :     context.have_non_var_grouping = have_non_var_grouping;
    1262      106988 :     context.func_grouped_rels = func_grouped_rels;
    1263      106988 :     context.sublevels_up = 0;
    1264      106988 :     context.in_agg_direct_args = false;
    1265      106988 :     check_ungrouped_columns_walker(node, &context);
    1266      106928 : }
    1267             : 
    1268             : static bool
    1269      364316 : check_ungrouped_columns_walker(Node *node,
    1270             :                                check_ungrouped_columns_context *context)
    1271             : {
    1272             :     ListCell   *gl;
    1273             : 
    1274      364316 :     if (node == NULL)
    1275      113752 :         return false;
    1276      250564 :     if (IsA(node, Const) ||
    1277      248684 :         IsA(node, Param))
    1278        1920 :         return false;           /* constants are always acceptable */
    1279             : 
    1280      248644 :     if (IsA(node, Aggref))
    1281             :     {
    1282       58616 :         Aggref     *agg = (Aggref *) node;
    1283             : 
    1284       58616 :         if ((int) agg->agglevelsup == context->sublevels_up)
    1285             :         {
    1286             :             /*
    1287             :              * If we find an aggregate call of the original level, do not
    1288             :              * recurse into its normal arguments, ORDER BY arguments, or
    1289             :              * filter; ungrouped vars there are not an error.  But we should
    1290             :              * check direct arguments as though they weren't in an aggregate.
    1291             :              * We set a special flag in the context to help produce a useful
    1292             :              * error message for ungrouped vars in direct arguments.
    1293             :              */
    1294             :             bool        result;
    1295             : 
    1296             :             Assert(!context->in_agg_direct_args);
    1297       58612 :             context->in_agg_direct_args = true;
    1298       58612 :             result = check_ungrouped_columns_walker((Node *) agg->aggdirectargs,
    1299             :                                                     context);
    1300       58608 :             context->in_agg_direct_args = false;
    1301       58608 :             return result;
    1302             :         }
    1303             : 
    1304             :         /*
    1305             :          * We can skip recursing into aggregates of higher levels altogether,
    1306             :          * since they could not possibly contain Vars of concern to us (see
    1307             :          * transformAggregateCall).  We do need to look at aggregates of lower
    1308             :          * levels, however.
    1309             :          */
    1310           4 :         if ((int) agg->agglevelsup > context->sublevels_up)
    1311           0 :             return false;
    1312             :     }
    1313             : 
    1314      190032 :     if (IsA(node, GroupingFunc))
    1315             :     {
    1316         204 :         GroupingFunc *grp = (GroupingFunc *) node;
    1317             : 
    1318             :         /* handled GroupingFunc separately, no need to recheck at this level */
    1319             : 
    1320         204 :         if ((int) grp->agglevelsup >= context->sublevels_up)
    1321         182 :             return false;
    1322             :     }
    1323             : 
    1324             :     /*
    1325             :      * If we have any GROUP BY items that are not simple Vars, check to see if
    1326             :      * subexpression as a whole matches any GROUP BY item. We need to do this
    1327             :      * at every recursion level so that we recognize GROUPed-BY expressions
    1328             :      * before reaching variables within them. But this only works at the outer
    1329             :      * query level, as noted above.
    1330             :      */
    1331      189850 :     if (context->have_non_var_grouping && context->sublevels_up == 0)
    1332             :     {
    1333       11770 :         foreach(gl, context->groupClauses)
    1334             :         {
    1335        8840 :             TargetEntry *tle = lfirst(gl);
    1336             : 
    1337        8840 :             if (equal(node, tle->expr))
    1338        1264 :                 return false;   /* acceptable, do not descend more */
    1339             :         }
    1340             :     }
    1341             : 
    1342             :     /*
    1343             :      * If we have an ungrouped Var of the original query level, we have a
    1344             :      * failure.  Vars below the original query level are not a problem, and
    1345             :      * neither are Vars from above it.  (If such Vars are ungrouped as far as
    1346             :      * their own query level is concerned, that's someone else's problem...)
    1347             :      */
    1348      188586 :     if (IsA(node, Var))
    1349             :     {
    1350       25764 :         Var        *var = (Var *) node;
    1351             :         RangeTblEntry *rte;
    1352             :         char       *attname;
    1353             : 
    1354       25764 :         if (var->varlevelsup != context->sublevels_up)
    1355         232 :             return false;       /* it's not local to my query, ignore */
    1356             : 
    1357             :         /*
    1358             :          * Check for a match, if we didn't do it above.
    1359             :          */
    1360       25532 :         if (!context->have_non_var_grouping || context->sublevels_up != 0)
    1361             :         {
    1362       45210 :             foreach(gl, context->groupClauses)
    1363             :             {
    1364       44986 :                 Var        *gvar = (Var *) ((TargetEntry *) lfirst(gl))->expr;
    1365             : 
    1366       44986 :                 if (IsA(gvar, Var) &&
    1367       44986 :                     gvar->varno == var->varno &&
    1368       28382 :                     gvar->varattno == var->varattno &&
    1369       25304 :                     gvar->varlevelsup == 0)
    1370       25304 :                     return false;   /* acceptable, we're okay */
    1371             :             }
    1372             :         }
    1373             : 
    1374             :         /*
    1375             :          * Check whether the Var is known functionally dependent on the GROUP
    1376             :          * BY columns.  If so, we can allow the Var to be used, because the
    1377             :          * grouping is really a no-op for this table.  However, this deduction
    1378             :          * depends on one or more constraints of the table, so we have to add
    1379             :          * those constraints to the query's constraintDeps list, because it's
    1380             :          * not semantically valid anymore if the constraint(s) get dropped.
    1381             :          * (Therefore, this check must be the last-ditch effort before raising
    1382             :          * error: we don't want to add dependencies unnecessarily.)
    1383             :          *
    1384             :          * Because this is a pretty expensive check, and will have the same
    1385             :          * outcome for all columns of a table, we remember which RTEs we've
    1386             :          * already proven functional dependency for in the func_grouped_rels
    1387             :          * list.  This test also prevents us from adding duplicate entries to
    1388             :          * the constraintDeps list.
    1389             :          */
    1390         228 :         if (list_member_int(*context->func_grouped_rels, var->varno))
    1391          92 :             return false;       /* previously proven acceptable */
    1392             : 
    1393             :         Assert(var->varno > 0 &&
    1394             :                (int) var->varno <= list_length(context->pstate->p_rtable));
    1395         136 :         rte = rt_fetch(var->varno, context->pstate->p_rtable);
    1396         136 :         if (rte->rtekind == RTE_RELATION)
    1397             :         {
    1398         132 :             if (check_functional_grouping(rte->relid,
    1399         132 :                                           var->varno,
    1400             :                                           0,
    1401             :                                           context->groupClauseCommonVars,
    1402         132 :                                           &context->qry->constraintDeps))
    1403             :             {
    1404         152 :                 *context->func_grouped_rels =
    1405          76 :                     lappend_int(*context->func_grouped_rels, var->varno);
    1406          76 :                 return false;   /* acceptable */
    1407             :             }
    1408             :         }
    1409             : 
    1410             :         /* Found an ungrouped local variable; generate error message */
    1411          60 :         attname = get_rte_attribute_name(rte, var->varattno);
    1412          60 :         if (context->sublevels_up == 0)
    1413          60 :             ereport(ERROR,
    1414             :                     (errcode(ERRCODE_GROUPING_ERROR),
    1415             :                      errmsg("column \"%s.%s\" must appear in the GROUP BY clause or be used in an aggregate function",
    1416             :                             rte->eref->aliasname, attname),
    1417             :                      context->in_agg_direct_args ?
    1418             :                      errdetail("Direct arguments of an ordered-set aggregate must use only grouped columns.") : 0,
    1419             :                      parser_errposition(context->pstate, var->location)));
    1420             :         else
    1421           0 :             ereport(ERROR,
    1422             :                     (errcode(ERRCODE_GROUPING_ERROR),
    1423             :                      errmsg("subquery uses ungrouped column \"%s.%s\" from outer query",
    1424             :                             rte->eref->aliasname, attname),
    1425             :                      parser_errposition(context->pstate, var->location)));
    1426             :     }
    1427             : 
    1428      162822 :     if (IsA(node, Query))
    1429             :     {
    1430             :         /* Recurse into subselects */
    1431             :         bool        result;
    1432             : 
    1433         192 :         context->sublevels_up++;
    1434         192 :         result = query_tree_walker((Query *) node,
    1435             :                                    check_ungrouped_columns_walker,
    1436             :                                    (void *) context,
    1437             :                                    0);
    1438         192 :         context->sublevels_up--;
    1439         192 :         return result;
    1440             :     }
    1441      162630 :     return expression_tree_walker(node, check_ungrouped_columns_walker,
    1442             :                                   (void *) context);
    1443             : }
    1444             : 
    1445             : /*
    1446             :  * finalize_grouping_exprs -
    1447             :  *    Scan the given expression tree for GROUPING() and related calls,
    1448             :  *    and validate and process their arguments.
    1449             :  *
    1450             :  * This is split out from check_ungrouped_columns above because it needs
    1451             :  * to modify the nodes (which it does in-place, not via a mutator) while
    1452             :  * check_ungrouped_columns may see only a copy of the original thanks to
    1453             :  * flattening of join alias vars. So here, we flatten each individual
    1454             :  * GROUPING argument as we see it before comparing it.
    1455             :  */
    1456             : static void
    1457      106992 : finalize_grouping_exprs(Node *node, ParseState *pstate, Query *qry,
    1458             :                         List *groupClauses, bool hasJoinRTEs,
    1459             :                         bool have_non_var_grouping)
    1460             : {
    1461             :     check_ungrouped_columns_context context;
    1462             : 
    1463      106992 :     context.pstate = pstate;
    1464      106992 :     context.qry = qry;
    1465      106992 :     context.hasJoinRTEs = hasJoinRTEs;
    1466      106992 :     context.groupClauses = groupClauses;
    1467      106992 :     context.groupClauseCommonVars = NIL;
    1468      106992 :     context.have_non_var_grouping = have_non_var_grouping;
    1469      106992 :     context.func_grouped_rels = NULL;
    1470      106992 :     context.sublevels_up = 0;
    1471      106992 :     context.in_agg_direct_args = false;
    1472      106992 :     finalize_grouping_exprs_walker(node, &context);
    1473      106988 : }
    1474             : 
    1475             : static bool
    1476      366834 : finalize_grouping_exprs_walker(Node *node,
    1477             :                                check_ungrouped_columns_context *context)
    1478             : {
    1479             :     ListCell   *gl;
    1480             : 
    1481      366834 :     if (node == NULL)
    1482      113832 :         return false;
    1483      253002 :     if (IsA(node, Const) ||
    1484      250304 :         IsA(node, Param))
    1485        2746 :         return false;           /* constants are always acceptable */
    1486             : 
    1487      250256 :     if (IsA(node, Aggref))
    1488             :     {
    1489       58620 :         Aggref     *agg = (Aggref *) node;
    1490             : 
    1491       58620 :         if ((int) agg->agglevelsup == context->sublevels_up)
    1492             :         {
    1493             :             /*
    1494             :              * If we find an aggregate call of the original level, do not
    1495             :              * recurse into its normal arguments, ORDER BY arguments, or
    1496             :              * filter; GROUPING exprs of this level are not allowed there. But
    1497             :              * check direct arguments as though they weren't in an aggregate.
    1498             :              */
    1499             :             bool        result;
    1500             : 
    1501             :             Assert(!context->in_agg_direct_args);
    1502       58616 :             context->in_agg_direct_args = true;
    1503       58616 :             result = finalize_grouping_exprs_walker((Node *) agg->aggdirectargs,
    1504             :                                                     context);
    1505       58616 :             context->in_agg_direct_args = false;
    1506       58616 :             return result;
    1507             :         }
    1508             : 
    1509             :         /*
    1510             :          * We can skip recursing into aggregates of higher levels altogether,
    1511             :          * since they could not possibly contain exprs of concern to us (see
    1512             :          * transformAggregateCall).  We do need to look at aggregates of lower
    1513             :          * levels, however.
    1514             :          */
    1515           4 :         if ((int) agg->agglevelsup > context->sublevels_up)
    1516           0 :             return false;
    1517             :     }
    1518             : 
    1519      191640 :     if (IsA(node, GroupingFunc))
    1520             :     {
    1521         208 :         GroupingFunc *grp = (GroupingFunc *) node;
    1522             : 
    1523             :         /*
    1524             :          * We only need to check GroupingFunc nodes at the exact level to
    1525             :          * which they belong, since they cannot mix levels in arguments.
    1526             :          */
    1527             : 
    1528         208 :         if ((int) grp->agglevelsup == context->sublevels_up)
    1529             :         {
    1530             :             ListCell   *lc;
    1531         180 :             List       *ref_list = NIL;
    1532             : 
    1533         484 :             foreach(lc, grp->args)
    1534             :             {
    1535         308 :                 Node       *expr = lfirst(lc);
    1536         308 :                 Index       ref = 0;
    1537             : 
    1538         308 :                 if (context->hasJoinRTEs)
    1539          16 :                     expr = flatten_join_alias_vars(context->qry, expr);
    1540             : 
    1541             :                 /*
    1542             :                  * Each expression must match a grouping entry at the current
    1543             :                  * query level. Unlike the general expression case, we don't
    1544             :                  * allow functional dependencies or outer references.
    1545             :                  */
    1546             : 
    1547         308 :                 if (IsA(expr, Var))
    1548             :                 {
    1549         300 :                     Var        *var = (Var *) expr;
    1550             : 
    1551         300 :                     if (var->varlevelsup == context->sublevels_up)
    1552             :                     {
    1553         456 :                         foreach(gl, context->groupClauses)
    1554             :                         {
    1555         452 :                             TargetEntry *tle = lfirst(gl);
    1556         452 :                             Var        *gvar = (Var *) tle->expr;
    1557             : 
    1558         452 :                             if (IsA(gvar, Var) &&
    1559         452 :                                 gvar->varno == var->varno &&
    1560         444 :                                 gvar->varattno == var->varattno &&
    1561         296 :                                 gvar->varlevelsup == 0)
    1562             :                             {
    1563         296 :                                 ref = tle->ressortgroupref;
    1564         296 :                                 break;
    1565             :                             }
    1566             :                         }
    1567             :                     }
    1568             :                 }
    1569           8 :                 else if (context->have_non_var_grouping &&
    1570           8 :                          context->sublevels_up == 0)
    1571             :                 {
    1572          16 :                     foreach(gl, context->groupClauses)
    1573             :                     {
    1574          16 :                         TargetEntry *tle = lfirst(gl);
    1575             : 
    1576          16 :                         if (equal(expr, tle->expr))
    1577             :                         {
    1578           8 :                             ref = tle->ressortgroupref;
    1579           8 :                             break;
    1580             :                         }
    1581             :                     }
    1582             :                 }
    1583             : 
    1584         308 :                 if (ref == 0)
    1585           4 :                     ereport(ERROR,
    1586             :                             (errcode(ERRCODE_GROUPING_ERROR),
    1587             :                              errmsg("arguments to GROUPING must be grouping expressions of the associated query level"),
    1588             :                              parser_errposition(context->pstate,
    1589             :                                                 exprLocation(expr))));
    1590             : 
    1591         304 :                 ref_list = lappend_int(ref_list, ref);
    1592             :             }
    1593             : 
    1594         176 :             grp->refs = ref_list;
    1595             :         }
    1596             : 
    1597         204 :         if ((int) grp->agglevelsup > context->sublevels_up)
    1598           6 :             return false;
    1599             :     }
    1600             : 
    1601      191630 :     if (IsA(node, Query))
    1602             :     {
    1603             :         /* Recurse into subselects */
    1604             :         bool        result;
    1605             : 
    1606         196 :         context->sublevels_up++;
    1607         196 :         result = query_tree_walker((Query *) node,
    1608             :                                    finalize_grouping_exprs_walker,
    1609             :                                    (void *) context,
    1610             :                                    0);
    1611         196 :         context->sublevels_up--;
    1612         196 :         return result;
    1613             :     }
    1614      191434 :     return expression_tree_walker(node, finalize_grouping_exprs_walker,
    1615             :                                   (void *) context);
    1616             : }
    1617             : 
    1618             : 
    1619             : /*
    1620             :  * Given a GroupingSet node, expand it and return a list of lists.
    1621             :  *
    1622             :  * For EMPTY nodes, return a list of one empty list.
    1623             :  *
    1624             :  * For SIMPLE nodes, return a list of one list, which is the node content.
    1625             :  *
    1626             :  * For CUBE and ROLLUP nodes, return a list of the expansions.
    1627             :  *
    1628             :  * For SET nodes, recursively expand contained CUBE and ROLLUP.
    1629             :  */
    1630             : static List *
    1631        2364 : expand_groupingset_node(GroupingSet *gs)
    1632             : {
    1633        2364 :     List       *result = NIL;
    1634             : 
    1635        2364 :     switch (gs->kind)
    1636             :     {
    1637         288 :         case GROUPING_SET_EMPTY:
    1638         288 :             result = list_make1(NIL);
    1639         288 :             break;
    1640             : 
    1641        1024 :         case GROUPING_SET_SIMPLE:
    1642        1024 :             result = list_make1(gs->content);
    1643        1024 :             break;
    1644             : 
    1645         332 :         case GROUPING_SET_ROLLUP:
    1646             :             {
    1647         332 :                 List       *rollup_val = gs->content;
    1648             :                 ListCell   *lc;
    1649         332 :                 int         curgroup_size = list_length(gs->content);
    1650             : 
    1651         892 :                 while (curgroup_size > 0)
    1652             :                 {
    1653         560 :                     List       *current_result = NIL;
    1654         560 :                     int         i = curgroup_size;
    1655             : 
    1656         788 :                     foreach(lc, rollup_val)
    1657             :                     {
    1658         788 :                         GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
    1659             : 
    1660             :                         Assert(gs_current->kind == GROUPING_SET_SIMPLE);
    1661             : 
    1662         788 :                         current_result = list_concat(current_result,
    1663         788 :                                                      gs_current->content);
    1664             : 
    1665             :                         /* If we are done with making the current group, break */
    1666         788 :                         if (--i == 0)
    1667         560 :                             break;
    1668             :                     }
    1669             : 
    1670         560 :                     result = lappend(result, current_result);
    1671         560 :                     --curgroup_size;
    1672             :                 }
    1673             : 
    1674         332 :                 result = lappend(result, NIL);
    1675             :             }
    1676         332 :             break;
    1677             : 
    1678         232 :         case GROUPING_SET_CUBE:
    1679             :             {
    1680         232 :                 List       *cube_list = gs->content;
    1681         232 :                 int         number_bits = list_length(cube_list);
    1682             :                 uint32      num_sets;
    1683             :                 uint32      i;
    1684             : 
    1685             :                 /* parser should cap this much lower */
    1686             :                 Assert(number_bits < 31);
    1687             : 
    1688         232 :                 num_sets = (1U << number_bits);
    1689             : 
    1690        1320 :                 for (i = 0; i < num_sets; i++)
    1691             :                 {
    1692        1088 :                     List       *current_result = NIL;
    1693             :                     ListCell   *lc;
    1694        1088 :                     uint32      mask = 1U;
    1695             : 
    1696        3648 :                     foreach(lc, cube_list)
    1697             :                     {
    1698        2560 :                         GroupingSet *gs_current = (GroupingSet *) lfirst(lc);
    1699             : 
    1700             :                         Assert(gs_current->kind == GROUPING_SET_SIMPLE);
    1701             : 
    1702        2560 :                         if (mask & i)
    1703        1280 :                             current_result = list_concat(current_result,
    1704        1280 :                                                          gs_current->content);
    1705             : 
    1706        2560 :                         mask <<= 1;
    1707             :                     }
    1708             : 
    1709        1088 :                     result = lappend(result, current_result);
    1710             :                 }
    1711             :             }
    1712         232 :             break;
    1713             : 
    1714         488 :         case GROUPING_SET_SETS:
    1715             :             {
    1716             :                 ListCell   *lc;
    1717             : 
    1718        1768 :                 foreach(lc, gs->content)
    1719             :                 {
    1720        1280 :                     List       *current_result = expand_groupingset_node(lfirst(lc));
    1721             : 
    1722        1280 :                     result = list_concat(result, current_result);
    1723             :                 }
    1724             :             }
    1725         488 :             break;
    1726             :     }
    1727             : 
    1728        2364 :     return result;
    1729             : }
    1730             : 
    1731             : /* list_sort comparator to sort sub-lists by length */
    1732             : static int
    1733        3672 : cmp_list_len_asc(const ListCell *a, const ListCell *b)
    1734             : {
    1735        3672 :     int         la = list_length((const List *) lfirst(a));
    1736        3672 :     int         lb = list_length((const List *) lfirst(b));
    1737             : 
    1738        3672 :     return (la > lb) ? 1 : (la == lb) ? 0 : -1;
    1739             : }
    1740             : 
    1741             : /* list_sort comparator to sort sub-lists by length and contents */
    1742             : static int
    1743         240 : cmp_list_len_contents_asc(const ListCell *a, const ListCell *b)
    1744             : {
    1745         240 :     int         res = cmp_list_len_asc(a, b);
    1746             : 
    1747         240 :     if (res == 0)
    1748             :     {
    1749          72 :         List       *la = (List *) lfirst(a);
    1750          72 :         List       *lb = (List *) lfirst(b);
    1751             :         ListCell   *lca;
    1752             :         ListCell   *lcb;
    1753             : 
    1754         168 :         forboth(lca, la, lcb, lb)
    1755             :         {
    1756         120 :             int         va = lfirst_int(lca);
    1757         120 :             int         vb = lfirst_int(lcb);
    1758             : 
    1759         120 :             if (va > vb)
    1760          24 :                 return 1;
    1761         108 :             if (va < vb)
    1762          12 :                 return -1;
    1763             :         }
    1764             :     }
    1765             : 
    1766         216 :     return res;
    1767             : }
    1768             : 
    1769             : /*
    1770             :  * Expand a groupingSets clause to a flat list of grouping sets.
    1771             :  * The returned list is sorted by length, shortest sets first.
    1772             :  *
    1773             :  * This is mainly for the planner, but we use it here too to do
    1774             :  * some consistency checks.
    1775             :  */
    1776             : List *
    1777         996 : expand_grouping_sets(List *groupingSets, bool groupDistinct, int limit)
    1778             : {
    1779         996 :     List       *expanded_groups = NIL;
    1780         996 :     List       *result = NIL;
    1781         996 :     double      numsets = 1;
    1782             :     ListCell   *lc;
    1783             : 
    1784         996 :     if (groupingSets == NIL)
    1785           0 :         return NIL;
    1786             : 
    1787        2080 :     foreach(lc, groupingSets)
    1788             :     {
    1789        1084 :         List       *current_result = NIL;
    1790        1084 :         GroupingSet *gs = lfirst(lc);
    1791             : 
    1792        1084 :         current_result = expand_groupingset_node(gs);
    1793             : 
    1794             :         Assert(current_result != NIL);
    1795             : 
    1796        1084 :         numsets *= list_length(current_result);
    1797             : 
    1798        1084 :         if (limit >= 0 && numsets > limit)
    1799           0 :             return NIL;
    1800             : 
    1801        1084 :         expanded_groups = lappend(expanded_groups, current_result);
    1802             :     }
    1803             : 
    1804             :     /*
    1805             :      * Do cartesian product between sublists of expanded_groups. While at it,
    1806             :      * remove any duplicate elements from individual grouping sets (we must
    1807             :      * NOT change the number of sets though)
    1808             :      */
    1809             : 
    1810        4088 :     foreach(lc, (List *) linitial(expanded_groups))
    1811             :     {
    1812        3092 :         result = lappend(result, list_union_int(NIL, (List *) lfirst(lc)));
    1813             :     }
    1814             : 
    1815        1084 :     for_each_from(lc, expanded_groups, 1)
    1816             :     {
    1817          88 :         List       *p = lfirst(lc);
    1818          88 :         List       *new_result = NIL;
    1819             :         ListCell   *lc2;
    1820             : 
    1821         280 :         foreach(lc2, result)
    1822             :         {
    1823         192 :             List       *q = lfirst(lc2);
    1824             :             ListCell   *lc3;
    1825             : 
    1826         672 :             foreach(lc3, p)
    1827             :             {
    1828         480 :                 new_result = lappend(new_result,
    1829         480 :                                      list_union_int(q, (List *) lfirst(lc3)));
    1830             :             }
    1831             :         }
    1832          88 :         result = new_result;
    1833             :     }
    1834             : 
    1835             :     /* Now sort the lists by length and deduplicate if necessary */
    1836         996 :     if (!groupDistinct || list_length(result) < 2)
    1837         984 :         list_sort(result, cmp_list_len_asc);
    1838             :     else
    1839             :     {
    1840             :         ListCell   *cell;
    1841             :         List       *prev;
    1842             : 
    1843             :         /* Sort each groupset individually */
    1844         120 :         foreach(cell, result)
    1845         108 :             list_sort(lfirst(cell), list_int_cmp);
    1846             : 
    1847             :         /* Now sort the list of groupsets by length and contents */
    1848          12 :         list_sort(result, cmp_list_len_contents_asc);
    1849             : 
    1850             :         /* Finally, remove duplicates */
    1851          12 :         prev = linitial(result);
    1852         108 :         for_each_from(cell, result, 1)
    1853             :         {
    1854          96 :             if (equal(lfirst(cell), prev))
    1855          48 :                 result = foreach_delete_current(result, cell);
    1856             :             else
    1857          48 :                 prev = lfirst(cell);
    1858             :         }
    1859             :     }
    1860             : 
    1861         996 :     return result;
    1862             : }
    1863             : 
    1864             : /*
    1865             :  * get_aggregate_argtypes
    1866             :  *  Identify the specific datatypes passed to an aggregate call.
    1867             :  *
    1868             :  * Given an Aggref, extract the actual datatypes of the input arguments.
    1869             :  * The input datatypes are reported in a way that matches up with the
    1870             :  * aggregate's declaration, ie, any ORDER BY columns attached to a plain
    1871             :  * aggregate are ignored, but we report both direct and aggregated args of
    1872             :  * an ordered-set aggregate.
    1873             :  *
    1874             :  * Datatypes are returned into inputTypes[], which must reference an array
    1875             :  * of length FUNC_MAX_ARGS.
    1876             :  *
    1877             :  * The function result is the number of actual arguments.
    1878             :  */
    1879             : int
    1880      113628 : get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
    1881             : {
    1882      113628 :     int         numArguments = 0;
    1883             :     ListCell   *lc;
    1884             : 
    1885             :     Assert(list_length(aggref->aggargtypes) <= FUNC_MAX_ARGS);
    1886             : 
    1887      212624 :     foreach(lc, aggref->aggargtypes)
    1888             :     {
    1889       98996 :         inputTypes[numArguments++] = lfirst_oid(lc);
    1890             :     }
    1891             : 
    1892      113628 :     return numArguments;
    1893             : }
    1894             : 
    1895             : /*
    1896             :  * resolve_aggregate_transtype
    1897             :  *  Identify the transition state value's datatype for an aggregate call.
    1898             :  *
    1899             :  * This function resolves a polymorphic aggregate's state datatype.
    1900             :  * It must be passed the aggtranstype from the aggregate's catalog entry,
    1901             :  * as well as the actual argument types extracted by get_aggregate_argtypes.
    1902             :  * (We could fetch pg_aggregate.aggtranstype internally, but all existing
    1903             :  * callers already have the value at hand, so we make them pass it.)
    1904             :  */
    1905             : Oid
    1906       54122 : resolve_aggregate_transtype(Oid aggfuncid,
    1907             :                             Oid aggtranstype,
    1908             :                             Oid *inputTypes,
    1909             :                             int numArguments)
    1910             : {
    1911             :     /* resolve actual type of transition state, if polymorphic */
    1912       54122 :     if (IsPolymorphicType(aggtranstype))
    1913             :     {
    1914             :         /* have to fetch the agg's declared input types... */
    1915             :         Oid        *declaredArgTypes;
    1916             :         int         agg_nargs;
    1917             : 
    1918         314 :         (void) get_func_signature(aggfuncid, &declaredArgTypes, &agg_nargs);
    1919             : 
    1920             :         /*
    1921             :          * VARIADIC ANY aggs could have more actual than declared args, but
    1922             :          * such extra args can't affect polymorphic type resolution.
    1923             :          */
    1924             :         Assert(agg_nargs <= numArguments);
    1925             : 
    1926         314 :         aggtranstype = enforce_generic_type_consistency(inputTypes,
    1927             :                                                         declaredArgTypes,
    1928             :                                                         agg_nargs,
    1929             :                                                         aggtranstype,
    1930             :                                                         false);
    1931         314 :         pfree(declaredArgTypes);
    1932             :     }
    1933       54122 :     return aggtranstype;
    1934             : }
    1935             : 
    1936             : /*
    1937             :  * Create an expression tree for the transition function of an aggregate.
    1938             :  * This is needed so that polymorphic functions can be used within an
    1939             :  * aggregate --- without the expression tree, such functions would not know
    1940             :  * the datatypes they are supposed to use.  (The trees will never actually
    1941             :  * be executed, however, so we can skimp a bit on correctness.)
    1942             :  *
    1943             :  * agg_input_types and agg_state_type identifies the input types of the
    1944             :  * aggregate.  These should be resolved to actual types (ie, none should
    1945             :  * ever be ANYELEMENT etc).
    1946             :  * agg_input_collation is the aggregate function's input collation.
    1947             :  *
    1948             :  * For an ordered-set aggregate, remember that agg_input_types describes
    1949             :  * the direct arguments followed by the aggregated arguments.
    1950             :  *
    1951             :  * transfn_oid and invtransfn_oid identify the funcs to be called; the
    1952             :  * latter may be InvalidOid, however if invtransfn_oid is set then
    1953             :  * transfn_oid must also be set.
    1954             :  *
    1955             :  * transfn_oid may also be passed as the aggcombinefn when the *transfnexpr is
    1956             :  * to be used for a combine aggregate phase.  We expect invtransfn_oid to be
    1957             :  * InvalidOid in this case since there is no such thing as an inverse
    1958             :  * combinefn.
    1959             :  *
    1960             :  * Pointers to the constructed trees are returned into *transfnexpr,
    1961             :  * *invtransfnexpr. If there is no invtransfn, the respective pointer is set
    1962             :  * to NULL.  Since use of the invtransfn is optional, NULL may be passed for
    1963             :  * invtransfnexpr.
    1964             :  */
    1965             : void
    1966       59768 : build_aggregate_transfn_expr(Oid *agg_input_types,
    1967             :                              int agg_num_inputs,
    1968             :                              int agg_num_direct_inputs,
    1969             :                              bool agg_variadic,
    1970             :                              Oid agg_state_type,
    1971             :                              Oid agg_input_collation,
    1972             :                              Oid transfn_oid,
    1973             :                              Oid invtransfn_oid,
    1974             :                              Expr **transfnexpr,
    1975             :                              Expr **invtransfnexpr)
    1976             : {
    1977             :     List       *args;
    1978             :     FuncExpr   *fexpr;
    1979             :     int         i;
    1980             : 
    1981             :     /*
    1982             :      * Build arg list to use in the transfn FuncExpr node.
    1983             :      */
    1984       59768 :     args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
    1985             : 
    1986      112366 :     for (i = agg_num_direct_inputs; i < agg_num_inputs; i++)
    1987             :     {
    1988       52598 :         args = lappend(args,
    1989       52598 :                        make_agg_arg(agg_input_types[i], agg_input_collation));
    1990             :     }
    1991             : 
    1992       59768 :     fexpr = makeFuncExpr(transfn_oid,
    1993             :                          agg_state_type,
    1994             :                          args,
    1995             :                          InvalidOid,
    1996             :                          agg_input_collation,
    1997             :                          COERCE_EXPLICIT_CALL);
    1998       59768 :     fexpr->funcvariadic = agg_variadic;
    1999       59768 :     *transfnexpr = (Expr *) fexpr;
    2000             : 
    2001             :     /*
    2002             :      * Build invtransfn expression if requested, with same args as transfn
    2003             :      */
    2004       59768 :     if (invtransfnexpr != NULL)
    2005             :     {
    2006         764 :         if (OidIsValid(invtransfn_oid))
    2007             :         {
    2008         680 :             fexpr = makeFuncExpr(invtransfn_oid,
    2009             :                                  agg_state_type,
    2010             :                                  args,
    2011             :                                  InvalidOid,
    2012             :                                  agg_input_collation,
    2013             :                                  COERCE_EXPLICIT_CALL);
    2014         680 :             fexpr->funcvariadic = agg_variadic;
    2015         680 :             *invtransfnexpr = (Expr *) fexpr;
    2016             :         }
    2017             :         else
    2018          84 :             *invtransfnexpr = NULL;
    2019             :     }
    2020       59768 : }
    2021             : 
    2022             : /*
    2023             :  * Like build_aggregate_transfn_expr, but creates an expression tree for the
    2024             :  * serialization function of an aggregate.
    2025             :  */
    2026             : void
    2027         160 : build_aggregate_serialfn_expr(Oid serialfn_oid,
    2028             :                               Expr **serialfnexpr)
    2029             : {
    2030             :     List       *args;
    2031             :     FuncExpr   *fexpr;
    2032             : 
    2033             :     /* serialfn always takes INTERNAL and returns BYTEA */
    2034         160 :     args = list_make1(make_agg_arg(INTERNALOID, InvalidOid));
    2035             : 
    2036         160 :     fexpr = makeFuncExpr(serialfn_oid,
    2037             :                          BYTEAOID,
    2038             :                          args,
    2039             :                          InvalidOid,
    2040             :                          InvalidOid,
    2041             :                          COERCE_EXPLICIT_CALL);
    2042         160 :     *serialfnexpr = (Expr *) fexpr;
    2043         160 : }
    2044             : 
    2045             : /*
    2046             :  * Like build_aggregate_transfn_expr, but creates an expression tree for the
    2047             :  * deserialization function of an aggregate.
    2048             :  */
    2049             : void
    2050          48 : build_aggregate_deserialfn_expr(Oid deserialfn_oid,
    2051             :                                 Expr **deserialfnexpr)
    2052             : {
    2053             :     List       *args;
    2054             :     FuncExpr   *fexpr;
    2055             : 
    2056             :     /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
    2057          48 :     args = list_make2(make_agg_arg(BYTEAOID, InvalidOid),
    2058             :                       make_agg_arg(INTERNALOID, InvalidOid));
    2059             : 
    2060          48 :     fexpr = makeFuncExpr(deserialfn_oid,
    2061             :                          INTERNALOID,
    2062             :                          args,
    2063             :                          InvalidOid,
    2064             :                          InvalidOid,
    2065             :                          COERCE_EXPLICIT_CALL);
    2066          48 :     *deserialfnexpr = (Expr *) fexpr;
    2067          48 : }
    2068             : 
    2069             : /*
    2070             :  * Like build_aggregate_transfn_expr, but creates an expression tree for the
    2071             :  * final function of an aggregate, rather than the transition function.
    2072             :  */
    2073             : void
    2074       42440 : build_aggregate_finalfn_expr(Oid *agg_input_types,
    2075             :                              int num_finalfn_inputs,
    2076             :                              Oid agg_state_type,
    2077             :                              Oid agg_result_type,
    2078             :                              Oid agg_input_collation,
    2079             :                              Oid finalfn_oid,
    2080             :                              Expr **finalfnexpr)
    2081             : {
    2082             :     List       *args;
    2083             :     int         i;
    2084             : 
    2085             :     /*
    2086             :      * Build expr tree for final function
    2087             :      */
    2088       42440 :     args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
    2089             : 
    2090             :     /* finalfn may take additional args, which match agg's input types */
    2091       82250 :     for (i = 0; i < num_finalfn_inputs - 1; i++)
    2092             :     {
    2093       39810 :         args = lappend(args,
    2094       39810 :                        make_agg_arg(agg_input_types[i], agg_input_collation));
    2095             :     }
    2096             : 
    2097       42440 :     *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
    2098             :                                          agg_result_type,
    2099             :                                          args,
    2100             :                                          InvalidOid,
    2101             :                                          agg_input_collation,
    2102             :                                          COERCE_EXPLICIT_CALL);
    2103             :     /* finalfn is currently never treated as variadic */
    2104       42440 : }
    2105             : 
    2106             : /*
    2107             :  * Convenience function to build dummy argument expressions for aggregates.
    2108             :  *
    2109             :  * We really only care that an aggregate support function can discover its
    2110             :  * actual argument types at runtime using get_fn_expr_argtype(), so it's okay
    2111             :  * to use Param nodes that don't correspond to any real Param.
    2112             :  */
    2113             : static Node *
    2114      194872 : make_agg_arg(Oid argtype, Oid argcollation)
    2115             : {
    2116      194872 :     Param      *argp = makeNode(Param);
    2117             : 
    2118      194872 :     argp->paramkind = PARAM_EXEC;
    2119      194872 :     argp->paramid = -1;
    2120      194872 :     argp->paramtype = argtype;
    2121      194872 :     argp->paramtypmod = -1;
    2122      194872 :     argp->paramcollid = argcollation;
    2123      194872 :     argp->location = -1;
    2124      194872 :     return (Node *) argp;
    2125             : }

Generated by: LCOV version 1.14