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

Generated by: LCOV version 1.11