LCOV - code coverage report
Current view: top level - src/backend/optimizer/plan - planner.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 1977 2032 97.3 %
Date: 2019-11-22 06:06:53 Functions: 52 52 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * planner.c
       4             :  *    The query optimizer external interface.
       5             :  *
       6             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/optimizer/plan/planner.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : 
      16             : #include "postgres.h"
      17             : 
      18             : #include <limits.h>
      19             : #include <math.h>
      20             : 
      21             : #include "access/genam.h"
      22             : #include "access/htup_details.h"
      23             : #include "access/parallel.h"
      24             : #include "access/sysattr.h"
      25             : #include "access/table.h"
      26             : #include "access/xact.h"
      27             : #include "catalog/pg_constraint.h"
      28             : #include "catalog/pg_inherits.h"
      29             : #include "catalog/pg_proc.h"
      30             : #include "catalog/pg_type.h"
      31             : #include "executor/executor.h"
      32             : #include "executor/nodeAgg.h"
      33             : #include "foreign/fdwapi.h"
      34             : #include "jit/jit.h"
      35             : #include "lib/bipartite_match.h"
      36             : #include "lib/knapsack.h"
      37             : #include "miscadmin.h"
      38             : #include "nodes/makefuncs.h"
      39             : #include "nodes/nodeFuncs.h"
      40             : #ifdef OPTIMIZER_DEBUG
      41             : #include "nodes/print.h"
      42             : #endif
      43             : #include "optimizer/appendinfo.h"
      44             : #include "optimizer/clauses.h"
      45             : #include "optimizer/cost.h"
      46             : #include "optimizer/inherit.h"
      47             : #include "optimizer/optimizer.h"
      48             : #include "optimizer/paramassign.h"
      49             : #include "optimizer/pathnode.h"
      50             : #include "optimizer/paths.h"
      51             : #include "optimizer/plancat.h"
      52             : #include "optimizer/planmain.h"
      53             : #include "optimizer/planner.h"
      54             : #include "optimizer/prep.h"
      55             : #include "optimizer/subselect.h"
      56             : #include "optimizer/tlist.h"
      57             : #include "parser/analyze.h"
      58             : #include "parser/parse_agg.h"
      59             : #include "parser/parsetree.h"
      60             : #include "partitioning/partdesc.h"
      61             : #include "rewrite/rewriteManip.h"
      62             : #include "storage/dsm_impl.h"
      63             : #include "utils/lsyscache.h"
      64             : #include "utils/rel.h"
      65             : #include "utils/selfuncs.h"
      66             : #include "utils/syscache.h"
      67             : 
      68             : /* GUC parameters */
      69             : double      cursor_tuple_fraction = DEFAULT_CURSOR_TUPLE_FRACTION;
      70             : int         force_parallel_mode = FORCE_PARALLEL_OFF;
      71             : bool        parallel_leader_participation = true;
      72             : 
      73             : /* Hook for plugins to get control in planner() */
      74             : planner_hook_type planner_hook = NULL;
      75             : 
      76             : /* Hook for plugins to get control when grouping_planner() plans upper rels */
      77             : create_upper_paths_hook_type create_upper_paths_hook = NULL;
      78             : 
      79             : 
      80             : /* Expression kind codes for preprocess_expression */
      81             : #define EXPRKIND_QUAL               0
      82             : #define EXPRKIND_TARGET             1
      83             : #define EXPRKIND_RTFUNC             2
      84             : #define EXPRKIND_RTFUNC_LATERAL     3
      85             : #define EXPRKIND_VALUES             4
      86             : #define EXPRKIND_VALUES_LATERAL     5
      87             : #define EXPRKIND_LIMIT              6
      88             : #define EXPRKIND_APPINFO            7
      89             : #define EXPRKIND_PHV                8
      90             : #define EXPRKIND_TABLESAMPLE        9
      91             : #define EXPRKIND_ARBITER_ELEM       10
      92             : #define EXPRKIND_TABLEFUNC          11
      93             : #define EXPRKIND_TABLEFUNC_LATERAL  12
      94             : 
      95             : /* Passthrough data for standard_qp_callback */
      96             : typedef struct
      97             : {
      98             :     List       *activeWindows;  /* active windows, if any */
      99             :     List       *groupClause;    /* overrides parse->groupClause */
     100             : } standard_qp_extra;
     101             : 
     102             : /*
     103             :  * Data specific to grouping sets
     104             :  */
     105             : 
     106             : typedef struct
     107             : {
     108             :     List       *rollups;
     109             :     List       *hash_sets_idx;
     110             :     double      dNumHashGroups;
     111             :     bool        any_hashable;
     112             :     Bitmapset  *unsortable_refs;
     113             :     Bitmapset  *unhashable_refs;
     114             :     List       *unsortable_sets;
     115             :     int        *tleref_to_colnum_map;
     116             : } grouping_sets_data;
     117             : 
     118             : /*
     119             :  * Temporary structure for use during WindowClause reordering in order to be
     120             :  * able to sort WindowClauses on partitioning/ordering prefix.
     121             :  */
     122             : typedef struct
     123             : {
     124             :     WindowClause *wc;
     125             :     List       *uniqueOrder;    /* A List of unique ordering/partitioning
     126             :                                  * clauses per Window */
     127             : } WindowClauseSortData;
     128             : 
     129             : /* Local functions */
     130             : static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
     131             : static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
     132             : static void inheritance_planner(PlannerInfo *root);
     133             : static void grouping_planner(PlannerInfo *root, bool inheritance_update,
     134             :                              double tuple_fraction);
     135             : static grouping_sets_data *preprocess_grouping_sets(PlannerInfo *root);
     136             : static List *remap_to_groupclause_idx(List *groupClause, List *gsets,
     137             :                                       int *tleref_to_colnum_map);
     138             : static void preprocess_rowmarks(PlannerInfo *root);
     139             : static double preprocess_limit(PlannerInfo *root,
     140             :                                double tuple_fraction,
     141             :                                int64 *offset_est, int64 *count_est);
     142             : static void remove_useless_groupby_columns(PlannerInfo *root);
     143             : static List *preprocess_groupclause(PlannerInfo *root, List *force);
     144             : static List *extract_rollup_sets(List *groupingSets);
     145             : static List *reorder_grouping_sets(List *groupingSets, List *sortclause);
     146             : static void standard_qp_callback(PlannerInfo *root, void *extra);
     147             : static double get_number_of_groups(PlannerInfo *root,
     148             :                                    double path_rows,
     149             :                                    grouping_sets_data *gd,
     150             :                                    List *target_list);
     151             : static RelOptInfo *create_grouping_paths(PlannerInfo *root,
     152             :                                          RelOptInfo *input_rel,
     153             :                                          PathTarget *target,
     154             :                                          bool target_parallel_safe,
     155             :                                          const AggClauseCosts *agg_costs,
     156             :                                          grouping_sets_data *gd);
     157             : static bool is_degenerate_grouping(PlannerInfo *root);
     158             : static void create_degenerate_grouping_paths(PlannerInfo *root,
     159             :                                              RelOptInfo *input_rel,
     160             :                                              RelOptInfo *grouped_rel);
     161             : static RelOptInfo *make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
     162             :                                      PathTarget *target, bool target_parallel_safe,
     163             :                                      Node *havingQual);
     164             : static void create_ordinary_grouping_paths(PlannerInfo *root,
     165             :                                            RelOptInfo *input_rel,
     166             :                                            RelOptInfo *grouped_rel,
     167             :                                            const AggClauseCosts *agg_costs,
     168             :                                            grouping_sets_data *gd,
     169             :                                            GroupPathExtraData *extra,
     170             :                                            RelOptInfo **partially_grouped_rel_p);
     171             : static void consider_groupingsets_paths(PlannerInfo *root,
     172             :                                         RelOptInfo *grouped_rel,
     173             :                                         Path *path,
     174             :                                         bool is_sorted,
     175             :                                         bool can_hash,
     176             :                                         grouping_sets_data *gd,
     177             :                                         const AggClauseCosts *agg_costs,
     178             :                                         double dNumGroups);
     179             : static RelOptInfo *create_window_paths(PlannerInfo *root,
     180             :                                        RelOptInfo *input_rel,
     181             :                                        PathTarget *input_target,
     182             :                                        PathTarget *output_target,
     183             :                                        bool output_target_parallel_safe,
     184             :                                        WindowFuncLists *wflists,
     185             :                                        List *activeWindows);
     186             : static void create_one_window_path(PlannerInfo *root,
     187             :                                    RelOptInfo *window_rel,
     188             :                                    Path *path,
     189             :                                    PathTarget *input_target,
     190             :                                    PathTarget *output_target,
     191             :                                    WindowFuncLists *wflists,
     192             :                                    List *activeWindows);
     193             : static RelOptInfo *create_distinct_paths(PlannerInfo *root,
     194             :                                          RelOptInfo *input_rel);
     195             : static RelOptInfo *create_ordered_paths(PlannerInfo *root,
     196             :                                         RelOptInfo *input_rel,
     197             :                                         PathTarget *target,
     198             :                                         bool target_parallel_safe,
     199             :                                         double limit_tuples);
     200             : static PathTarget *make_group_input_target(PlannerInfo *root,
     201             :                                            PathTarget *final_target);
     202             : static PathTarget *make_partial_grouping_target(PlannerInfo *root,
     203             :                                                 PathTarget *grouping_target,
     204             :                                                 Node *havingQual);
     205             : static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
     206             : static List *select_active_windows(PlannerInfo *root, WindowFuncLists *wflists);
     207             : static PathTarget *make_window_input_target(PlannerInfo *root,
     208             :                                             PathTarget *final_target,
     209             :                                             List *activeWindows);
     210             : static List *make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc,
     211             :                                       List *tlist);
     212             : static PathTarget *make_sort_input_target(PlannerInfo *root,
     213             :                                           PathTarget *final_target,
     214             :                                           bool *have_postponed_srfs);
     215             : static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel,
     216             :                                   List *targets, List *targets_contain_srfs);
     217             : static void add_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
     218             :                                       RelOptInfo *grouped_rel,
     219             :                                       RelOptInfo *partially_grouped_rel,
     220             :                                       const AggClauseCosts *agg_costs,
     221             :                                       grouping_sets_data *gd,
     222             :                                       double dNumGroups,
     223             :                                       GroupPathExtraData *extra);
     224             : static RelOptInfo *create_partial_grouping_paths(PlannerInfo *root,
     225             :                                                  RelOptInfo *grouped_rel,
     226             :                                                  RelOptInfo *input_rel,
     227             :                                                  grouping_sets_data *gd,
     228             :                                                  GroupPathExtraData *extra,
     229             :                                                  bool force_rel_creation);
     230             : static void gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel);
     231             : static bool can_partial_agg(PlannerInfo *root,
     232             :                             const AggClauseCosts *agg_costs);
     233             : static void apply_scanjoin_target_to_paths(PlannerInfo *root,
     234             :                                            RelOptInfo *rel,
     235             :                                            List *scanjoin_targets,
     236             :                                            List *scanjoin_targets_contain_srfs,
     237             :                                            bool scanjoin_target_parallel_safe,
     238             :                                            bool tlist_same_exprs);
     239             : static void create_partitionwise_grouping_paths(PlannerInfo *root,
     240             :                                                 RelOptInfo *input_rel,
     241             :                                                 RelOptInfo *grouped_rel,
     242             :                                                 RelOptInfo *partially_grouped_rel,
     243             :                                                 const AggClauseCosts *agg_costs,
     244             :                                                 grouping_sets_data *gd,
     245             :                                                 PartitionwiseAggregateType patype,
     246             :                                                 GroupPathExtraData *extra);
     247             : static bool group_by_has_partkey(RelOptInfo *input_rel,
     248             :                                  List *targetList,
     249             :                                  List *groupClause);
     250             : static int  common_prefix_cmp(const void *a, const void *b);
     251             : 
     252             : 
     253             : /*****************************************************************************
     254             :  *
     255             :  *     Query optimizer entry point
     256             :  *
     257             :  * To support loadable plugins that monitor or modify planner behavior,
     258             :  * we provide a hook variable that lets a plugin get control before and
     259             :  * after the standard planning process.  The plugin would normally call
     260             :  * standard_planner().
     261             :  *
     262             :  * Note to plugin authors: standard_planner() scribbles on its Query input,
     263             :  * so you'd better copy that data structure if you want to plan more than once.
     264             :  *
     265             :  *****************************************************************************/
     266             : PlannedStmt *
     267      247288 : planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
     268             : {
     269             :     PlannedStmt *result;
     270             : 
     271      247288 :     if (planner_hook)
     272           0 :         result = (*planner_hook) (parse, cursorOptions, boundParams);
     273             :     else
     274      247288 :         result = standard_planner(parse, cursorOptions, boundParams);
     275      245762 :     return result;
     276             : }
     277             : 
     278             : PlannedStmt *
     279      247288 : standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
     280             : {
     281             :     PlannedStmt *result;
     282             :     PlannerGlobal *glob;
     283             :     double      tuple_fraction;
     284             :     PlannerInfo *root;
     285             :     RelOptInfo *final_rel;
     286             :     Path       *best_path;
     287             :     Plan       *top_plan;
     288             :     ListCell   *lp,
     289             :                *lr;
     290             : 
     291             :     /*
     292             :      * Set up global state for this planner invocation.  This data is needed
     293             :      * across all levels of sub-Query that might exist in the given command,
     294             :      * so we keep it in a separate struct that's linked to by each per-Query
     295             :      * PlannerInfo.
     296             :      */
     297      247288 :     glob = makeNode(PlannerGlobal);
     298             : 
     299      247288 :     glob->boundParams = boundParams;
     300      247288 :     glob->subplans = NIL;
     301      247288 :     glob->subroots = NIL;
     302      247288 :     glob->rewindPlanIDs = NULL;
     303      247288 :     glob->finalrtable = NIL;
     304      247288 :     glob->finalrowmarks = NIL;
     305      247288 :     glob->resultRelations = NIL;
     306      247288 :     glob->rootResultRelations = NIL;
     307      247288 :     glob->relationOids = NIL;
     308      247288 :     glob->invalItems = NIL;
     309      247288 :     glob->paramExecTypes = NIL;
     310      247288 :     glob->lastPHId = 0;
     311      247288 :     glob->lastRowMarkId = 0;
     312      247288 :     glob->lastPlanNodeId = 0;
     313      247288 :     glob->transientPlan = false;
     314      247288 :     glob->dependsOnRole = false;
     315             : 
     316             :     /*
     317             :      * Assess whether it's feasible to use parallel mode for this query. We
     318             :      * can't do this in a standalone backend, or if the command will try to
     319             :      * modify any data, or if this is a cursor operation, or if GUCs are set
     320             :      * to values that don't permit parallelism, or if parallel-unsafe
     321             :      * functions are present in the query tree.
     322             :      *
     323             :      * (Note that we do allow CREATE TABLE AS, SELECT INTO, and CREATE
     324             :      * MATERIALIZED VIEW to use parallel plans, but this is safe only because
     325             :      * the command is writing into a completely new table which workers won't
     326             :      * be able to see.  If the workers could see the table, the fact that
     327             :      * group locking would cause them to ignore the leader's heavyweight
     328             :      * relation extension lock and GIN page locks would make this unsafe.
     329             :      * We'll have to fix that somehow if we want to allow parallel inserts in
     330             :      * general; updates and deletes have additional problems especially around
     331             :      * combo CIDs.)
     332             :      *
     333             :      * For now, we don't try to use parallel mode if we're running inside a
     334             :      * parallel worker.  We might eventually be able to relax this
     335             :      * restriction, but for now it seems best not to have parallel workers
     336             :      * trying to create their own parallel workers.
     337             :      */
     338      247288 :     if ((cursorOptions & CURSOR_OPT_PARALLEL_OK) != 0 &&
     339      208104 :         IsUnderPostmaster &&
     340      374890 :         parse->commandType == CMD_SELECT &&
     341      333488 :         !parse->hasModifyingCTE &&
     342      333098 :         max_parallel_workers_per_gather > 0 &&
     343      166396 :         !IsParallelWorker())
     344             :     {
     345             :         /* all the cheap tests pass, so scan the query tree */
     346      166364 :         glob->maxParallelHazard = max_parallel_hazard(parse);
     347      166364 :         glob->parallelModeOK = (glob->maxParallelHazard != PROPARALLEL_UNSAFE);
     348             :     }
     349             :     else
     350             :     {
     351             :         /* skip the query tree scan, just assume it's unsafe */
     352       80924 :         glob->maxParallelHazard = PROPARALLEL_UNSAFE;
     353       80924 :         glob->parallelModeOK = false;
     354             :     }
     355             : 
     356             :     /*
     357             :      * glob->parallelModeNeeded is normally set to false here and changed to
     358             :      * true during plan creation if a Gather or Gather Merge plan is actually
     359             :      * created (cf. create_gather_plan, create_gather_merge_plan).
     360             :      *
     361             :      * However, if force_parallel_mode = on or force_parallel_mode = regress,
     362             :      * then we impose parallel mode whenever it's safe to do so, even if the
     363             :      * final plan doesn't use parallelism.  It's not safe to do so if the
     364             :      * query contains anything parallel-unsafe; parallelModeOK will be false
     365             :      * in that case.  Note that parallelModeOK can't change after this point.
     366             :      * Otherwise, everything in the query is either parallel-safe or
     367             :      * parallel-restricted, and in either case it should be OK to impose
     368             :      * parallel-mode restrictions.  If that ends up breaking something, then
     369             :      * either some function the user included in the query is incorrectly
     370             :      * labelled as parallel-safe or parallel-restricted when in reality it's
     371             :      * parallel-unsafe, or else the query planner itself has a bug.
     372             :      */
     373      392298 :     glob->parallelModeNeeded = glob->parallelModeOK &&
     374      145010 :         (force_parallel_mode != FORCE_PARALLEL_OFF);
     375             : 
     376             :     /* Determine what fraction of the plan is likely to be scanned */
     377      247288 :     if (cursorOptions & CURSOR_OPT_FAST_PLAN)
     378             :     {
     379             :         /*
     380             :          * We have no real idea how many tuples the user will ultimately FETCH
     381             :          * from a cursor, but it is often the case that he doesn't want 'em
     382             :          * all, or would prefer a fast-start plan anyway so that he can
     383             :          * process some of the tuples sooner.  Use a GUC parameter to decide
     384             :          * what fraction to optimize for.
     385             :          */
     386        2064 :         tuple_fraction = cursor_tuple_fraction;
     387             : 
     388             :         /*
     389             :          * We document cursor_tuple_fraction as simply being a fraction, which
     390             :          * means the edge cases 0 and 1 have to be treated specially here.  We
     391             :          * convert 1 to 0 ("all the tuples") and 0 to a very small fraction.
     392             :          */
     393        2064 :         if (tuple_fraction >= 1.0)
     394           0 :             tuple_fraction = 0.0;
     395        2064 :         else if (tuple_fraction <= 0.0)
     396           0 :             tuple_fraction = 1e-10;
     397             :     }
     398             :     else
     399             :     {
     400             :         /* Default assumption is we need all the tuples */
     401      245224 :         tuple_fraction = 0.0;
     402             :     }
     403             : 
     404             :     /* primary planning entry point (may recurse for subqueries) */
     405      247288 :     root = subquery_planner(glob, parse, NULL,
     406             :                             false, tuple_fraction);
     407             : 
     408             :     /* Select best Path and turn it into a Plan */
     409      245882 :     final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
     410      245882 :     best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
     411             : 
     412      245882 :     top_plan = create_plan(root, best_path);
     413             : 
     414             :     /*
     415             :      * If creating a plan for a scrollable cursor, make sure it can run
     416             :      * backwards on demand.  Add a Material node at the top at need.
     417             :      */
     418      245762 :     if (cursorOptions & CURSOR_OPT_SCROLL)
     419             :     {
     420         164 :         if (!ExecSupportsBackwardScan(top_plan))
     421          16 :             top_plan = materialize_finished_plan(top_plan);
     422             :     }
     423             : 
     424             :     /*
     425             :      * Optionally add a Gather node for testing purposes, provided this is
     426             :      * actually a safe thing to do.
     427             :      */
     428      245762 :     if (force_parallel_mode != FORCE_PARALLEL_OFF && top_plan->parallel_safe)
     429             :     {
     430          18 :         Gather     *gather = makeNode(Gather);
     431             : 
     432             :         /*
     433             :          * If there are any initPlans attached to the formerly-top plan node,
     434             :          * move them up to the Gather node; same as we do for Material node in
     435             :          * materialize_finished_plan.
     436             :          */
     437          18 :         gather->plan.initPlan = top_plan->initPlan;
     438          18 :         top_plan->initPlan = NIL;
     439             : 
     440          18 :         gather->plan.targetlist = top_plan->targetlist;
     441          18 :         gather->plan.qual = NIL;
     442          18 :         gather->plan.lefttree = top_plan;
     443          18 :         gather->plan.righttree = NULL;
     444          18 :         gather->num_workers = 1;
     445          18 :         gather->single_copy = true;
     446          18 :         gather->invisible = (force_parallel_mode == FORCE_PARALLEL_REGRESS);
     447             : 
     448             :         /*
     449             :          * Since this Gather has no parallel-aware descendants to signal to,
     450             :          * we don't need a rescan Param.
     451             :          */
     452          18 :         gather->rescan_param = -1;
     453             : 
     454             :         /*
     455             :          * Ideally we'd use cost_gather here, but setting up dummy path data
     456             :          * to satisfy it doesn't seem much cleaner than knowing what it does.
     457             :          */
     458          18 :         gather->plan.startup_cost = top_plan->startup_cost +
     459             :             parallel_setup_cost;
     460          36 :         gather->plan.total_cost = top_plan->total_cost +
     461          18 :             parallel_setup_cost + parallel_tuple_cost * top_plan->plan_rows;
     462          18 :         gather->plan.plan_rows = top_plan->plan_rows;
     463          18 :         gather->plan.plan_width = top_plan->plan_width;
     464          18 :         gather->plan.parallel_aware = false;
     465          18 :         gather->plan.parallel_safe = false;
     466             : 
     467             :         /* use parallel mode for parallel plans. */
     468          18 :         root->glob->parallelModeNeeded = true;
     469             : 
     470          18 :         top_plan = &gather->plan;
     471             :     }
     472             : 
     473             :     /*
     474             :      * If any Params were generated, run through the plan tree and compute
     475             :      * each plan node's extParam/allParam sets.  Ideally we'd merge this into
     476             :      * set_plan_references' tree traversal, but for now it has to be separate
     477             :      * because we need to visit subplans before not after main plan.
     478             :      */
     479      245762 :     if (glob->paramExecTypes != NIL)
     480             :     {
     481             :         Assert(list_length(glob->subplans) == list_length(glob->subroots));
     482      154246 :         forboth(lp, glob->subplans, lr, glob->subroots)
     483             :         {
     484       46230 :             Plan       *subplan = (Plan *) lfirst(lp);
     485       46230 :             PlannerInfo *subroot = lfirst_node(PlannerInfo, lr);
     486             : 
     487       46230 :             SS_finalize_plan(subroot, subplan);
     488             :         }
     489      108016 :         SS_finalize_plan(root, top_plan);
     490             :     }
     491             : 
     492             :     /* final cleanup of the plan */
     493             :     Assert(glob->finalrtable == NIL);
     494             :     Assert(glob->finalrowmarks == NIL);
     495             :     Assert(glob->resultRelations == NIL);
     496             :     Assert(glob->rootResultRelations == NIL);
     497      245762 :     top_plan = set_plan_references(root, top_plan);
     498             :     /* ... and the subplans (both regular subplans and initplans) */
     499             :     Assert(list_length(glob->subplans) == list_length(glob->subroots));
     500      291992 :     forboth(lp, glob->subplans, lr, glob->subroots)
     501             :     {
     502       46230 :         Plan       *subplan = (Plan *) lfirst(lp);
     503       46230 :         PlannerInfo *subroot = lfirst_node(PlannerInfo, lr);
     504             : 
     505       46230 :         lfirst(lp) = set_plan_references(subroot, subplan);
     506             :     }
     507             : 
     508             :     /* build the PlannedStmt result */
     509      245762 :     result = makeNode(PlannedStmt);
     510             : 
     511      245762 :     result->commandType = parse->commandType;
     512      245762 :     result->queryId = parse->queryId;
     513      245762 :     result->hasReturning = (parse->returningList != NIL);
     514      245762 :     result->hasModifyingCTE = parse->hasModifyingCTE;
     515      245762 :     result->canSetTag = parse->canSetTag;
     516      245762 :     result->transientPlan = glob->transientPlan;
     517      245762 :     result->dependsOnRole = glob->dependsOnRole;
     518      245762 :     result->parallelModeNeeded = glob->parallelModeNeeded;
     519      245762 :     result->planTree = top_plan;
     520      245762 :     result->rtable = glob->finalrtable;
     521      245762 :     result->resultRelations = glob->resultRelations;
     522      245762 :     result->rootResultRelations = glob->rootResultRelations;
     523      245762 :     result->subplans = glob->subplans;
     524      245762 :     result->rewindPlanIDs = glob->rewindPlanIDs;
     525      245762 :     result->rowMarks = glob->finalrowmarks;
     526      245762 :     result->relationOids = glob->relationOids;
     527      245762 :     result->invalItems = glob->invalItems;
     528      245762 :     result->paramExecTypes = glob->paramExecTypes;
     529             :     /* utilityStmt should be null, but we might as well copy it */
     530      245762 :     result->utilityStmt = parse->utilityStmt;
     531      245762 :     result->stmt_location = parse->stmt_location;
     532      245762 :     result->stmt_len = parse->stmt_len;
     533             : 
     534      245762 :     result->jitFlags = PGJIT_NONE;
     535      491524 :     if (jit_enabled && jit_above_cost >= 0 &&
     536      245762 :         top_plan->total_cost > jit_above_cost)
     537             :     {
     538         530 :         result->jitFlags |= PGJIT_PERFORM;
     539             : 
     540             :         /*
     541             :          * Decide how much effort should be put into generating better code.
     542             :          */
     543        1060 :         if (jit_optimize_above_cost >= 0 &&
     544         530 :             top_plan->total_cost > jit_optimize_above_cost)
     545         442 :             result->jitFlags |= PGJIT_OPT3;
     546        1060 :         if (jit_inline_above_cost >= 0 &&
     547         530 :             top_plan->total_cost > jit_inline_above_cost)
     548         442 :             result->jitFlags |= PGJIT_INLINE;
     549             : 
     550             :         /*
     551             :          * Decide which operations should be JITed.
     552             :          */
     553         530 :         if (jit_expressions)
     554         530 :             result->jitFlags |= PGJIT_EXPR;
     555         530 :         if (jit_tuple_deforming)
     556         530 :             result->jitFlags |= PGJIT_DEFORM;
     557             :     }
     558             : 
     559      245762 :     if (glob->partition_directory != NULL)
     560        5924 :         DestroyPartitionDirectory(glob->partition_directory);
     561             : 
     562      245762 :     return result;
     563             : }
     564             : 
     565             : 
     566             : /*--------------------
     567             :  * subquery_planner
     568             :  *    Invokes the planner on a subquery.  We recurse to here for each
     569             :  *    sub-SELECT found in the query tree.
     570             :  *
     571             :  * glob is the global state for the current planner run.
     572             :  * parse is the querytree produced by the parser & rewriter.
     573             :  * parent_root is the immediate parent Query's info (NULL at the top level).
     574             :  * hasRecursion is true if this is a recursive WITH query.
     575             :  * tuple_fraction is the fraction of tuples we expect will be retrieved.
     576             :  * tuple_fraction is interpreted as explained for grouping_planner, below.
     577             :  *
     578             :  * Basically, this routine does the stuff that should only be done once
     579             :  * per Query object.  It then calls grouping_planner.  At one time,
     580             :  * grouping_planner could be invoked recursively on the same Query object;
     581             :  * that's not currently true, but we keep the separation between the two
     582             :  * routines anyway, in case we need it again someday.
     583             :  *
     584             :  * subquery_planner will be called recursively to handle sub-Query nodes
     585             :  * found within the query's expressions and rangetable.
     586             :  *
     587             :  * Returns the PlannerInfo struct ("root") that contains all data generated
     588             :  * while planning the subquery.  In particular, the Path(s) attached to
     589             :  * the (UPPERREL_FINAL, NULL) upperrel represent our conclusions about the
     590             :  * cheapest way(s) to implement the query.  The top level will select the
     591             :  * best Path and pass it through createplan.c to produce a finished Plan.
     592             :  *--------------------
     593             :  */
     594             : PlannerInfo *
     595      301564 : subquery_planner(PlannerGlobal *glob, Query *parse,
     596             :                  PlannerInfo *parent_root,
     597             :                  bool hasRecursion, double tuple_fraction)
     598             : {
     599             :     PlannerInfo *root;
     600             :     List       *newWithCheckOptions;
     601             :     List       *newHaving;
     602             :     bool        hasOuterJoins;
     603             :     bool        hasResultRTEs;
     604             :     RelOptInfo *final_rel;
     605             :     ListCell   *l;
     606             : 
     607             :     /* Create a PlannerInfo data structure for this subquery */
     608      301564 :     root = makeNode(PlannerInfo);
     609      301564 :     root->parse = parse;
     610      301564 :     root->glob = glob;
     611      301564 :     root->query_level = parent_root ? parent_root->query_level + 1 : 1;
     612      301564 :     root->parent_root = parent_root;
     613      301564 :     root->plan_params = NIL;
     614      301564 :     root->outer_params = NULL;
     615      301564 :     root->planner_cxt = CurrentMemoryContext;
     616      301564 :     root->init_plans = NIL;
     617      301564 :     root->cte_plan_ids = NIL;
     618      301564 :     root->multiexpr_params = NIL;
     619      301564 :     root->eq_classes = NIL;
     620      301564 :     root->ec_merging_done = false;
     621      301564 :     root->append_rel_list = NIL;
     622      301564 :     root->rowMarks = NIL;
     623      301564 :     memset(root->upper_rels, 0, sizeof(root->upper_rels));
     624      301564 :     memset(root->upper_targets, 0, sizeof(root->upper_targets));
     625      301564 :     root->processed_tlist = NIL;
     626      301564 :     root->grouping_map = NULL;
     627      301564 :     root->minmax_aggs = NIL;
     628      301564 :     root->qual_security_level = 0;
     629      301564 :     root->inhTargetKind = INHKIND_NONE;
     630      301564 :     root->hasRecursion = hasRecursion;
     631      301564 :     if (hasRecursion)
     632         320 :         root->wt_param_id = assign_special_exec_param(root);
     633             :     else
     634      301244 :         root->wt_param_id = -1;
     635      301564 :     root->non_recursive_path = NULL;
     636      301564 :     root->partColsUpdated = false;
     637             : 
     638             :     /*
     639             :      * If there is a WITH list, process each WITH query and either convert it
     640             :      * to RTE_SUBQUERY RTE(s) or build an initplan SubPlan structure for it.
     641             :      */
     642      301564 :     if (parse->cteList)
     643        1170 :         SS_process_ctes(root);
     644             : 
     645             :     /*
     646             :      * If the FROM clause is empty, replace it with a dummy RTE_RESULT RTE, so
     647             :      * that we don't need so many special cases to deal with that situation.
     648             :      */
     649      301564 :     replace_empty_jointree(parse);
     650             : 
     651             :     /*
     652             :      * Look for ANY and EXISTS SubLinks in WHERE and JOIN/ON clauses, and try
     653             :      * to transform them into joins.  Note that this step does not descend
     654             :      * into subqueries; if we pull up any subqueries below, their SubLinks are
     655             :      * processed just before pulling them up.
     656             :      */
     657      301564 :     if (parse->hasSubLinks)
     658       29790 :         pull_up_sublinks(root);
     659             : 
     660             :     /*
     661             :      * Scan the rangetable for function RTEs, do const-simplification on them,
     662             :      * and then inline them if possible (producing subqueries that might get
     663             :      * pulled up next).  Recursion issues here are handled in the same way as
     664             :      * for SubLinks.
     665             :      */
     666      301564 :     preprocess_function_rtes(root);
     667             : 
     668             :     /*
     669             :      * Check to see if any subqueries in the jointree can be merged into this
     670             :      * query.
     671             :      */
     672      301564 :     pull_up_subqueries(root);
     673             : 
     674             :     /*
     675             :      * If this is a simple UNION ALL query, flatten it into an appendrel. We
     676             :      * do this now because it requires applying pull_up_subqueries to the leaf
     677             :      * queries of the UNION ALL, which weren't touched above because they
     678             :      * weren't referenced by the jointree (they will be after we do this).
     679             :      */
     680      301560 :     if (parse->setOperations)
     681        2498 :         flatten_simple_union_all(root);
     682             : 
     683             :     /*
     684             :      * Survey the rangetable to see what kinds of entries are present.  We can
     685             :      * skip some later processing if relevant SQL features are not used; for
     686             :      * example if there are no JOIN RTEs we can avoid the expense of doing
     687             :      * flatten_join_alias_vars().  This must be done after we have finished
     688             :      * adding rangetable entries, of course.  (Note: actually, processing of
     689             :      * inherited or partitioned rels can cause RTEs for their child tables to
     690             :      * get added later; but those must all be RTE_RELATION entries, so they
     691             :      * don't invalidate the conclusions drawn here.)
     692             :      */
     693      301560 :     root->hasJoinRTEs = false;
     694      301560 :     root->hasLateralRTEs = false;
     695      301560 :     hasOuterJoins = false;
     696      301560 :     hasResultRTEs = false;
     697      855858 :     foreach(l, parse->rtable)
     698             :     {
     699      554298 :         RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
     700             : 
     701      554298 :         switch (rte->rtekind)
     702             :         {
     703             :             case RTE_RELATION:
     704      309892 :                 if (rte->inh)
     705             :                 {
     706             :                     /*
     707             :                      * Check to see if the relation actually has any children;
     708             :                      * if not, clear the inh flag so we can treat it as a
     709             :                      * plain base relation.
     710             :                      *
     711             :                      * Note: this could give a false-positive result, if the
     712             :                      * rel once had children but no longer does.  We used to
     713             :                      * be able to clear rte->inh later on when we discovered
     714             :                      * that, but no more; we have to handle such cases as
     715             :                      * full-fledged inheritance.
     716             :                      */
     717      216732 :                     rte->inh = has_subclass(rte->relid);
     718             :                 }
     719      309892 :                 break;
     720             :             case RTE_JOIN:
     721       48068 :                 root->hasJoinRTEs = true;
     722       48068 :                 if (IS_OUTER_JOIN(rte->jointype))
     723       35396 :                     hasOuterJoins = true;
     724       48068 :                 break;
     725             :             case RTE_RESULT:
     726      114234 :                 hasResultRTEs = true;
     727      114234 :                 break;
     728             :             default:
     729             :                 /* No work here for other RTE types */
     730       82104 :                 break;
     731             :         }
     732             : 
     733      554298 :         if (rte->lateral)
     734        1014 :             root->hasLateralRTEs = true;
     735             : 
     736             :         /*
     737             :          * We can also determine the maximum security level required for any
     738             :          * securityQuals now.  Addition of inheritance-child RTEs won't affect
     739             :          * this, because child tables don't have their own securityQuals; see
     740             :          * expand_single_inheritance_child().
     741             :          */
     742      554298 :         if (rte->securityQuals)
     743        1152 :             root->qual_security_level = Max(root->qual_security_level,
     744             :                                             list_length(rte->securityQuals));
     745             :     }
     746             : 
     747             :     /*
     748             :      * Preprocess RowMark information.  We need to do this after subquery
     749             :      * pullup, so that all base relations are present.
     750             :      */
     751      301560 :     preprocess_rowmarks(root);
     752             : 
     753             :     /*
     754             :      * Set hasHavingQual to remember if HAVING clause is present.  Needed
     755             :      * because preprocess_expression will reduce a constant-true condition to
     756             :      * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
     757             :      */
     758      301560 :     root->hasHavingQual = (parse->havingQual != NULL);
     759             : 
     760             :     /* Clear this flag; might get set in distribute_qual_to_rels */
     761      301560 :     root->hasPseudoConstantQuals = false;
     762             : 
     763             :     /*
     764             :      * Do expression preprocessing on targetlist and quals, as well as other
     765             :      * random expressions in the querytree.  Note that we do not need to
     766             :      * handle sort/group expressions explicitly, because they are actually
     767             :      * part of the targetlist.
     768             :      */
     769      300176 :     parse->targetList = (List *)
     770      301560 :         preprocess_expression(root, (Node *) parse->targetList,
     771             :                               EXPRKIND_TARGET);
     772             : 
     773             :     /* Constant-folding might have removed all set-returning functions */
     774      300176 :     if (parse->hasTargetSRFs)
     775        3682 :         parse->hasTargetSRFs = expression_returns_set((Node *) parse->targetList);
     776             : 
     777      300176 :     newWithCheckOptions = NIL;
     778      301330 :     foreach(l, parse->withCheckOptions)
     779             :     {
     780        1154 :         WithCheckOption *wco = lfirst_node(WithCheckOption, l);
     781             : 
     782        1154 :         wco->qual = preprocess_expression(root, wco->qual,
     783             :                                           EXPRKIND_QUAL);
     784        1154 :         if (wco->qual != NULL)
     785         934 :             newWithCheckOptions = lappend(newWithCheckOptions, wco);
     786             :     }
     787      300176 :     parse->withCheckOptions = newWithCheckOptions;
     788             : 
     789      300176 :     parse->returningList = (List *)
     790      300176 :         preprocess_expression(root, (Node *) parse->returningList,
     791             :                               EXPRKIND_TARGET);
     792             : 
     793      300176 :     preprocess_qual_conditions(root, (Node *) parse->jointree);
     794             : 
     795      300176 :     parse->havingQual = preprocess_expression(root, parse->havingQual,
     796             :                                               EXPRKIND_QUAL);
     797             : 
     798      301360 :     foreach(l, parse->windowClause)
     799             :     {
     800        1184 :         WindowClause *wc = lfirst_node(WindowClause, l);
     801             : 
     802             :         /* partitionClause/orderClause are sort/group expressions */
     803        1184 :         wc->startOffset = preprocess_expression(root, wc->startOffset,
     804             :                                                 EXPRKIND_LIMIT);
     805        1184 :         wc->endOffset = preprocess_expression(root, wc->endOffset,
     806             :                                               EXPRKIND_LIMIT);
     807             :     }
     808             : 
     809      300176 :     parse->limitOffset = preprocess_expression(root, parse->limitOffset,
     810             :                                                EXPRKIND_LIMIT);
     811      300176 :     parse->limitCount = preprocess_expression(root, parse->limitCount,
     812             :                                               EXPRKIND_LIMIT);
     813             : 
     814      300176 :     if (parse->onConflict)
     815             :     {
     816        1960 :         parse->onConflict->arbiterElems = (List *)
     817         980 :             preprocess_expression(root,
     818         980 :                                   (Node *) parse->onConflict->arbiterElems,
     819             :                                   EXPRKIND_ARBITER_ELEM);
     820        1960 :         parse->onConflict->arbiterWhere =
     821         980 :             preprocess_expression(root,
     822         980 :                                   parse->onConflict->arbiterWhere,
     823             :                                   EXPRKIND_QUAL);
     824        1960 :         parse->onConflict->onConflictSet = (List *)
     825         980 :             preprocess_expression(root,
     826         980 :                                   (Node *) parse->onConflict->onConflictSet,
     827             :                                   EXPRKIND_TARGET);
     828        1960 :         parse->onConflict->onConflictWhere =
     829         980 :             preprocess_expression(root,
     830         980 :                                   parse->onConflict->onConflictWhere,
     831             :                                   EXPRKIND_QUAL);
     832             :         /* exclRelTlist contains only Vars, so no preprocessing needed */
     833             :     }
     834             : 
     835      300176 :     root->append_rel_list = (List *)
     836      300176 :         preprocess_expression(root, (Node *) root->append_rel_list,
     837             :                               EXPRKIND_APPINFO);
     838             : 
     839             :     /* Also need to preprocess expressions within RTEs */
     840      852964 :     foreach(l, parse->rtable)
     841             :     {
     842      552788 :         RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
     843             :         int         kind;
     844             :         ListCell   *lcsq;
     845             : 
     846      552788 :         if (rte->rtekind == RTE_RELATION)
     847             :         {
     848      309762 :             if (rte->tablesample)
     849         152 :                 rte->tablesample = (TableSampleClause *)
     850         152 :                     preprocess_expression(root,
     851         152 :                                           (Node *) rte->tablesample,
     852             :                                           EXPRKIND_TABLESAMPLE);
     853             :         }
     854      243026 :         else if (rte->rtekind == RTE_SUBQUERY)
     855             :         {
     856             :             /*
     857             :              * We don't want to do all preprocessing yet on the subquery's
     858             :              * expressions, since that will happen when we plan it.  But if it
     859             :              * contains any join aliases of our level, those have to get
     860             :              * expanded now, because planning of the subquery won't do it.
     861             :              * That's only possible if the subquery is LATERAL.
     862             :              */
     863       48102 :             if (rte->lateral && root->hasJoinRTEs)
     864         316 :                 rte->subquery = (Query *)
     865         316 :                     flatten_join_alias_vars(root->parse,
     866         316 :                                             (Node *) rte->subquery);
     867             :         }
     868      194924 :         else if (rte->rtekind == RTE_FUNCTION)
     869             :         {
     870             :             /* Preprocess the function expression(s) fully */
     871       28658 :             kind = rte->lateral ? EXPRKIND_RTFUNC_LATERAL : EXPRKIND_RTFUNC;
     872       28658 :             rte->functions = (List *)
     873       28658 :                 preprocess_expression(root, (Node *) rte->functions, kind);
     874             :         }
     875      166266 :         else if (rte->rtekind == RTE_TABLEFUNC)
     876             :         {
     877             :             /* Preprocess the function expression(s) fully */
     878         144 :             kind = rte->lateral ? EXPRKIND_TABLEFUNC_LATERAL : EXPRKIND_TABLEFUNC;
     879         144 :             rte->tablefunc = (TableFunc *)
     880         144 :                 preprocess_expression(root, (Node *) rte->tablefunc, kind);
     881             :         }
     882      166122 :         else if (rte->rtekind == RTE_VALUES)
     883             :         {
     884             :             /* Preprocess the values lists fully */
     885        3784 :             kind = rte->lateral ? EXPRKIND_VALUES_LATERAL : EXPRKIND_VALUES;
     886        3784 :             rte->values_lists = (List *)
     887        3784 :                 preprocess_expression(root, (Node *) rte->values_lists, kind);
     888             :         }
     889             : 
     890             :         /*
     891             :          * Process each element of the securityQuals list as if it were a
     892             :          * separate qual expression (as indeed it is).  We need to do it this
     893             :          * way to get proper canonicalization of AND/OR structure.  Note that
     894             :          * this converts each element into an implicit-AND sublist.
     895             :          */
     896      554096 :         foreach(lcsq, rte->securityQuals)
     897             :         {
     898        1308 :             lfirst(lcsq) = preprocess_expression(root,
     899        1308 :                                                  (Node *) lfirst(lcsq),
     900             :                                                  EXPRKIND_QUAL);
     901             :         }
     902             :     }
     903             : 
     904             :     /*
     905             :      * Now that we are done preprocessing expressions, and in particular done
     906             :      * flattening join alias variables, get rid of the joinaliasvars lists.
     907             :      * They no longer match what expressions in the rest of the tree look
     908             :      * like, because we have not preprocessed expressions in those lists (and
     909             :      * do not want to; for example, expanding a SubLink there would result in
     910             :      * a useless unreferenced subplan).  Leaving them in place simply creates
     911             :      * a hazard for later scans of the tree.  We could try to prevent that by
     912             :      * using QTW_IGNORE_JOINALIASES in every tree scan done after this point,
     913             :      * but that doesn't sound very reliable.
     914             :      */
     915      300176 :     if (root->hasJoinRTEs)
     916             :     {
     917      208030 :         foreach(l, parse->rtable)
     918             :         {
     919      172102 :             RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
     920             : 
     921      172102 :             rte->joinaliasvars = NIL;
     922             :         }
     923             :     }
     924             : 
     925             :     /*
     926             :      * In some cases we may want to transfer a HAVING clause into WHERE. We
     927             :      * cannot do so if the HAVING clause contains aggregates (obviously) or
     928             :      * volatile functions (since a HAVING clause is supposed to be executed
     929             :      * only once per group).  We also can't do this if there are any nonempty
     930             :      * grouping sets; moving such a clause into WHERE would potentially change
     931             :      * the results, if any referenced column isn't present in all the grouping
     932             :      * sets.  (If there are only empty grouping sets, then the HAVING clause
     933             :      * must be degenerate as discussed below.)
     934             :      *
     935             :      * Also, it may be that the clause is so expensive to execute that we're
     936             :      * better off doing it only once per group, despite the loss of
     937             :      * selectivity.  This is hard to estimate short of doing the entire
     938             :      * planning process twice, so we use a heuristic: clauses containing
     939             :      * subplans are left in HAVING.  Otherwise, we move or copy the HAVING
     940             :      * clause into WHERE, in hopes of eliminating tuples before aggregation
     941             :      * instead of after.
     942             :      *
     943             :      * If the query has explicit grouping then we can simply move such a
     944             :      * clause into WHERE; any group that fails the clause will not be in the
     945             :      * output because none of its tuples will reach the grouping or
     946             :      * aggregation stage.  Otherwise we must have a degenerate (variable-free)
     947             :      * HAVING clause, which we put in WHERE so that query_planner() can use it
     948             :      * in a gating Result node, but also keep in HAVING to ensure that we
     949             :      * don't emit a bogus aggregated row. (This could be done better, but it
     950             :      * seems not worth optimizing.)
     951             :      *
     952             :      * Note that both havingQual and parse->jointree->quals are in
     953             :      * implicitly-ANDed-list form at this point, even though they are declared
     954             :      * as Node *.
     955             :      */
     956      300176 :     newHaving = NIL;
     957      300630 :     foreach(l, (List *) parse->havingQual)
     958             :     {
     959         454 :         Node       *havingclause = (Node *) lfirst(l);
     960             : 
     961         880 :         if ((parse->groupClause && parse->groupingSets) ||
     962         542 :             contain_agg_clause(havingclause) ||
     963         232 :             contain_volatile_functions(havingclause) ||
     964         116 :             contain_subplans(havingclause))
     965             :         {
     966             :             /* keep it in HAVING */
     967         338 :             newHaving = lappend(newHaving, havingclause);
     968             :         }
     969         116 :         else if (parse->groupClause && !parse->groupingSets)
     970             :         {
     971             :             /* move it to WHERE */
     972         208 :             parse->jointree->quals = (Node *)
     973         104 :                 lappend((List *) parse->jointree->quals, havingclause);
     974             :         }
     975             :         else
     976             :         {
     977             :             /* put a copy in WHERE, keep it in HAVING */
     978          24 :             parse->jointree->quals = (Node *)
     979          12 :                 lappend((List *) parse->jointree->quals,
     980             :                         copyObject(havingclause));
     981          12 :             newHaving = lappend(newHaving, havingclause);
     982             :         }
     983             :     }
     984      300176 :     parse->havingQual = (Node *) newHaving;
     985             : 
     986             :     /* Remove any redundant GROUP BY columns */
     987      300176 :     remove_useless_groupby_columns(root);
     988             : 
     989             :     /*
     990             :      * If we have any outer joins, try to reduce them to plain inner joins.
     991             :      * This step is most easily done after we've done expression
     992             :      * preprocessing.
     993             :      */
     994      300176 :     if (hasOuterJoins)
     995       30202 :         reduce_outer_joins(root);
     996             : 
     997             :     /*
     998             :      * If we have any RTE_RESULT relations, see if they can be deleted from
     999             :      * the jointree.  This step is most effectively done after we've done
    1000             :      * expression preprocessing and outer join reduction.
    1001             :      */
    1002      300176 :     if (hasResultRTEs)
    1003      112658 :         remove_useless_result_rtes(root);
    1004             : 
    1005             :     /*
    1006             :      * Do the main planning.  If we have an inherited target relation, that
    1007             :      * needs special processing, else go straight to grouping_planner.
    1008             :      */
    1009      369568 :     if (parse->resultRelation &&
    1010       69392 :         rt_fetch(parse->resultRelation, parse->rtable)->inh)
    1011        1224 :         inheritance_planner(root);
    1012             :     else
    1013      298952 :         grouping_planner(root, false, tuple_fraction);
    1014             : 
    1015             :     /*
    1016             :      * Capture the set of outer-level param IDs we have access to, for use in
    1017             :      * extParam/allParam calculations later.
    1018             :      */
    1019      300158 :     SS_identify_outer_params(root);
    1020             : 
    1021             :     /*
    1022             :      * If any initPlans were created in this query level, adjust the surviving
    1023             :      * Paths' costs and parallel-safety flags to account for them.  The
    1024             :      * initPlans won't actually get attached to the plan tree till
    1025             :      * create_plan() runs, but we must include their effects now.
    1026             :      */
    1027      300158 :     final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
    1028      300158 :     SS_charge_for_initplans(root, final_rel);
    1029             : 
    1030             :     /*
    1031             :      * Make sure we've identified the cheapest Path for the final rel.  (By
    1032             :      * doing this here not in grouping_planner, we include initPlan costs in
    1033             :      * the decision, though it's unlikely that will change anything.)
    1034             :      */
    1035      300158 :     set_cheapest(final_rel);
    1036             : 
    1037      300158 :     return root;
    1038             : }
    1039             : 
    1040             : /*
    1041             :  * preprocess_expression
    1042             :  *      Do subquery_planner's preprocessing work for an expression,
    1043             :  *      which can be a targetlist, a WHERE clause (including JOIN/ON
    1044             :  *      conditions), a HAVING clause, or a few other things.
    1045             :  */
    1046             : static Node *
    1047     2214014 : preprocess_expression(PlannerInfo *root, Node *expr, int kind)
    1048             : {
    1049             :     /*
    1050             :      * Fall out quickly if expression is empty.  This occurs often enough to
    1051             :      * be worth checking.  Note that null->null is the correct conversion for
    1052             :      * implicit-AND result format, too.
    1053             :      */
    1054     2214014 :     if (expr == NULL)
    1055     1689252 :         return NULL;
    1056             : 
    1057             :     /*
    1058             :      * If the query has any join RTEs, replace join alias variables with
    1059             :      * base-relation variables.  We must do this first, since any expressions
    1060             :      * we may extract from the joinaliasvars lists have not been preprocessed.
    1061             :      * For example, if we did this after sublink processing, sublinks expanded
    1062             :      * out from join aliases would not get processed.  But we can skip this in
    1063             :      * non-lateral RTE functions, VALUES lists, and TABLESAMPLE clauses, since
    1064             :      * they can't contain any Vars of the current query level.
    1065             :      */
    1066      524762 :     if (root->hasJoinRTEs &&
    1067      234528 :         !(kind == EXPRKIND_RTFUNC ||
    1068      117174 :           kind == EXPRKIND_VALUES ||
    1069             :           kind == EXPRKIND_TABLESAMPLE ||
    1070             :           kind == EXPRKIND_TABLEFUNC))
    1071      117174 :         expr = flatten_join_alias_vars(root->parse, expr);
    1072             : 
    1073             :     /*
    1074             :      * Simplify constant expressions.  For function RTEs, this was already
    1075             :      * done by preprocess_function_rtes ... but we have to do it again if the
    1076             :      * RTE is LATERAL and might have contained join alias variables.
    1077             :      *
    1078             :      * Note: an essential effect of this is to convert named-argument function
    1079             :      * calls to positional notation and insert the current actual values of
    1080             :      * any default arguments for functions.  To ensure that happens, we *must*
    1081             :      * process all expressions here.  Previous PG versions sometimes skipped
    1082             :      * const-simplification if it didn't seem worth the trouble, but we can't
    1083             :      * do that anymore.
    1084             :      *
    1085             :      * Note: this also flattens nested AND and OR expressions into N-argument
    1086             :      * form.  All processing of a qual expression after this point must be
    1087             :      * careful to maintain AND/OR flatness --- that is, do not generate a tree
    1088             :      * with AND directly under AND, nor OR directly under OR.
    1089             :      */
    1090      524762 :     if (!(kind == EXPRKIND_RTFUNC ||
    1091         346 :           (kind == EXPRKIND_RTFUNC_LATERAL && !root->hasJoinRTEs)))
    1092      496214 :         expr = eval_const_expressions(root, expr);
    1093             : 
    1094             :     /*
    1095             :      * If it's a qual or havingQual, canonicalize it.
    1096             :      */
    1097      523378 :     if (kind == EXPRKIND_QUAL)
    1098             :     {
    1099      185890 :         expr = (Node *) canonicalize_qual((Expr *) expr, false);
    1100             : 
    1101             : #ifdef OPTIMIZER_DEBUG
    1102             :         printf("After canonicalize_qual()\n");
    1103             :         pprint(expr);
    1104             : #endif
    1105             :     }
    1106             : 
    1107             :     /* Expand SubLinks to SubPlans */
    1108      523378 :     if (root->parse->hasSubLinks)
    1109      104108 :         expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
    1110             : 
    1111             :     /*
    1112             :      * XXX do not insert anything here unless you have grokked the comments in
    1113             :      * SS_replace_correlation_vars ...
    1114             :      */
    1115             : 
    1116             :     /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
    1117      523378 :     if (root->query_level > 1)
    1118      128076 :         expr = SS_replace_correlation_vars(root, expr);
    1119             : 
    1120             :     /*
    1121             :      * If it's a qual or havingQual, convert it to implicit-AND format. (We
    1122             :      * don't want to do this before eval_const_expressions, since the latter
    1123             :      * would be unable to simplify a top-level AND correctly. Also,
    1124             :      * SS_process_sublinks expects explicit-AND format.)
    1125             :      */
    1126      523378 :     if (kind == EXPRKIND_QUAL)
    1127      185890 :         expr = (Node *) make_ands_implicit((Expr *) expr);
    1128             : 
    1129      523378 :     return expr;
    1130             : }
    1131             : 
    1132             : /*
    1133             :  * preprocess_qual_conditions
    1134             :  *      Recursively scan the query's jointree and do subquery_planner's
    1135             :  *      preprocessing work on each qual condition found therein.
    1136             :  */
    1137             : static void
    1138      740764 : preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
    1139             : {
    1140      740764 :     if (jtnode == NULL)
    1141           0 :         return;
    1142      740764 :     if (IsA(jtnode, RangeTblRef))
    1143             :     {
    1144             :         /* nothing to do here */
    1145             :     }
    1146      370062 :     else if (IsA(jtnode, FromExpr))
    1147             :     {
    1148      313806 :         FromExpr   *f = (FromExpr *) jtnode;
    1149             :         ListCell   *l;
    1150             : 
    1151      641882 :         foreach(l, f->fromlist)
    1152      328076 :             preprocess_qual_conditions(root, lfirst(l));
    1153             : 
    1154      313806 :         f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
    1155             :     }
    1156       56256 :     else if (IsA(jtnode, JoinExpr))
    1157             :     {
    1158       56256 :         JoinExpr   *j = (JoinExpr *) jtnode;
    1159             : 
    1160       56256 :         preprocess_qual_conditions(root, j->larg);
    1161       56256 :         preprocess_qual_conditions(root, j->rarg);
    1162             : 
    1163       56256 :         j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
    1164             :     }
    1165             :     else
    1166           0 :         elog(ERROR, "unrecognized node type: %d",
    1167             :              (int) nodeTag(jtnode));
    1168             : }
    1169             : 
    1170             : /*
    1171             :  * preprocess_phv_expression
    1172             :  *    Do preprocessing on a PlaceHolderVar expression that's been pulled up.
    1173             :  *
    1174             :  * If a LATERAL subquery references an output of another subquery, and that
    1175             :  * output must be wrapped in a PlaceHolderVar because of an intermediate outer
    1176             :  * join, then we'll push the PlaceHolderVar expression down into the subquery
    1177             :  * and later pull it back up during find_lateral_references, which runs after
    1178             :  * subquery_planner has preprocessed all the expressions that were in the
    1179             :  * current query level to start with.  So we need to preprocess it then.
    1180             :  */
    1181             : Expr *
    1182          24 : preprocess_phv_expression(PlannerInfo *root, Expr *expr)
    1183             : {
    1184          24 :     return (Expr *) preprocess_expression(root, (Node *) expr, EXPRKIND_PHV);
    1185             : }
    1186             : 
    1187             : /*
    1188             :  * inheritance_planner
    1189             :  *    Generate Paths in the case where the result relation is an
    1190             :  *    inheritance set.
    1191             :  *
    1192             :  * We have to handle this case differently from cases where a source relation
    1193             :  * is an inheritance set. Source inheritance is expanded at the bottom of the
    1194             :  * plan tree (see allpaths.c), but target inheritance has to be expanded at
    1195             :  * the top.  The reason is that for UPDATE, each target relation needs a
    1196             :  * different targetlist matching its own column set.  Fortunately,
    1197             :  * the UPDATE/DELETE target can never be the nullable side of an outer join,
    1198             :  * so it's OK to generate the plan this way.
    1199             :  *
    1200             :  * Returns nothing; the useful output is in the Paths we attach to
    1201             :  * the (UPPERREL_FINAL, NULL) upperrel stored in *root.
    1202             :  *
    1203             :  * Note that we have not done set_cheapest() on the final rel; it's convenient
    1204             :  * to leave this to the caller.
    1205             :  */
    1206             : static void
    1207        1224 : inheritance_planner(PlannerInfo *root)
    1208             : {
    1209        1224 :     Query      *parse = root->parse;
    1210        1224 :     int         top_parentRTindex = parse->resultRelation;
    1211             :     List       *select_rtable;
    1212             :     List       *select_appinfos;
    1213             :     List       *child_appinfos;
    1214             :     List       *old_child_rtis;
    1215             :     List       *new_child_rtis;
    1216             :     Bitmapset  *subqueryRTindexes;
    1217             :     Index       next_subquery_rti;
    1218        1224 :     int         nominalRelation = -1;
    1219        1224 :     Index       rootRelation = 0;
    1220        1224 :     List       *final_rtable = NIL;
    1221        1224 :     List       *final_rowmarks = NIL;
    1222        1224 :     int         save_rel_array_size = 0;
    1223        1224 :     RelOptInfo **save_rel_array = NULL;
    1224        1224 :     AppendRelInfo **save_append_rel_array = NULL;
    1225        1224 :     List       *subpaths = NIL;
    1226        1224 :     List       *subroots = NIL;
    1227        1224 :     List       *resultRelations = NIL;
    1228        1224 :     List       *withCheckOptionLists = NIL;
    1229        1224 :     List       *returningLists = NIL;
    1230             :     List       *rowMarks;
    1231             :     RelOptInfo *final_rel;
    1232             :     ListCell   *lc;
    1233             :     ListCell   *lc2;
    1234             :     Index       rti;
    1235             :     RangeTblEntry *parent_rte;
    1236             :     Bitmapset  *parent_relids;
    1237             :     Query     **parent_parses;
    1238             : 
    1239             :     /* Should only get here for UPDATE or DELETE */
    1240             :     Assert(parse->commandType == CMD_UPDATE ||
    1241             :            parse->commandType == CMD_DELETE);
    1242             : 
    1243             :     /*
    1244             :      * We generate a modified instance of the original Query for each target
    1245             :      * relation, plan that, and put all the plans into a list that will be
    1246             :      * controlled by a single ModifyTable node.  All the instances share the
    1247             :      * same rangetable, but each instance must have its own set of subquery
    1248             :      * RTEs within the finished rangetable because (1) they are likely to get
    1249             :      * scribbled on during planning, and (2) it's not inconceivable that
    1250             :      * subqueries could get planned differently in different cases.  We need
    1251             :      * not create duplicate copies of other RTE kinds, in particular not the
    1252             :      * target relations, because they don't have either of those issues.  Not
    1253             :      * having to duplicate the target relations is important because doing so
    1254             :      * (1) would result in a rangetable of length O(N^2) for N targets, with
    1255             :      * at least O(N^3) work expended here; and (2) would greatly complicate
    1256             :      * management of the rowMarks list.
    1257             :      *
    1258             :      * To begin with, generate a bitmapset of the relids of the subquery RTEs.
    1259             :      */
    1260        1224 :     subqueryRTindexes = NULL;
    1261        1224 :     rti = 1;
    1262        2872 :     foreach(lc, parse->rtable)
    1263             :     {
    1264        1648 :         RangeTblEntry *rte = lfirst_node(RangeTblEntry, lc);
    1265             : 
    1266        1648 :         if (rte->rtekind == RTE_SUBQUERY)
    1267         116 :             subqueryRTindexes = bms_add_member(subqueryRTindexes, rti);
    1268        1648 :         rti++;
    1269             :     }
    1270             : 
    1271             :     /*
    1272             :      * If the parent RTE is a partitioned table, we should use that as the
    1273             :      * nominal target relation, because the RTEs added for partitioned tables
    1274             :      * (including the root parent) as child members of the inheritance set do
    1275             :      * not appear anywhere else in the plan, so the confusion explained below
    1276             :      * for non-partitioning inheritance cases is not possible.
    1277             :      */
    1278        1224 :     parent_rte = rt_fetch(top_parentRTindex, parse->rtable);
    1279             :     Assert(parent_rte->inh);
    1280        1224 :     if (parent_rte->relkind == RELKIND_PARTITIONED_TABLE)
    1281             :     {
    1282         850 :         nominalRelation = top_parentRTindex;
    1283         850 :         rootRelation = top_parentRTindex;
    1284             :     }
    1285             : 
    1286             :     /*
    1287             :      * Before generating the real per-child-relation plans, do a cycle of
    1288             :      * planning as though the query were a SELECT.  The objective here is to
    1289             :      * find out which child relations need to be processed, using the same
    1290             :      * expansion and pruning logic as for a SELECT.  We'll then pull out the
    1291             :      * RangeTblEntry-s generated for the child rels, and make use of the
    1292             :      * AppendRelInfo entries for them to guide the real planning.  (This is
    1293             :      * rather inefficient; we could perhaps stop short of making a full Path
    1294             :      * tree.  But this whole function is inefficient and slated for
    1295             :      * destruction, so let's not contort query_planner for that.)
    1296             :      */
    1297             :     {
    1298             :         PlannerInfo *subroot;
    1299             : 
    1300             :         /*
    1301             :          * Flat-copy the PlannerInfo to prevent modification of the original.
    1302             :          */
    1303        1224 :         subroot = makeNode(PlannerInfo);
    1304        1224 :         memcpy(subroot, root, sizeof(PlannerInfo));
    1305             : 
    1306             :         /*
    1307             :          * Make a deep copy of the parsetree for this planning cycle to mess
    1308             :          * around with, and change it to look like a SELECT.  (Hack alert: the
    1309             :          * target RTE still has updatedCols set if this is an UPDATE, so that
    1310             :          * expand_partitioned_rtentry will correctly update
    1311             :          * subroot->partColsUpdated.)
    1312             :          */
    1313        1224 :         subroot->parse = copyObject(root->parse);
    1314             : 
    1315        1224 :         subroot->parse->commandType = CMD_SELECT;
    1316        1224 :         subroot->parse->resultRelation = 0;
    1317             : 
    1318             :         /*
    1319             :          * Ensure the subroot has its own copy of the original
    1320             :          * append_rel_list, since it'll be scribbled on.  (Note that at this
    1321             :          * point, the list only contains AppendRelInfos for flattened UNION
    1322             :          * ALL subqueries.)
    1323             :          */
    1324        1224 :         subroot->append_rel_list = copyObject(root->append_rel_list);
    1325             : 
    1326             :         /*
    1327             :          * Better make a private copy of the rowMarks, too.
    1328             :          */
    1329        1224 :         subroot->rowMarks = copyObject(root->rowMarks);
    1330             : 
    1331             :         /* There shouldn't be any OJ info to translate, as yet */
    1332             :         Assert(subroot->join_info_list == NIL);
    1333             :         /* and we haven't created PlaceHolderInfos, either */
    1334             :         Assert(subroot->placeholder_list == NIL);
    1335             : 
    1336             :         /* Generate Path(s) for accessing this result relation */
    1337        1224 :         grouping_planner(subroot, true, 0.0 /* retrieve all tuples */ );
    1338             : 
    1339             :         /* Extract the info we need. */
    1340        1224 :         select_rtable = subroot->parse->rtable;
    1341        1224 :         select_appinfos = subroot->append_rel_list;
    1342             : 
    1343             :         /*
    1344             :          * We need to propagate partColsUpdated back, too.  (The later
    1345             :          * planning cycles will not set this because they won't run
    1346             :          * expand_partitioned_rtentry for the UPDATE target.)
    1347             :          */
    1348        1224 :         root->partColsUpdated = subroot->partColsUpdated;
    1349             :     }
    1350             : 
    1351             :     /*----------
    1352             :      * Since only one rangetable can exist in the final plan, we need to make
    1353             :      * sure that it contains all the RTEs needed for any child plan.  This is
    1354             :      * complicated by the need to use separate subquery RTEs for each child.
    1355             :      * We arrange the final rtable as follows:
    1356             :      * 1. All original rtable entries (with their original RT indexes).
    1357             :      * 2. All the relation RTEs generated for children of the target table.
    1358             :      * 3. Subquery RTEs for children after the first.  We need N * (K - 1)
    1359             :      *    RT slots for this, if there are N subqueries and K child tables.
    1360             :      * 4. Additional RTEs generated during the child planning runs, such as
    1361             :      *    children of inheritable RTEs other than the target table.
    1362             :      * We assume that each child planning run will create an identical set
    1363             :      * of type-4 RTEs.
    1364             :      *
    1365             :      * So the next thing to do is append the type-2 RTEs (the target table's
    1366             :      * children) to the original rtable.  We look through select_appinfos
    1367             :      * to find them.
    1368             :      *
    1369             :      * To identify which AppendRelInfos are relevant as we thumb through
    1370             :      * select_appinfos, we need to look for both direct and indirect children
    1371             :      * of top_parentRTindex, so we use a bitmap of known parent relids.
    1372             :      * expand_inherited_rtentry() always processes a parent before any of that
    1373             :      * parent's children, so we should see an intermediate parent before its
    1374             :      * children.
    1375             :      *----------
    1376             :      */
    1377        1224 :     child_appinfos = NIL;
    1378        1224 :     old_child_rtis = NIL;
    1379        1224 :     new_child_rtis = NIL;
    1380        1224 :     parent_relids = bms_make_singleton(top_parentRTindex);
    1381        4154 :     foreach(lc, select_appinfos)
    1382             :     {
    1383        2930 :         AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
    1384             :         RangeTblEntry *child_rte;
    1385             : 
    1386             :         /* append_rel_list contains all append rels; ignore others */
    1387        2930 :         if (!bms_is_member(appinfo->parent_relid, parent_relids))
    1388         224 :             continue;
    1389             : 
    1390             :         /* remember relevant AppendRelInfos for use below */
    1391        2706 :         child_appinfos = lappend(child_appinfos, appinfo);
    1392             : 
    1393             :         /* extract RTE for this child rel */
    1394        2706 :         child_rte = rt_fetch(appinfo->child_relid, select_rtable);
    1395             : 
    1396             :         /* and append it to the original rtable */
    1397        2706 :         parse->rtable = lappend(parse->rtable, child_rte);
    1398             : 
    1399             :         /* remember child's index in the SELECT rtable */
    1400        2706 :         old_child_rtis = lappend_int(old_child_rtis, appinfo->child_relid);
    1401             : 
    1402             :         /* and its new index in the final rtable */
    1403        2706 :         new_child_rtis = lappend_int(new_child_rtis, list_length(parse->rtable));
    1404             : 
    1405             :         /* if child is itself partitioned, update parent_relids */
    1406        2706 :         if (child_rte->inh)
    1407             :         {
    1408             :             Assert(child_rte->relkind == RELKIND_PARTITIONED_TABLE);
    1409         284 :             parent_relids = bms_add_member(parent_relids, appinfo->child_relid);
    1410             :         }
    1411             :     }
    1412             : 
    1413             :     /*
    1414             :      * It's possible that the RTIs we just assigned for the child rels in the
    1415             :      * final rtable are different from what they were in the SELECT query.
    1416             :      * Adjust the AppendRelInfos so that they will correctly map RT indexes to
    1417             :      * the final indexes.  We can do this left-to-right since no child rel's
    1418             :      * final RT index could be greater than what it had in the SELECT query.
    1419             :      */
    1420        3930 :     forboth(lc, old_child_rtis, lc2, new_child_rtis)
    1421             :     {
    1422        2706 :         int         old_child_rti = lfirst_int(lc);
    1423        2706 :         int         new_child_rti = lfirst_int(lc2);
    1424             : 
    1425        2706 :         if (old_child_rti == new_child_rti)
    1426        2690 :             continue;           /* nothing to do */
    1427             : 
    1428             :         Assert(old_child_rti > new_child_rti);
    1429             : 
    1430          16 :         ChangeVarNodes((Node *) child_appinfos,
    1431             :                        old_child_rti, new_child_rti, 0);
    1432             :     }
    1433             : 
    1434             :     /*
    1435             :      * Now set up rangetable entries for subqueries for additional children
    1436             :      * (the first child will just use the original ones).  These all have to
    1437             :      * look more or less real, or EXPLAIN will get unhappy; so we just make
    1438             :      * them all clones of the original subqueries.
    1439             :      */
    1440        1224 :     next_subquery_rti = list_length(parse->rtable) + 1;
    1441        1224 :     if (subqueryRTindexes != NULL)
    1442             :     {
    1443          76 :         int         n_children = list_length(child_appinfos);
    1444             : 
    1445         284 :         while (n_children-- > 1)
    1446             :         {
    1447         132 :             int         oldrti = -1;
    1448             : 
    1449         476 :             while ((oldrti = bms_next_member(subqueryRTindexes, oldrti)) >= 0)
    1450             :             {
    1451             :                 RangeTblEntry *subqrte;
    1452             : 
    1453         212 :                 subqrte = rt_fetch(oldrti, parse->rtable);
    1454         212 :                 parse->rtable = lappend(parse->rtable, copyObject(subqrte));
    1455             :             }
    1456             :         }
    1457             :     }
    1458             : 
    1459             :     /*
    1460             :      * The query for each child is obtained by translating the query for its
    1461             :      * immediate parent, since the AppendRelInfo data we have shows deltas
    1462             :      * between parents and children.  We use the parent_parses array to
    1463             :      * remember the appropriate query trees.  This is indexed by parent relid.
    1464             :      * Since the maximum number of parents is limited by the number of RTEs in
    1465             :      * the SELECT query, we use that number to allocate the array.  An extra
    1466             :      * entry is needed since relids start from 1.
    1467             :      */
    1468        1224 :     parent_parses = (Query **) palloc0((list_length(select_rtable) + 1) *
    1469             :                                        sizeof(Query *));
    1470        1224 :     parent_parses[top_parentRTindex] = parse;
    1471             : 
    1472             :     /*
    1473             :      * And now we can get on with generating a plan for each child table.
    1474             :      */
    1475        3930 :     foreach(lc, child_appinfos)
    1476             :     {
    1477        2706 :         AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
    1478        2706 :         Index       this_subquery_rti = next_subquery_rti;
    1479             :         Query      *parent_parse;
    1480             :         PlannerInfo *subroot;
    1481             :         RangeTblEntry *child_rte;
    1482             :         RelOptInfo *sub_final_rel;
    1483             :         Path       *subpath;
    1484             : 
    1485             :         /*
    1486             :          * expand_inherited_rtentry() always processes a parent before any of
    1487             :          * that parent's children, so the parent query for this relation
    1488             :          * should already be available.
    1489             :          */
    1490        2706 :         parent_parse = parent_parses[appinfo->parent_relid];
    1491             :         Assert(parent_parse != NULL);
    1492             : 
    1493             :         /*
    1494             :          * We need a working copy of the PlannerInfo so that we can control
    1495             :          * propagation of information back to the main copy.
    1496             :          */
    1497        2706 :         subroot = makeNode(PlannerInfo);
    1498        2706 :         memcpy(subroot, root, sizeof(PlannerInfo));
    1499             : 
    1500             :         /*
    1501             :          * Generate modified query with this rel as target.  We first apply
    1502             :          * adjust_appendrel_attrs, which copies the Query and changes
    1503             :          * references to the parent RTE to refer to the current child RTE,
    1504             :          * then fool around with subquery RTEs.
    1505             :          */
    1506        2706 :         subroot->parse = (Query *)
    1507        2706 :             adjust_appendrel_attrs(subroot,
    1508             :                                    (Node *) parent_parse,
    1509             :                                    1, &appinfo);
    1510             : 
    1511             :         /*
    1512             :          * If there are securityQuals attached to the parent, move them to the
    1513             :          * child rel (they've already been transformed properly for that).
    1514             :          */
    1515        2706 :         parent_rte = rt_fetch(appinfo->parent_relid, subroot->parse->rtable);
    1516        2706 :         child_rte = rt_fetch(appinfo->child_relid, subroot->parse->rtable);
    1517        2706 :         child_rte->securityQuals = parent_rte->securityQuals;
    1518        2706 :         parent_rte->securityQuals = NIL;
    1519             : 
    1520             :         /*
    1521             :          * HACK: setting this to a value other than INHKIND_NONE signals to
    1522             :          * relation_excluded_by_constraints() to treat the result relation as
    1523             :          * being an appendrel member.
    1524             :          */
    1525        2706 :         subroot->inhTargetKind =
    1526        2706 :             (rootRelation != 0) ? INHKIND_PARTITIONED : INHKIND_INHERITED;
    1527             : 
    1528             :         /*
    1529             :          * If this child is further partitioned, remember it as a parent.
    1530             :          * Since a partitioned table does not have any data, we don't need to
    1531             :          * create a plan for it, and we can stop processing it here.  We do,
    1532             :          * however, need to remember its modified PlannerInfo for use when
    1533             :          * processing its children, since we'll update their varnos based on
    1534             :          * the delta from immediate parent to child, not from top to child.
    1535             :          *
    1536             :          * Note: a very non-obvious point is that we have not yet added
    1537             :          * duplicate subquery RTEs to the subroot's rtable.  We mustn't,
    1538             :          * because then its children would have two sets of duplicates,
    1539             :          * confusing matters.
    1540             :          */
    1541        2706 :         if (child_rte->inh)
    1542             :         {
    1543             :             Assert(child_rte->relkind == RELKIND_PARTITIONED_TABLE);
    1544         284 :             parent_parses[appinfo->child_relid] = subroot->parse;
    1545         628 :             continue;
    1546             :         }
    1547             : 
    1548             :         /*
    1549             :          * Set the nominal target relation of the ModifyTable node if not
    1550             :          * already done.  If the target is a partitioned table, we already set
    1551             :          * nominalRelation to refer to the partition root, above.  For
    1552             :          * non-partitioned inheritance cases, we'll use the first child
    1553             :          * relation (even if it's excluded) as the nominal target relation.
    1554             :          * Because of the way expand_inherited_rtentry works, that should be
    1555             :          * the RTE representing the parent table in its role as a simple
    1556             :          * member of the inheritance set.
    1557             :          *
    1558             :          * It would be logically cleaner to *always* use the inheritance
    1559             :          * parent RTE as the nominal relation; but that RTE is not otherwise
    1560             :          * referenced in the plan in the non-partitioned inheritance case.
    1561             :          * Instead the duplicate child RTE created by expand_inherited_rtentry
    1562             :          * is used elsewhere in the plan, so using the original parent RTE
    1563             :          * would give rise to confusing use of multiple aliases in EXPLAIN
    1564             :          * output for what the user will think is the "same" table.  OTOH,
    1565             :          * it's not a problem in the partitioned inheritance case, because
    1566             :          * there is no duplicate RTE for the parent.
    1567             :          */
    1568        2422 :         if (nominalRelation < 0)
    1569         374 :             nominalRelation = appinfo->child_relid;
    1570             : 
    1571             :         /*
    1572             :          * As above, each child plan run needs its own append_rel_list and
    1573             :          * rowmarks, which should start out as pristine copies of the
    1574             :          * originals.  There can't be any references to UPDATE/DELETE target
    1575             :          * rels in them; but there could be subquery references, which we'll
    1576             :          * fix up in a moment.
    1577             :          */
    1578        2422 :         subroot->append_rel_list = copyObject(root->append_rel_list);
    1579        2422 :         subroot->rowMarks = copyObject(root->rowMarks);
    1580             : 
    1581             :         /*
    1582             :          * If this isn't the first child Query, adjust Vars and jointree
    1583             :          * entries to reference the appropriate set of subquery RTEs.
    1584             :          */
    1585        2422 :         if (final_rtable != NIL && subqueryRTindexes != NULL)
    1586             :         {
    1587         120 :             int         oldrti = -1;
    1588             : 
    1589         432 :             while ((oldrti = bms_next_member(subqueryRTindexes, oldrti)) >= 0)
    1590             :             {
    1591         192 :                 Index       newrti = next_subquery_rti++;
    1592             : 
    1593         192 :                 ChangeVarNodes((Node *) subroot->parse, oldrti, newrti, 0);
    1594         192 :                 ChangeVarNodes((Node *) subroot->append_rel_list,
    1595             :                                oldrti, newrti, 0);
    1596         192 :                 ChangeVarNodes((Node *) subroot->rowMarks, oldrti, newrti, 0);
    1597             :             }
    1598             :         }
    1599             : 
    1600             :         /* There shouldn't be any OJ info to translate, as yet */
    1601             :         Assert(subroot->join_info_list == NIL);
    1602             :         /* and we haven't created PlaceHolderInfos, either */
    1603             :         Assert(subroot->placeholder_list == NIL);
    1604             : 
    1605             :         /* Generate Path(s) for accessing this result relation */
    1606        2422 :         grouping_planner(subroot, true, 0.0 /* retrieve all tuples */ );
    1607             : 
    1608             :         /*
    1609             :          * Select cheapest path in case there's more than one.  We always run
    1610             :          * modification queries to conclusion, so we care only for the
    1611             :          * cheapest-total path.
    1612             :          */
    1613        2422 :         sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
    1614        2422 :         set_cheapest(sub_final_rel);
    1615        2422 :         subpath = sub_final_rel->cheapest_total_path;
    1616             : 
    1617             :         /*
    1618             :          * If this child rel was excluded by constraint exclusion, exclude it
    1619             :          * from the result plan.
    1620             :          */
    1621        2422 :         if (IS_DUMMY_REL(sub_final_rel))
    1622          60 :             continue;
    1623             : 
    1624             :         /*
    1625             :          * If this is the first non-excluded child, its post-planning rtable
    1626             :          * becomes the initial contents of final_rtable; otherwise, copy its
    1627             :          * modified subquery RTEs into final_rtable, to ensure we have sane
    1628             :          * copies of those.  Also save the first non-excluded child's version
    1629             :          * of the rowmarks list; we assume all children will end up with
    1630             :          * equivalent versions of that.
    1631             :          */
    1632        2362 :         if (final_rtable == NIL)
    1633             :         {
    1634        1192 :             final_rtable = subroot->parse->rtable;
    1635        1192 :             final_rowmarks = subroot->rowMarks;
    1636             :         }
    1637             :         else
    1638             :         {
    1639             :             Assert(list_length(final_rtable) ==
    1640             :                    list_length(subroot->parse->rtable));
    1641        1170 :             if (subqueryRTindexes != NULL)
    1642             :             {
    1643         120 :                 int         oldrti = -1;
    1644             : 
    1645         432 :                 while ((oldrti = bms_next_member(subqueryRTindexes, oldrti)) >= 0)
    1646             :                 {
    1647         192 :                     Index       newrti = this_subquery_rti++;
    1648             :                     RangeTblEntry *subqrte;
    1649             :                     ListCell   *newrticell;
    1650             : 
    1651         192 :                     subqrte = rt_fetch(newrti, subroot->parse->rtable);
    1652         192 :                     newrticell = list_nth_cell(final_rtable, newrti - 1);
    1653         192 :                     lfirst(newrticell) = subqrte;
    1654             :                 }
    1655             :             }
    1656             :         }
    1657             : 
    1658             :         /*
    1659             :          * We need to collect all the RelOptInfos from all child plans into
    1660             :          * the main PlannerInfo, since setrefs.c will need them.  We use the
    1661             :          * last child's simple_rel_array, so we have to propagate forward the
    1662             :          * RelOptInfos that were already built in previous children.
    1663             :          */
    1664             :         Assert(subroot->simple_rel_array_size >= save_rel_array_size);
    1665       10216 :         for (rti = 1; rti < save_rel_array_size; rti++)
    1666             :         {
    1667        7854 :             RelOptInfo *brel = save_rel_array[rti];
    1668             : 
    1669        7854 :             if (brel)
    1670        2932 :                 subroot->simple_rel_array[rti] = brel;
    1671             :         }
    1672        2362 :         save_rel_array_size = subroot->simple_rel_array_size;
    1673        2362 :         save_rel_array = subroot->simple_rel_array;
    1674        2362 :         save_append_rel_array = subroot->append_rel_array;
    1675             : 
    1676             :         /*
    1677             :          * Make sure any initplans from this rel get into the outer list. Note
    1678             :          * we're effectively assuming all children generate the same
    1679             :          * init_plans.
    1680             :          */
    1681        2362 :         root->init_plans = subroot->init_plans;
    1682             : 
    1683             :         /* Build list of sub-paths */
    1684        2362 :         subpaths = lappend(subpaths, subpath);
    1685             : 
    1686             :         /* Build list of modified subroots, too */
    1687        2362 :         subroots = lappend(subroots, subroot);
    1688             : 
    1689             :         /* Build list of target-relation RT indexes */
    1690        2362 :         resultRelations = lappend_int(resultRelations, appinfo->child_relid);
    1691             : 
    1692             :         /* Build lists of per-relation WCO and RETURNING targetlists */
    1693        2362 :         if (parse->withCheckOptions)
    1694         272 :             withCheckOptionLists = lappend(withCheckOptionLists,
    1695         272 :                                            subroot->parse->withCheckOptions);
    1696        2362 :         if (parse->returningList)
    1697         316 :             returningLists = lappend(returningLists,
    1698         316 :                                      subroot->parse->returningList);
    1699             : 
    1700             :         Assert(!parse->onConflict);
    1701             :     }
    1702             : 
    1703             :     /* Result path must go into outer query's FINAL upperrel */
    1704        1224 :     final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
    1705             : 
    1706             :     /*
    1707             :      * We don't currently worry about setting final_rel's consider_parallel
    1708             :      * flag in this case, nor about allowing FDWs or create_upper_paths_hook
    1709             :      * to get control here.
    1710             :      */
    1711             : 
    1712        1224 :     if (subpaths == NIL)
    1713             :     {
    1714             :         /*
    1715             :          * We managed to exclude every child rel, so generate a dummy path
    1716             :          * representing the empty set.  Although it's clear that no data will
    1717             :          * be updated or deleted, we will still need to have a ModifyTable
    1718             :          * node so that any statement triggers are executed.  (This could be
    1719             :          * cleaner if we fixed nodeModifyTable.c to support zero child nodes,
    1720             :          * but that probably wouldn't be a net win.)
    1721             :          */
    1722             :         Path       *dummy_path;
    1723             : 
    1724             :         /* tlist processing never got done, either */
    1725          32 :         root->processed_tlist = preprocess_targetlist(root);
    1726          32 :         final_rel->reltarget = create_pathtarget(root, root->processed_tlist);
    1727             : 
    1728             :         /* Make a dummy path, cf set_dummy_rel_pathlist() */
    1729          32 :         dummy_path = (Path *) create_append_path(NULL, final_rel, NIL, NIL,
    1730             :                                                  NIL, NULL, 0, false,
    1731             :                                                  NIL, -1);
    1732             : 
    1733             :         /* These lists must be nonempty to make a valid ModifyTable node */
    1734          32 :         subpaths = list_make1(dummy_path);
    1735          32 :         subroots = list_make1(root);
    1736          32 :         resultRelations = list_make1_int(parse->resultRelation);
    1737          32 :         if (parse->withCheckOptions)
    1738           0 :             withCheckOptionLists = list_make1(parse->withCheckOptions);
    1739          32 :         if (parse->returningList)
    1740          12 :             returningLists = list_make1(parse->returningList);
    1741             :         /* Disable tuple routing, too, just to be safe */
    1742          32 :         root->partColsUpdated = false;
    1743             :     }
    1744             :     else
    1745             :     {
    1746             :         /*
    1747             :          * Put back the final adjusted rtable into the master copy of the
    1748             :          * Query.  (We mustn't do this if we found no non-excluded children,
    1749             :          * since we never saved an adjusted rtable at all.)
    1750             :          */
    1751        1192 :         parse->rtable = final_rtable;
    1752        1192 :         root->simple_rel_array_size = save_rel_array_size;
    1753        1192 :         root->simple_rel_array = save_rel_array;
    1754        1192 :         root->append_rel_array = save_append_rel_array;
    1755             : 
    1756             :         /* Must reconstruct master's simple_rte_array, too */
    1757        1192 :         root->simple_rte_array = (RangeTblEntry **)
    1758        1192 :             palloc0((list_length(final_rtable) + 1) * sizeof(RangeTblEntry *));
    1759        1192 :         rti = 1;
    1760        5858 :         foreach(lc, final_rtable)
    1761             :         {
    1762        4666 :             RangeTblEntry *rte = lfirst_node(RangeTblEntry, lc);
    1763             : 
    1764        4666 :             root->simple_rte_array[rti++] = rte;
    1765             :         }
    1766             : 
    1767             :         /* Put back adjusted rowmarks, too */
    1768        1192 :         root->rowMarks = final_rowmarks;
    1769             :     }
    1770             : 
    1771             :     /*
    1772             :      * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node will
    1773             :      * have dealt with fetching non-locked marked rows, else we need to have
    1774             :      * ModifyTable do that.
    1775             :      */
    1776        1224 :     if (parse->rowMarks)
    1777           0 :         rowMarks = NIL;
    1778             :     else
    1779        1224 :         rowMarks = root->rowMarks;
    1780             : 
    1781             :     /* Create Path representing a ModifyTable to do the UPDATE/DELETE work */
    1782        1224 :     add_path(final_rel, (Path *)
    1783        3672 :              create_modifytable_path(root, final_rel,
    1784             :                                      parse->commandType,
    1785        1224 :                                      parse->canSetTag,
    1786             :                                      nominalRelation,
    1787             :                                      rootRelation,
    1788        1224 :                                      root->partColsUpdated,
    1789             :                                      resultRelations,
    1790             :                                      subpaths,
    1791             :                                      subroots,
    1792             :                                      withCheckOptionLists,
    1793             :                                      returningLists,
    1794             :                                      rowMarks,
    1795             :                                      NULL,
    1796             :                                      assign_special_exec_param(root)));
    1797        1224 : }
    1798             : 
    1799             : /*--------------------
    1800             :  * grouping_planner
    1801             :  *    Perform planning steps related to grouping, aggregation, etc.
    1802             :  *
    1803             :  * This function adds all required top-level processing to the scan/join
    1804             :  * Path(s) produced by query_planner.
    1805             :  *
    1806             :  * If inheritance_update is true, we're being called from inheritance_planner
    1807             :  * and should not include a ModifyTable step in the resulting Path(s).
    1808             :  * (inheritance_planner will create a single ModifyTable node covering all the
    1809             :  * target tables.)
    1810             :  *
    1811             :  * tuple_fraction is the fraction of tuples we expect will be retrieved.
    1812             :  * tuple_fraction is interpreted as follows:
    1813             :  *    0: expect all tuples to be retrieved (normal case)
    1814             :  *    0 < tuple_fraction < 1: expect the given fraction of tuples available
    1815             :  *      from the plan to be retrieved
    1816             :  *    tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
    1817             :  *      expected to be retrieved (ie, a LIMIT specification)
    1818             :  *
    1819             :  * Returns nothing; the useful output is in the Paths we attach to the
    1820             :  * (UPPERREL_FINAL, NULL) upperrel in *root.  In addition,
    1821             :  * root->processed_tlist contains the final processed targetlist.
    1822             :  *
    1823             :  * Note that we have not done set_cheapest() on the final rel; it's convenient
    1824             :  * to leave this to the caller.
    1825             :  *--------------------
    1826             :  */
    1827             : static void
    1828      302598 : grouping_planner(PlannerInfo *root, bool inheritance_update,
    1829             :                  double tuple_fraction)
    1830             : {
    1831      302598 :     Query      *parse = root->parse;
    1832      302598 :     int64       offset_est = 0;
    1833      302598 :     int64       count_est = 0;
    1834      302598 :     double      limit_tuples = -1.0;
    1835      302598 :     bool        have_postponed_srfs = false;
    1836             :     PathTarget *final_target;
    1837             :     List       *final_targets;
    1838             :     List       *final_targets_contain_srfs;
    1839             :     bool        final_target_parallel_safe;
    1840             :     RelOptInfo *current_rel;
    1841             :     RelOptInfo *final_rel;
    1842             :     FinalPathExtraData extra;
    1843             :     ListCell   *lc;
    1844             : 
    1845             :     /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
    1846      302598 :     if (parse->limitCount || parse->limitOffset)
    1847             :     {
    1848        3054 :         tuple_fraction = preprocess_limit(root, tuple_fraction,
    1849             :                                           &offset_est, &count_est);
    1850             : 
    1851             :         /*
    1852             :          * If we have a known LIMIT, and don't have an unknown OFFSET, we can
    1853             :          * estimate the effects of using a bounded sort.
    1854             :          */
    1855        3054 :         if (count_est > 0 && offset_est >= 0)
    1856        2820 :             limit_tuples = (double) count_est + (double) offset_est;
    1857             :     }
    1858             : 
    1859             :     /* Make tuple_fraction accessible to lower-level routines */
    1860      302598 :     root->tuple_fraction = tuple_fraction;
    1861             : 
    1862      302598 :     if (parse->setOperations)
    1863             :     {
    1864             :         /*
    1865             :          * If there's a top-level ORDER BY, assume we have to fetch all the
    1866             :          * tuples.  This might be too simplistic given all the hackery below
    1867             :          * to possibly avoid the sort; but the odds of accurate estimates here
    1868             :          * are pretty low anyway.  XXX try to get rid of this in favor of
    1869             :          * letting plan_set_operations generate both fast-start and
    1870             :          * cheapest-total paths.
    1871             :          */
    1872        1248 :         if (parse->sortClause)
    1873         360 :             root->tuple_fraction = 0.0;
    1874             : 
    1875             :         /*
    1876             :          * Construct Paths for set operations.  The results will not need any
    1877             :          * work except perhaps a top-level sort and/or LIMIT.  Note that any
    1878             :          * special work for recursive unions is the responsibility of
    1879             :          * plan_set_operations.
    1880             :          */
    1881        1248 :         current_rel = plan_set_operations(root);
    1882             : 
    1883             :         /*
    1884             :          * We should not need to call preprocess_targetlist, since we must be
    1885             :          * in a SELECT query node.  Instead, use the processed_tlist returned
    1886             :          * by plan_set_operations (since this tells whether it returned any
    1887             :          * resjunk columns!), and transfer any sort key information from the
    1888             :          * original tlist.
    1889             :          */
    1890             :         Assert(parse->commandType == CMD_SELECT);
    1891             : 
    1892             :         /* for safety, copy processed_tlist instead of modifying in-place */
    1893        1248 :         root->processed_tlist =
    1894        1248 :             postprocess_setop_tlist(copyObject(root->processed_tlist),
    1895             :                                     parse->targetList);
    1896             : 
    1897             :         /* Also extract the PathTarget form of the setop result tlist */
    1898        1248 :         final_target = current_rel->cheapest_total_path->pathtarget;
    1899             : 
    1900             :         /* And check whether it's parallel safe */
    1901        1248 :         final_target_parallel_safe =
    1902        1248 :             is_parallel_safe(root, (Node *) final_target->exprs);
    1903             : 
    1904             :         /* The setop result tlist couldn't contain any SRFs */
    1905             :         Assert(!parse->hasTargetSRFs);
    1906        1248 :         final_targets = final_targets_contain_srfs = NIL;
    1907             : 
    1908             :         /*
    1909             :          * Can't handle FOR [KEY] UPDATE/SHARE here (parser should have
    1910             :          * checked already, but let's make sure).
    1911             :          */
    1912        1248 :         if (parse->rowMarks)
    1913           0 :             ereport(ERROR,
    1914             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1915             :             /*------
    1916             :               translator: %s is a SQL row locking clause such as FOR UPDATE */
    1917             :                      errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
    1918             :                             LCS_asString(linitial_node(RowMarkClause,
    1919             :                                                        parse->rowMarks)->strength))));
    1920             : 
    1921             :         /*
    1922             :          * Calculate pathkeys that represent result ordering requirements
    1923             :          */
    1924             :         Assert(parse->distinctClause == NIL);
    1925        1248 :         root->sort_pathkeys = make_pathkeys_for_sortclauses(root,
    1926             :                                                             parse->sortClause,
    1927             :                                                             root->processed_tlist);
    1928             :     }
    1929             :     else
    1930             :     {
    1931             :         /* No set operations, do regular planning */
    1932             :         PathTarget *sort_input_target;
    1933             :         List       *sort_input_targets;
    1934             :         List       *sort_input_targets_contain_srfs;
    1935             :         bool        sort_input_target_parallel_safe;
    1936             :         PathTarget *grouping_target;
    1937             :         List       *grouping_targets;
    1938             :         List       *grouping_targets_contain_srfs;
    1939             :         bool        grouping_target_parallel_safe;
    1940             :         PathTarget *scanjoin_target;
    1941             :         List       *scanjoin_targets;
    1942             :         List       *scanjoin_targets_contain_srfs;
    1943             :         bool        scanjoin_target_parallel_safe;
    1944             :         bool        scanjoin_target_same_exprs;
    1945             :         bool        have_grouping;
    1946             :         AggClauseCosts agg_costs;
    1947      301350 :         WindowFuncLists *wflists = NULL;
    1948      301350 :         List       *activeWindows = NIL;
    1949      301350 :         grouping_sets_data *gset_data = NULL;
    1950             :         standard_qp_extra qp_extra;
    1951             : 
    1952             :         /* A recursive query should always have setOperations */
    1953             :         Assert(!root->hasRecursion);
    1954             : 
    1955             :         /* Preprocess grouping sets and GROUP BY clause, if any */
    1956      301350 :         if (parse->groupingSets)
    1957             :         {
    1958         436 :             gset_data = preprocess_grouping_sets(root);
    1959             :         }
    1960             :         else
    1961             :         {
    1962             :             /* Preprocess regular GROUP BY clause, if any */
    1963      300914 :             if (parse->groupClause)
    1964        1704 :                 parse->groupClause = preprocess_groupclause(root, NIL);
    1965             :         }
    1966             : 
    1967             :         /*
    1968             :          * Preprocess targetlist.  Note that much of the remaining planning
    1969             :          * work will be done with the PathTarget representation of tlists, but
    1970             :          * we must also maintain the full representation of the final tlist so
    1971             :          * that we can transfer its decoration (resnames etc) to the topmost
    1972             :          * tlist of the finished Plan.  This is kept in processed_tlist.
    1973             :          */
    1974      301346 :         root->processed_tlist = preprocess_targetlist(root);
    1975             : 
    1976             :         /*
    1977             :          * Collect statistics about aggregates for estimating costs, and mark
    1978             :          * all the aggregates with resolved aggtranstypes.  We must do this
    1979             :          * before slicing and dicing the tlist into various pathtargets, else
    1980             :          * some copies of the Aggref nodes might escape being marked with the
    1981             :          * correct transtypes.
    1982             :          *
    1983             :          * Note: currently, we do not detect duplicate aggregates here.  This
    1984             :          * may result in somewhat-overestimated cost, which is fine for our
    1985             :          * purposes since all Paths will get charged the same.  But at some
    1986             :          * point we might wish to do that detection in the planner, rather
    1987             :          * than during executor startup.
    1988             :          */
    1989      301346 :         MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
    1990      301346 :         if (parse->hasAggs)
    1991             :         {
    1992       23560 :             get_agg_clause_costs(root, (Node *) root->processed_tlist,
    1993             :                                  AGGSPLIT_SIMPLE, &agg_costs);
    1994       23560 :             get_agg_clause_costs(root, parse->havingQual, AGGSPLIT_SIMPLE,
    1995             :                                  &agg_costs);
    1996             :         }
    1997             : 
    1998             :         /*
    1999             :          * Locate any window functions in the tlist.  (We don't need to look
    2000             :          * anywhere else, since expressions used in ORDER BY will be in there
    2001             :          * too.)  Note that they could all have been eliminated by constant
    2002             :          * folding, in which case we don't need to do any more work.
    2003             :          */
    2004      301346 :         if (parse->hasWindowFuncs)
    2005             :         {
    2006        1116 :             wflists = find_window_functions((Node *) root->processed_tlist,
    2007        1116 :                                             list_length(parse->windowClause));
    2008        1116 :             if (wflists->numWindowFuncs > 0)
    2009        1112 :                 activeWindows = select_active_windows(root, wflists);
    2010             :             else
    2011           4 :                 parse->hasWindowFuncs = false;
    2012             :         }
    2013             : 
    2014             :         /*
    2015             :          * Preprocess MIN/MAX aggregates, if any.  Note: be careful about
    2016             :          * adding logic between here and the query_planner() call.  Anything
    2017             :          * that is needed in MIN/MAX-optimizable cases will have to be
    2018             :          * duplicated in planagg.c.
    2019             :          */
    2020      301346 :         if (parse->hasAggs)
    2021       23560 :             preprocess_minmax_aggregates(root);
    2022             : 
    2023             :         /*
    2024             :          * Figure out whether there's a hard limit on the number of rows that
    2025             :          * query_planner's result subplan needs to return.  Even if we know a
    2026             :          * hard limit overall, it doesn't apply if the query has any
    2027             :          * grouping/aggregation operations, or SRFs in the tlist.
    2028             :          */
    2029      600584 :         if (parse->groupClause ||
    2030      598448 :             parse->groupingSets ||
    2031      598038 :             parse->distinctClause ||
    2032      576002 :             parse->hasAggs ||
    2033      553316 :             parse->hasWindowFuncs ||
    2034      548714 :             parse->hasTargetSRFs ||
    2035      272572 :             root->hasHavingQual)
    2036       28786 :             root->limit_tuples = -1.0;
    2037             :         else
    2038      272560 :             root->limit_tuples = limit_tuples;
    2039             : 
    2040             :         /* Set up data needed by standard_qp_callback */
    2041      301346 :         qp_extra.activeWindows = activeWindows;
    2042      301346 :         qp_extra.groupClause = (gset_data
    2043         432 :                                 ? (gset_data->rollups ? linitial_node(RollupData, gset_data->rollups)->groupClause : NIL)
    2044      301778 :                                 : parse->groupClause);
    2045             : 
    2046             :         /*
    2047             :          * Generate the best unsorted and presorted paths for the scan/join
    2048             :          * portion of this Query, ie the processing represented by the
    2049             :          * FROM/WHERE clauses.  (Note there may not be any presorted paths.)
    2050             :          * We also generate (in standard_qp_callback) pathkey representations
    2051             :          * of the query's sort clause, distinct clause, etc.
    2052             :          */
    2053      301346 :         current_rel = query_planner(root, standard_qp_callback, &qp_extra);
    2054             : 
    2055             :         /*
    2056             :          * Convert the query's result tlist into PathTarget format.
    2057             :          *
    2058             :          * Note: this cannot be done before query_planner() has performed
    2059             :          * appendrel expansion, because that might add resjunk entries to
    2060             :          * root->processed_tlist.  Waiting till afterwards is also helpful
    2061             :          * because the target width estimates can use per-Var width numbers
    2062             :          * that were obtained within query_planner().
    2063             :          */
    2064      301336 :         final_target = create_pathtarget(root, root->processed_tlist);
    2065      301336 :         final_target_parallel_safe =
    2066      301336 :             is_parallel_safe(root, (Node *) final_target->exprs);
    2067             : 
    2068             :         /*
    2069             :          * If ORDER BY was given, consider whether we should use a post-sort
    2070             :          * projection, and compute the adjusted target for preceding steps if
    2071             :          * so.
    2072             :          */
    2073      301336 :         if (parse->sortClause)
    2074             :         {
    2075       35756 :             sort_input_target = make_sort_input_target(root,
    2076             :                                                        final_target,
    2077             :                                                        &have_postponed_srfs);
    2078       35756 :             sort_input_target_parallel_safe =
    2079       35756 :                 is_parallel_safe(root, (Node *) sort_input_target->exprs);
    2080             :         }
    2081             :         else
    2082             :         {
    2083      265580 :             sort_input_target = final_target;
    2084      265580 :             sort_input_target_parallel_safe = final_target_parallel_safe;
    2085             :         }
    2086             : 
    2087             :         /*
    2088             :          * If we have window functions to deal with, the output from any
    2089             :          * grouping step needs to be what the window functions want;
    2090             :          * otherwise, it should be sort_input_target.
    2091             :          */
    2092      301336 :         if (activeWindows)
    2093             :         {
    2094        1112 :             grouping_target = make_window_input_target(root,
    2095             :                                                        final_target,
    2096             :                                                        activeWindows);
    2097        1112 :             grouping_target_parallel_safe =
    2098        1112 :                 is_parallel_safe(root, (Node *) grouping_target->exprs);
    2099             :         }
    2100             :         else
    2101             :         {
    2102      300224 :             grouping_target = sort_input_target;
    2103      300224 :             grouping_target_parallel_safe = sort_input_target_parallel_safe;
    2104             :         }
    2105             : 
    2106             :         /*
    2107             :          * If we have grouping or aggregation to do, the topmost scan/join
    2108             :          * plan node must emit what the grouping step wants; otherwise, it
    2109             :          * should emit grouping_target.
    2110             :          */
    2111     1201100 :         have_grouping = (parse->groupClause || parse->groupingSets ||
    2112      878064 :                          parse->hasAggs || root->hasHavingQual);
    2113      301336 :         if (have_grouping)
    2114             :         {
    2115       23820 :             scanjoin_target = make_group_input_target(root, final_target);
    2116       23820 :             scanjoin_target_parallel_safe =
    2117       23820 :                 is_parallel_safe(root, (Node *) scanjoin_target->exprs);
    2118             :         }
    2119             :         else
    2120             :         {
    2121      277516 :             scanjoin_target = grouping_target;
    2122      277516 :             scanjoin_target_parallel_safe = grouping_target_parallel_safe;
    2123             :         }
    2124             : 
    2125             :         /*
    2126             :          * If there are any SRFs in the targetlist, we must separate each of
    2127             :          * these PathTargets into SRF-computing and SRF-free targets.  Replace
    2128             :          * each of the named targets with a SRF-free version, and remember the
    2129             :          * list of additional projection steps we need to add afterwards.
    2130             :          */
    2131      301336 :         if (parse->hasTargetSRFs)
    2132             :         {
    2133             :             /* final_target doesn't recompute any SRFs in sort_input_target */
    2134        3682 :             split_pathtarget_at_srfs(root, final_target, sort_input_target,
    2135             :                                      &final_targets,
    2136             :                                      &final_targets_contain_srfs);
    2137        3682 :             final_target = linitial_node(PathTarget, final_targets);
    2138             :             Assert(!linitial_int(final_targets_contain_srfs));
    2139             :             /* likewise for sort_input_target vs. grouping_target */
    2140        3682 :             split_pathtarget_at_srfs(root, sort_input_target, grouping_target,
    2141             :                                      &sort_input_targets,
    2142             :                                      &sort_input_targets_contain_srfs);
    2143        3682 :             sort_input_target = linitial_node(PathTarget, sort_input_targets);
    2144             :             Assert(!linitial_int(sort_input_targets_contain_srfs));
    2145             :             /* likewise for grouping_target vs. scanjoin_target */
    2146        3682 :             split_pathtarget_at_srfs(root, grouping_target, scanjoin_target,
    2147             :                                      &grouping_targets,
    2148             :                                      &grouping_targets_contain_srfs);
    2149        3682 :             grouping_target = linitial_node(PathTarget, grouping_targets);
    2150             :             Assert(!linitial_int(grouping_targets_contain_srfs));
    2151             :             /* scanjoin_target will not have any SRFs precomputed for it */
    2152        3682 :             split_pathtarget_at_srfs(root, scanjoin_target, NULL,
    2153             :                                      &scanjoin_targets,
    2154             :                                      &scanjoin_targets_contain_srfs);
    2155        3682 :             scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
    2156             :             Assert(!linitial_int(scanjoin_targets_contain_srfs));
    2157             :         }
    2158             :         else
    2159             :         {
    2160             :             /* initialize lists; for most of these, dummy values are OK */
    2161      297654 :             final_targets = final_targets_contain_srfs = NIL;
    2162      297654 :             sort_input_targets = sort_input_targets_contain_srfs = NIL;
    2163      297654 :             grouping_targets = grouping_targets_contain_srfs = NIL;
    2164      297654 :             scanjoin_targets = list_make1(scanjoin_target);
    2165      297654 :             scanjoin_targets_contain_srfs = NIL;
    2166             :         }
    2167             : 
    2168             :         /* Apply scan/join target. */
    2169      602672 :         scanjoin_target_same_exprs = list_length(scanjoin_targets) == 1
    2170      301336 :             && equal(scanjoin_target->exprs, current_rel->reltarget->exprs);
    2171      301336 :         apply_scanjoin_target_to_paths(root, current_rel, scanjoin_targets,
    2172             :                                        scanjoin_targets_contain_srfs,
    2173             :                                        scanjoin_target_parallel_safe,
    2174             :                                        scanjoin_target_same_exprs);
    2175             : 
    2176             :         /*
    2177             :          * Save the various upper-rel PathTargets we just computed into
    2178             :          * root->upper_targets[].  The core code doesn't use this, but it
    2179             :          * provides a convenient place for extensions to get at the info.  For
    2180             :          * consistency, we save all the intermediate targets, even though some
    2181             :          * of the corresponding upperrels might not be needed for this query.
    2182             :          */
    2183      301336 :         root->upper_targets[UPPERREL_FINAL] = final_target;
    2184      301336 :         root->upper_targets[UPPERREL_ORDERED] = final_target;
    2185      301336 :         root->upper_targets[UPPERREL_DISTINCT] = sort_input_target;
    2186      301336 :         root->upper_targets[UPPERREL_WINDOW] = sort_input_target;
    2187      301336 :         root->upper_targets[UPPERREL_GROUP_AGG] = grouping_target;
    2188             : 
    2189             :         /*
    2190             :          * If we have grouping and/or aggregation, consider ways to implement
    2191             :          * that.  We build a new upperrel representing the output of this
    2192             :          * phase.
    2193             :          */
    2194      301336 :         if (have_grouping)
    2195             :         {
    2196       23820 :             current_rel = create_grouping_paths(root,
    2197             :                                                 current_rel,
    2198             :                                                 grouping_target,
    2199             :                                                 grouping_target_parallel_safe,
    2200             :                                                 &agg_costs,
    2201             :                                                 gset_data);
    2202             :             /* Fix things up if grouping_target contains SRFs */
    2203       23816 :             if (parse->hasTargetSRFs)
    2204          84 :                 adjust_paths_for_srfs(root, current_rel,
    2205             :                                       grouping_targets,
    2206             :                                       grouping_targets_contain_srfs);
    2207             :         }
    2208             : 
    2209             :         /*
    2210             :          * If we have window functions, consider ways to implement those.  We
    2211             :          * build a new upperrel representing the output of this phase.
    2212             :          */
    2213      301332 :         if (activeWindows)
    2214             :         {
    2215        1112 :             current_rel = create_window_paths(root,
    2216             :                                               current_rel,
    2217             :                                               grouping_target,
    2218             :                                               sort_input_target,
    2219             :                                               sort_input_target_parallel_safe,
    2220             :                                               wflists,
    2221             :                                               activeWindows);
    2222             :             /* Fix things up if sort_input_target contains SRFs */
    2223        1112 :             if (parse->hasTargetSRFs)
    2224           8 :                 adjust_paths_for_srfs(root, current_rel,
    2225             :                                       sort_input_targets,
    2226             :                                       sort_input_targets_contain_srfs);
    2227             :         }
    2228             : 
    2229             :         /*
    2230             :          * If there is a DISTINCT clause, consider ways to implement that. We
    2231             :          * build a new upperrel representing the output of this phase.
    2232             :          */
    2233      301332 :         if (parse->distinctClause)
    2234             :         {
    2235         386 :             current_rel = create_distinct_paths(root,
    2236             :                                                 current_rel);
    2237             :         }
    2238             :     }                           /* end of if (setOperations) */
    2239             : 
    2240             :     /*
    2241             :      * If ORDER BY was given, consider ways to implement that, and generate a
    2242             :      * new upperrel containing only paths that emit the correct ordering and
    2243             :      * project the correct final_target.  We can apply the original
    2244             :      * limit_tuples limit in sort costing here, but only if there are no
    2245             :      * postponed SRFs.
    2246             :      */
    2247      302580 :     if (parse->sortClause)
    2248             :     {
    2249       36116 :         current_rel = create_ordered_paths(root,
    2250             :                                            current_rel,
    2251             :                                            final_target,
    2252             :                                            final_target_parallel_safe,
    2253             :                                            have_postponed_srfs ? -1.0 :
    2254             :                                            limit_tuples);
    2255             :         /* Fix things up if final_target contains SRFs */
    2256       36116 :         if (parse->hasTargetSRFs)
    2257         120 :             adjust_paths_for_srfs(root, current_rel,
    2258             :                                   final_targets,
    2259             :                                   final_targets_contain_srfs);
    2260             :     }
    2261             : 
    2262             :     /*
    2263             :      * Now we are prepared to build the final-output upperrel.
    2264             :      */
    2265      302580 :     final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
    2266             : 
    2267             :     /*
    2268             :      * If the input rel is marked consider_parallel and there's nothing that's
    2269             :      * not parallel-safe in the LIMIT clause, then the final_rel can be marked
    2270             :      * consider_parallel as well.  Note that if the query has rowMarks or is
    2271             :      * not a SELECT, consider_parallel will be false for every relation in the
    2272             :      * query.
    2273             :      */
    2274      375102 :     if (current_rel->consider_parallel &&
    2275      145036 :         is_parallel_safe(root, parse->limitOffset) &&
    2276       72514 :         is_parallel_safe(root, parse->limitCount))
    2277       72510 :         final_rel->consider_parallel = true;
    2278             : 
    2279             :     /*
    2280             :      * If the current_rel belongs to a single FDW, so does the final_rel.
    2281             :      */
    2282      302580 :     final_rel->serverid = current_rel->serverid;
    2283      302580 :     final_rel->userid = current_rel->userid;
    2284      302580 :     final_rel->useridiscurrent = current_rel->useridiscurrent;
    2285      302580 :     final_rel->fdwroutine = current_rel->fdwroutine;
    2286             : 
    2287             :     /*
    2288             :      * Generate paths for the final_rel.  Insert all surviving paths, with
    2289             :      * LockRows, Limit, and/or ModifyTable steps added if needed.
    2290             :      */
    2291      610382 :     foreach(lc, current_rel->pathlist)
    2292             :     {
    2293      307802 :         Path       *path = (Path *) lfirst(lc);
    2294             : 
    2295             :         /*
    2296             :          * If there is a FOR [KEY] UPDATE/SHARE clause, add the LockRows node.
    2297             :          * (Note: we intentionally test parse->rowMarks not root->rowMarks
    2298             :          * here.  If there are only non-locking rowmarks, they should be
    2299             :          * handled by the ModifyTable node instead.  However, root->rowMarks
    2300             :          * is what goes into the LockRows node.)
    2301             :          */
    2302      307802 :         if (parse->rowMarks)
    2303             :         {
    2304        5310 :             path = (Path *) create_lockrows_path(root, final_rel, path,
    2305             :                                                  root->rowMarks,
    2306             :                                                  assign_special_exec_param(root));
    2307             :         }
    2308             : 
    2309             :         /*
    2310             :          * If there is a LIMIT/OFFSET clause, add the LIMIT node.
    2311             :          */
    2312      307802 :         if (limit_needed(parse))
    2313             :         {
    2314        3536 :             path = (Path *) create_limit_path(root, final_rel, path,
    2315             :                                               parse->limitOffset,
    2316             :                                               parse->limitCount,
    2317             :                                               offset_est, count_est);
    2318             :         }
    2319             : 
    2320             :         /*
    2321             :          * If this is an INSERT/UPDATE/DELETE, and we're not being called from
    2322             :          * inheritance_planner, add the ModifyTable node.
    2323             :          */
    2324      307802 :         if (parse->commandType != CMD_SELECT && !inheritance_update)
    2325             :         {
    2326             :             Index       rootRelation;
    2327             :             List       *withCheckOptionLists;
    2328             :             List       *returningLists;
    2329             :             List       *rowMarks;
    2330             : 
    2331             :             /*
    2332             :              * If target is a partition root table, we need to mark the
    2333             :              * ModifyTable node appropriately for that.
    2334             :              */
    2335       68172 :             if (rt_fetch(parse->resultRelation, parse->rtable)->relkind ==
    2336             :                 RELKIND_PARTITIONED_TABLE)
    2337        1498 :                 rootRelation = parse->resultRelation;
    2338             :             else
    2339       66674 :                 rootRelation = 0;
    2340             : 
    2341             :             /*
    2342             :              * Set up the WITH CHECK OPTION and RETURNING lists-of-lists, if
    2343             :              * needed.
    2344             :              */
    2345       68172 :             if (parse->withCheckOptions)
    2346         508 :                 withCheckOptionLists = list_make1(parse->withCheckOptions);
    2347             :             else
    2348       67664 :                 withCheckOptionLists = NIL;
    2349             : 
    2350       68172 :             if (parse->returningList)
    2351        1484 :                 returningLists = list_make1(parse->returningList);
    2352             :             else
    2353       66688 :                 returningLists = NIL;
    2354             : 
    2355             :             /*
    2356             :              * If there was a FOR [KEY] UPDATE/SHARE clause, the LockRows node
    2357             :              * will have dealt with fetching non-locked marked rows, else we
    2358             :              * need to have ModifyTable do that.
    2359             :              */
    2360       68172 :             if (parse->rowMarks)
    2361           0 :                 rowMarks = NIL;
    2362             :             else
    2363       68172 :                 rowMarks = root->rowMarks;
    2364             : 
    2365       68172 :             path = (Path *)
    2366      409032 :                 create_modifytable_path(root, final_rel,
    2367             :                                         parse->commandType,
    2368       68172 :                                         parse->canSetTag,
    2369       68172 :                                         parse->resultRelation,
    2370             :                                         rootRelation,
    2371             :                                         false,
    2372       68172 :                                         list_make1_int(parse->resultRelation),
    2373       68172 :                                         list_make1(path),
    2374       68172 :                                         list_make1(root),
    2375             :                                         withCheckOptionLists,
    2376             :                                         returningLists,
    2377             :                                         rowMarks,
    2378             :                                         parse->onConflict,
    2379             :                                         assign_special_exec_param(root));
    2380             :         }
    2381             : 
    2382             :         /* And shove it into final_rel */
    2383      307802 :         add_path(final_rel, path);
    2384             :     }
    2385             : 
    2386             :     /*
    2387             :      * Generate partial paths for final_rel, too, if outer query levels might
    2388             :      * be able to make use of them.
    2389             :      */
    2390      309412 :     if (final_rel->consider_parallel && root->query_level > 1 &&
    2391        6832 :         !limit_needed(parse))
    2392             :     {
    2393             :         Assert(!parse->rowMarks && parse->commandType == CMD_SELECT);
    2394        6798 :         foreach(lc, current_rel->partial_pathlist)
    2395             :         {
    2396          44 :             Path       *partial_path = (Path *) lfirst(lc);
    2397             : 
    2398          44 :             add_partial_path(final_rel, partial_path);
    2399             :         }
    2400             :     }
    2401             : 
    2402      302580 :     extra.limit_needed = limit_needed(parse);
    2403      302580 :     extra.limit_tuples = limit_tuples;
    2404      302580 :     extra.count_est = count_est;
    2405      302580 :     extra.offset_est = offset_est;
    2406             : 
    2407             :     /*
    2408             :      * If there is an FDW that's responsible for all baserels of the query,
    2409             :      * let it consider adding ForeignPaths.
    2410             :      */
    2411      303572 :     if (final_rel->fdwroutine &&
    2412         992 :         final_rel->fdwroutine->GetForeignUpperPaths)
    2413         934 :         final_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_FINAL,
    2414             :                                                     current_rel, final_rel,
    2415             :                                                     &extra);
    2416             : 
    2417             :     /* Let extensions possibly add some more paths */
    2418      302580 :     if (create_upper_paths_hook)
    2419           0 :         (*create_upper_paths_hook) (root, UPPERREL_FINAL,
    2420             :                                     current_rel, final_rel, &extra);
    2421             : 
    2422             :     /* Note: currently, we leave it to callers to do set_cheapest() */
    2423      302580 : }
    2424             : 
    2425             : /*
    2426             :  * Do preprocessing for groupingSets clause and related data.  This handles the
    2427             :  * preliminary steps of expanding the grouping sets, organizing them into lists
    2428             :  * of rollups, and preparing annotations which will later be filled in with
    2429             :  * size estimates.
    2430             :  */
    2431             : static grouping_sets_data *
    2432         436 : preprocess_grouping_sets(PlannerInfo *root)
    2433             : {
    2434         436 :     Query      *parse = root->parse;
    2435             :     List       *sets;
    2436         436 :     int         maxref = 0;
    2437             :     ListCell   *lc;
    2438             :     ListCell   *lc_set;
    2439         436 :     grouping_sets_data *gd = palloc0(sizeof(grouping_sets_data));
    2440             : 
    2441         436 :     parse->groupingSets = expand_grouping_sets(parse->groupingSets, -1);
    2442             : 
    2443         436 :     gd->any_hashable = false;
    2444         436 :     gd->unhashable_refs = NULL;
    2445         436 :     gd->unsortable_refs = NULL;
    2446         436 :     gd->unsortable_sets = NIL;
    2447             : 
    2448         436 :     if (parse->groupClause)
    2449             :     {
    2450             :         ListCell   *lc;
    2451             : 
    2452        1312 :         foreach(lc, parse->groupClause)
    2453             :         {
    2454         904 :             SortGroupClause *gc = lfirst_node(SortGroupClause, lc);
    2455         904 :             Index       ref = gc->tleSortGroupRef;
    2456             : 
    2457         904 :             if (ref > maxref)
    2458         880 :                 maxref = ref;
    2459             : 
    2460         904 :             if (!gc->hashable)
    2461          20 :                 gd->unhashable_refs = bms_add_member(gd->unhashable_refs, ref);
    2462             : 
    2463         904 :             if (!OidIsValid(gc->sortop))
    2464          28 :                 gd->unsortable_refs = bms_add_member(gd->unsortable_refs, ref);
    2465             :         }
    2466             :     }
    2467             : 
    2468             :     /* Allocate workspace array for remapping */
    2469         436 :     gd->tleref_to_colnum_map = (int *) palloc((maxref + 1) * sizeof(int));
    2470             : 
    2471             :     /*
    2472             :      * If we have any unsortable sets, we must extract them before trying to
    2473             :      * prepare rollups. Unsortable sets don't go through
    2474             :      * reorder_grouping_sets, so we must apply the GroupingSetData annotation
    2475             :      * here.
    2476             :      */
    2477         436 :     if (!bms_is_empty(gd->unsortable_refs))
    2478             :     {
    2479          28 :         List       *sortable_sets = NIL;
    2480             : 
    2481          84 :         foreach(lc, parse->groupingSets)
    2482             :         {
    2483          60 :             List       *gset = (List *) lfirst(lc);
    2484             : 
    2485          60 :             if (bms_overlap_list(gd->unsortable_refs, gset))
    2486             :             {
    2487          32 :                 GroupingSetData *gs = makeNode(GroupingSetData);
    2488             : 
    2489          32 :                 gs->set = gset;
    2490          32 :                 gd->unsortable_sets = lappend(gd->unsortable_sets, gs);
    2491             : 
    2492             :                 /*
    2493             :                  * We must enforce here that an unsortable set is hashable;
    2494             :                  * later code assumes this.  Parse analysis only checks that
    2495             :                  * every individual column is either hashable or sortable.
    2496             :                  *
    2497             :                  * Note that passing this test doesn't guarantee we can
    2498             :                  * generate a plan; there might be other showstoppers.
    2499             :                  */
    2500          32 :                 if (bms_overlap_list(gd->unhashable_refs, gset))
    2501           4 :                     ereport(ERROR,
    2502             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2503             :                              errmsg("could not implement GROUP BY"),
    2504             :                              errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
    2505             :             }
    2506             :             else
    2507          28 :                 sortable_sets = lappend(sortable_sets, gset);
    2508             :         }
    2509             : 
    2510          24 :         if (sortable_sets)
    2511          20 :             sets = extract_rollup_sets(sortable_sets);
    2512             :         else
    2513           4 :             sets = NIL;
    2514             :     }
    2515             :     else
    2516         408 :         sets = extract_rollup_sets(parse->groupingSets);
    2517             : 
    2518        1124 :     foreach(lc_set, sets)
    2519             :     {
    2520         692 :         List       *current_sets = (List *) lfirst(lc_set);
    2521         692 :         RollupData *rollup = makeNode(RollupData);
    2522             :         GroupingSetData *gs;
    2523             : 
    2524             :         /*
    2525             :          * Reorder the current list of grouping sets into correct prefix
    2526             :          * order.  If only one aggregation pass is needed, try to make the
    2527             :          * list match the ORDER BY clause; if more than one pass is needed, we
    2528             :          * don't bother with that.
    2529             :          *
    2530             :          * Note that this reorders the sets from smallest-member-first to
    2531             :          * largest-member-first, and applies the GroupingSetData annotations,
    2532             :          * though the data will be filled in later.
    2533             :          */
    2534         692 :         current_sets = reorder_grouping_sets(current_sets,
    2535         692 :                                              (list_length(sets) == 1
    2536             :                                               ? parse->sortClause
    2537             :                                               : NIL));
    2538             : 
    2539             :         /*
    2540             :          * Get the initial (and therefore largest) grouping set.
    2541             :          */
    2542         692 :         gs = linitial_node(GroupingSetData, current_sets);
    2543             : 
    2544             :         /*
    2545             :          * Order the groupClause appropriately.  If the first grouping set is
    2546             :          * empty, then the groupClause must also be empty; otherwise we have
    2547             :          * to force the groupClause to match that grouping set's order.
    2548             :          *
    2549             :          * (The first grouping set can be empty even though parse->groupClause
    2550             :          * is not empty only if all non-empty grouping sets are unsortable.
    2551             :          * The groupClauses for hashed grouping sets are built later on.)
    2552             :          */
    2553         692 :         if (gs->set)
    2554         664 :             rollup->groupClause = preprocess_groupclause(root, gs->set);
    2555             :         else
    2556          28 :             rollup->groupClause = NIL;
    2557             : 
    2558             :         /*
    2559             :          * Is it hashable? We pretend empty sets are hashable even though we
    2560             :          * actually force them not to be hashed later. But don't bother if
    2561             :          * there's nothing but empty sets (since in that case we can't hash
    2562             :          * anything).
    2563             :          */
    2564        1356 :         if (gs->set &&
    2565         664 :             !bms_overlap_list(gd->unhashable_refs, gs->set))
    2566             :         {
    2567         648 :             rollup->hashable = true;
    2568         648 :             gd->any_hashable = true;
    2569             :         }
    2570             : 
    2571             :         /*
    2572             :          * Now that we've pinned down an order for the groupClause for this
    2573             :          * list of grouping sets, we need to remap the entries in the grouping
    2574             :          * sets from sortgrouprefs to plain indices (0-based) into the
    2575             :          * groupClause for this collection of grouping sets. We keep the
    2576             :          * original form for later use, though.
    2577             :          */
    2578         692 :         rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
    2579             :                                                  current_sets,
    2580             :                                                  gd->tleref_to_colnum_map);
    2581         692 :         rollup->gsets_data = current_sets;
    2582             : 
    2583         692 :         gd->rollups = lappend(gd->rollups, rollup);
    2584             :     }
    2585             : 
    2586         432 :     if (gd->unsortable_sets)
    2587             :     {
    2588             :         /*
    2589             :          * We have not yet pinned down a groupclause for this, but we will
    2590             :          * need index-based lists for estimation purposes. Construct
    2591             :          * hash_sets_idx based on the entire original groupclause for now.
    2592             :          */
    2593          24 :         gd->hash_sets_idx = remap_to_groupclause_idx(parse->groupClause,
    2594             :                                                      gd->unsortable_sets,
    2595             :                                                      gd->tleref_to_colnum_map);
    2596          24 :         gd->any_hashable = true;
    2597             :     }
    2598             : 
    2599         432 :     return gd;
    2600             : }
    2601             : 
    2602             : /*
    2603             :  * Given a groupclause and a list of GroupingSetData, return equivalent sets
    2604             :  * (without annotation) mapped to indexes into the given groupclause.
    2605             :  */
    2606             : static List *
    2607        1892 : remap_to_groupclause_idx(List *groupClause,
    2608             :                          List *gsets,
    2609             :                          int *tleref_to_colnum_map)
    2610             : {
    2611        1892 :     int         ref = 0;
    2612        1892 :     List       *result = NIL;
    2613             :     ListCell   *lc;
    2614             : 
    2615        4556 :     foreach(lc, groupClause)
    2616             :     {
    2617        2664 :         SortGroupClause *gc = lfirst_node(SortGroupClause, lc);
    2618             : 
    2619        2664 :         tleref_to_colnum_map[gc->tleSortGroupRef] = ref++;
    2620             :     }
    2621             : 
    2622        4380 :     foreach(lc, gsets)
    2623             :     {
    2624        2488 :         List       *set = NIL;
    2625             :         ListCell   *lc2;
    2626        2488 :         GroupingSetData *gs = lfirst_node(GroupingSetData, lc);
    2627             : 
    2628        5448 :         foreach(lc2, gs->set)
    2629             :         {
    2630        2960 :             set = lappend_int(set, tleref_to_colnum_map[lfirst_int(lc2)]);
    2631             :         }
    2632             : 
    2633        2488 :         result = lappend(result, set);
    2634             :     }
    2635             : 
    2636        1892 :     return result;
    2637             : }
    2638             : 
    2639             : 
    2640             : /*
    2641             :  * preprocess_rowmarks - set up PlanRowMarks if needed
    2642             :  */
    2643             : static void
    2644      301560 : preprocess_rowmarks(PlannerInfo *root)
    2645             : {
    2646      301560 :     Query      *parse = root->parse;
    2647             :     Bitmapset  *rels;
    2648             :     List       *prowmarks;
    2649             :     ListCell   *l;
    2650             :     int         i;
    2651             : 
    2652      301560 :     if (parse->rowMarks)
    2653             :     {
    2654             :         /*
    2655             :          * We've got trouble if FOR [KEY] UPDATE/SHARE appears inside
    2656             :          * grouping, since grouping renders a reference to individual tuple
    2657             :          * CTIDs invalid.  This is also checked at parse time, but that's
    2658             :          * insufficient because of rule substitution, query pullup, etc.
    2659             :          */
    2660        4866 :         CheckSelectLocking(parse, linitial_node(RowMarkClause,
    2661             :                                                 parse->rowMarks)->strength);
    2662             :     }
    2663             :     else
    2664             :     {
    2665             :         /*
    2666             :          * We only need rowmarks for UPDATE, DELETE, or FOR [KEY]
    2667             :          * UPDATE/SHARE.
    2668             :          */
    2669      583940 :         if (parse->commandType != CMD_UPDATE &&
    2670      287246 :             parse->commandType != CMD_DELETE)
    2671      284330 :             return;
    2672             :     }
    2673             : 
    2674             :     /*
    2675             :      * We need to have rowmarks for all base relations except the target. We
    2676             :      * make a bitmapset of all base rels and then remove the items we don't
    2677             :      * need or have FOR [KEY] UPDATE/SHARE marks for.
    2678             :      */
    2679       17230 :     rels = get_relids_in_jointree((Node *) parse->jointree, false);
    2680       17230 :     if (parse->resultRelation)
    2681       12364 :         rels = bms_del_member(rels, parse->resultRelation);
    2682             : 
    2683             :     /*
    2684             :      * Convert RowMarkClauses to PlanRowMark representation.
    2685             :      */
    2686       17230 :     prowmarks = NIL;
    2687       22318 :     foreach(l, parse->rowMarks)
    2688             :     {
    2689        5088 :         RowMarkClause *rc = lfirst_node(RowMarkClause, l);
    2690        5088 :         RangeTblEntry *rte = rt_fetch(rc->rti, parse->rtable);
    2691             :         PlanRowMark *newrc;
    2692             : 
    2693             :         /*
    2694             :          * Currently, it is syntactically impossible to have FOR UPDATE et al
    2695             :          * applied to an update/delete target rel.  If that ever becomes
    2696             :          * possible, we should drop the target from the PlanRowMark list.
    2697             :          */
    2698             :         Assert(rc->rti != parse->resultRelation);
    2699             : 
    2700             :         /*
    2701             :          * Ignore RowMarkClauses for subqueries; they aren't real tables and
    2702             :          * can't support true locking.  Subqueries that got flattened into the
    2703             :          * main query should be ignored completely.  Any that didn't will get
    2704             :          * ROW_MARK_COPY items in the next loop.
    2705             :          */
    2706        5088 :         if (rte->rtekind != RTE_RELATION)
    2707          76 :             continue;
    2708             : 
    2709        5012 :         rels = bms_del_member(rels, rc->rti);
    2710             : 
    2711        5012 :         newrc = makeNode(PlanRowMark);
    2712        5012 :         newrc->rti = newrc->prti = rc->rti;
    2713        5012 :         newrc->rowmarkId = ++(root->glob->lastRowMarkId);
    2714        5012 :         newrc->markType = select_rowmark_type(rte, rc->strength);
    2715        5012 :         newrc->allMarkTypes = (1 << newrc->markType);
    2716        5012 :         newrc->strength = rc->strength;
    2717        5012 :         newrc->waitPolicy = rc->waitPolicy;
    2718        5012 :         newrc->isParent = false;
    2719             : 
    2720        5012 :         prowmarks = lappend(prowmarks, newrc);
    2721             :     }
    2722             : 
    2723             :     /*
    2724             :      * Now, add rowmarks for any non-target, non-locked base relations.
    2725             :      */
    2726       17230 :     i = 0;
    2727       38136 :     foreach(l, parse->rtable)
    2728             :     {
    2729       20906 :         RangeTblEntry *rte = lfirst_node(RangeTblEntry, l);
    2730             :         PlanRowMark *newrc;
    2731             : 
    2732       20906 :         i++;
    2733       20906 :         if (!bms_is_member(i, rels))
    2734       19902 :             continue;
    2735             : 
    2736        1004 :         newrc = makeNode(PlanRowMark);
    2737        1004 :         newrc->rti = newrc->prti = i;
    2738        1004 :         newrc->rowmarkId = ++(root->glob->lastRowMarkId);
    2739        1004 :         newrc->markType = select_rowmark_type(rte, LCS_NONE);
    2740        1004 :         newrc->allMarkTypes = (1 << newrc->markType);
    2741        1004 :         newrc->strength = LCS_NONE;
    2742        1004 :         newrc->waitPolicy = LockWaitBlock;   /* doesn't matter */
    2743        1004 :         newrc->isParent = false;
    2744             : 
    2745        1004 :         prowmarks = lappend(prowmarks, newrc);
    2746             :     }
    2747             : 
    2748       17230 :     root->rowMarks = prowmarks;
    2749             : }
    2750             : 
    2751             : /*
    2752             :  * Select RowMarkType to use for a given table
    2753             :  */
    2754             : RowMarkType
    2755        7202 : select_rowmark_type(RangeTblEntry *rte, LockClauseStrength strength)
    2756             : {
    2757        7202 :     if (rte->rtekind != RTE_RELATION)
    2758             :     {
    2759             :         /* If it's not a table at all, use ROW_MARK_COPY */
    2760         174 :         return ROW_MARK_COPY;
    2761             :     }
    2762        7028 :     else if (rte->relkind == RELKIND_FOREIGN_TABLE)
    2763             :     {
    2764             :         /* Let the FDW select the rowmark type, if it wants to */
    2765         160 :         FdwRoutine *fdwroutine = GetFdwRoutineByRelId(rte->relid);
    2766             : 
    2767         160 :         if (fdwroutine->GetForeignRowMarkType != NULL)
    2768           0 :             return fdwroutine->GetForeignRowMarkType(rte, strength);
    2769             :         /* Otherwise, use ROW_MARK_COPY by default */
    2770         160 :         return ROW_MARK_COPY;
    2771             :     }
    2772             :     else
    2773             :     {
    2774             :         /* Regular table, apply the appropriate lock type */
    2775        6868 :         switch (strength)
    2776             :         {
    2777             :             case LCS_NONE:
    2778             : 
    2779             :                 /*
    2780             :                  * We don't need a tuple lock, only the ability to re-fetch
    2781             :                  * the row.
    2782             :                  */
    2783        1146 :                 return ROW_MARK_REFERENCE;
    2784             :                 break;
    2785             :             case LCS_FORKEYSHARE:
    2786        4150 :                 return ROW_MARK_KEYSHARE;
    2787             :                 break;
    2788             :             case LCS_FORSHARE:
    2789         234 :                 return ROW_MARK_SHARE;
    2790             :                 break;
    2791             :             case LCS_FORNOKEYUPDATE:
    2792          58 :                 return ROW_MARK_NOKEYEXCLUSIVE;
    2793             :                 break;
    2794             :             case LCS_FORUPDATE:
    2795        1280 :                 return ROW_MARK_EXCLUSIVE;
    2796             :                 break;
    2797             :         }
    2798           0 :         elog(ERROR, "unrecognized LockClauseStrength %d", (int) strength);
    2799             :         return ROW_MARK_EXCLUSIVE;  /* keep compiler quiet */
    2800             :     }
    2801             : }
    2802             : 
    2803             : /*
    2804             :  * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
    2805             :  *
    2806             :  * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
    2807             :  * results back in *count_est and *offset_est.  These variables are set to
    2808             :  * 0 if the corresponding clause is not present, and -1 if it's present
    2809             :  * but we couldn't estimate the value for it.  (The "0" convention is OK
    2810             :  * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
    2811             :  * LIMIT 0 as though it were LIMIT 1.  But this is in line with the planner's
    2812             :  * usual practice of never estimating less than one row.)  These values will
    2813             :  * be passed to create_limit_path, which see if you change this code.
    2814             :  *
    2815             :  * The return value is the suitably adjusted tuple_fraction to use for
    2816             :  * planning the query.  This adjustment is not overridable, since it reflects
    2817             :  * plan actions that grouping_planner() will certainly take, not assumptions
    2818             :  * about context.
    2819             :  */
    2820             : static double
    2821        3054 : preprocess_limit(PlannerInfo *root, double tuple_fraction,
    2822             :                  int64 *offset_est, int64 *count_est)
    2823             : {
    2824        3054 :     Query      *parse = root->parse;
    2825             :     Node       *est;
    2826             :     double      limit_fraction;
    2827             : 
    2828             :     /* Should not be called unless LIMIT or OFFSET */
    2829             :     Assert(parse->limitCount || parse->limitOffset);
    2830             : 
    2831             :     /*
    2832             :      * Try to obtain the clause values.  We use estimate_expression_value
    2833             :      * primarily because it can sometimes do something useful with Params.
    2834             :      */
    2835        3054 :     if (parse->limitCount)
    2836             :     {
    2837        2836 :         est = estimate_expression_value(root, parse->limitCount);
    2838        2836 :         if (est && IsA(est, Const))
    2839             :         {
    2840        5664 :             if (((Const *) est)->constisnull)
    2841             :             {
    2842             :                 /* NULL indicates LIMIT ALL, ie, no limit */
    2843           0 :                 *count_est = 0; /* treat as not present */
    2844             :             }
    2845             :             else
    2846             :             {
    2847        2832 :                 *count_est = DatumGetInt64(((Const *) est)->constvalue);
    2848        2832 :                 if (*count_est <= 0)
    2849          96 :                     *count_est = 1; /* force to at least 1 */
    2850             :             }
    2851             :         }
    2852             :         else
    2853           4 :             *count_est = -1;    /* can't estimate */
    2854             :     }
    2855             :     else
    2856         218 :         *count_est = 0;         /* not present */
    2857             : 
    2858        3054 :     if (parse->limitOffset)
    2859             :     {
    2860         536 :         est = estimate_expression_value(root, parse->limitOffset);
    2861         536 :         if (est && IsA(est, Const))
    2862             :         {
    2863        1040 :             if (((Const *) est)->constisnull)
    2864             :             {
    2865             :                 /* Treat NULL as no offset; the executor will too */
    2866           0 :                 *offset_est = 0;    /* treat as not present */
    2867             :             }
    2868             :             else
    2869             :             {
    2870         520 :                 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
    2871         520 :                 if (*offset_est < 0)
    2872           0 :                     *offset_est = 0;    /* treat as not present */
    2873             :             }
    2874             :         }
    2875             :         else
    2876          16 :             *offset_est = -1;   /* can't estimate */
    2877             :     }
    2878             :     else
    2879        2518 :         *offset_est = 0;        /* not present */
    2880             : 
    2881        3054 :     if (*count_est != 0)
    2882             :     {
    2883             :         /*
    2884             :          * A LIMIT clause limits the absolute number of tuples returned.
    2885             :          * However, if it's not a constant LIMIT then we have to guess; for
    2886             :          * lack of a better idea, assume 10% of the plan's result is wanted.
    2887             :          */
    2888        2836 :         if (*count_est < 0 || *offset_est < 0)
    2889             :         {
    2890             :             /* LIMIT or OFFSET is an expression ... punt ... */
    2891          16 :             limit_fraction = 0.10;
    2892             :         }
    2893             :         else
    2894             :         {
    2895             :             /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
    2896        2820 :             limit_fraction = (double) *count_est + (double) *offset_est;
    2897             :         }
    2898             : 
    2899             :         /*
    2900             :          * If we have absolute limits from both caller and LIMIT, use the
    2901             :          * smaller value; likewise if they are both fractional.  If one is
    2902             :          * fractional and the other absolute, we can't easily determine which
    2903             :          * is smaller, but we use the heuristic that the absolute will usually
    2904             :          * be smaller.
    2905             :          */
    2906        2836 :         if (tuple_fraction >= 1.0)
    2907             :         {
    2908           4 :             if (limit_fraction >= 1.0)
    2909             :             {
    2910             :                 /* both absolute */
    2911           4 :                 tuple_fraction = Min(tuple_fraction, limit_fraction);
    2912             :             }
    2913             :             else
    2914             :             {
    2915             :                 /* caller absolute, limit fractional; use caller's value */
    2916             :             }
    2917             :         }
    2918        2832 :         else if (tuple_fraction > 0.0)
    2919             :         {
    2920          94 :             if (limit_fraction >= 1.0)
    2921             :             {
    2922             :                 /* caller fractional, limit absolute; use limit */
    2923          94 :                 tuple_fraction = limit_fraction;
    2924             :             }
    2925             :             else
    2926             :             {
    2927             :                 /* both fractional */
    2928           0 :                 tuple_fraction = Min(tuple_fraction, limit_fraction);
    2929             :             }
    2930             :         }
    2931             :         else
    2932             :         {
    2933             :             /* no info from caller, just use limit */
    2934        2738 :             tuple_fraction = limit_fraction;
    2935             :         }
    2936             :     }
    2937         218 :     else if (*offset_est != 0 && tuple_fraction > 0.0)
    2938             :     {
    2939             :         /*
    2940             :          * We have an OFFSET but no LIMIT.  This acts entirely differently
    2941             :          * from the LIMIT case: here, we need to increase rather than decrease
    2942             :          * the caller's tuple_fraction, because the OFFSET acts to cause more
    2943             :          * tuples to be fetched instead of fewer.  This only matters if we got
    2944             :          * a tuple_fraction > 0, however.
    2945             :          *
    2946             :          * As above, use 10% if OFFSET is present but unestimatable.
    2947             :          */
    2948           8 :         if (*offset_est < 0)
    2949           0 :             limit_fraction = 0.10;
    2950             :         else
    2951           8 :             limit_fraction = (double) *offset_est;
    2952             : 
    2953             :         /*
    2954             :          * If we have absolute counts from both caller and OFFSET, add them
    2955             :          * together; likewise if they are both fractional.  If one is
    2956             :          * fractional and the other absolute, we want to take the larger, and
    2957             :          * we heuristically assume that's the fractional one.
    2958             :          */
    2959           8 :         if (tuple_fraction >= 1.0)
    2960             :         {
    2961           0 :             if (limit_fraction >= 1.0)
    2962             :             {
    2963             :                 /* both absolute, so add them together */
    2964           0 :                 tuple_fraction += limit_fraction;
    2965             :             }
    2966             :             else
    2967             :             {
    2968             :                 /* caller absolute, limit fractional; use limit */
    2969           0 :                 tuple_fraction = limit_fraction;
    2970             :             }
    2971             :         }
    2972             :         else
    2973             :         {
    2974           8 :             if (limit_fraction >= 1.0)
    2975             :             {
    2976             :                 /* caller fractional, limit absolute; use caller's value */
    2977             :             }
    2978             :             else
    2979             :             {
    2980             :                 /* both fractional, so add them together */
    2981           0 :                 tuple_fraction += limit_fraction;
    2982           0 :                 if (tuple_fraction >= 1.0)
    2983           0 :                     tuple_fraction = 0.0;   /* assume fetch all */
    2984             :             }
    2985             :         }
    2986             :     }
    2987             : 
    2988        3054 :     return tuple_fraction;
    2989             : }
    2990             : 
    2991             : /*
    2992             :  * limit_needed - do we actually need a Limit plan node?
    2993             :  *
    2994             :  * If we have constant-zero OFFSET and constant-null LIMIT, we can skip adding
    2995             :  * a Limit node.  This is worth checking for because "OFFSET 0" is a common
    2996             :  * locution for an optimization fence.  (Because other places in the planner
    2997             :  * merely check whether parse->limitOffset isn't NULL, it will still work as
    2998             :  * an optimization fence --- we're just suppressing unnecessary run-time
    2999             :  * overhead.)
    3000             :  *
    3001             :  * This might look like it could be merged into preprocess_limit, but there's
    3002             :  * a key distinction: here we need hard constants in OFFSET/LIMIT, whereas
    3003             :  * in preprocess_limit it's good enough to consider estimated values.
    3004             :  */
    3005             : bool
    3006      622738 : limit_needed(Query *parse)
    3007             : {
    3008             :     Node       *node;
    3009             : 
    3010      622738 :     node = parse->limitCount;
    3011      622738 :     if (node)
    3012             :     {
    3013        6494 :         if (IsA(node, Const))
    3014             :         {
    3015             :             /* NULL indicates LIMIT ALL, ie, no limit */
    3016        6402 :             if (!((Const *) node)->constisnull)
    3017        6402 :                 return true;    /* LIMIT with a constant value */
    3018             :         }
    3019             :         else
    3020          92 :             return true;        /* non-constant LIMIT */
    3021             :     }
    3022             : 
    3023      616244 :     node = parse->limitOffset;
    3024      616244 :     if (node)
    3025             :     {
    3026         648 :         if (IsA(node, Const))
    3027             :         {
    3028             :             /* Treat NULL as no offset; the executor would too */
    3029         502 :             if (!((Const *) node)->constisnull)
    3030             :             {
    3031         502 :                 int64       offset = DatumGetInt64(((Const *) node)->constvalue);
    3032             : 
    3033         502 :                 if (offset != 0)
    3034          56 :                     return true;    /* OFFSET with a nonzero value */
    3035             :             }
    3036             :         }
    3037             :         else
    3038         146 :             return true;        /* non-constant OFFSET */
    3039             :     }
    3040             : 
    3041      616042 :     return false;               /* don't need a Limit plan node */
    3042             : }
    3043             : 
    3044             : 
    3045             : /*
    3046             :  * remove_useless_groupby_columns
    3047             :  *      Remove any columns in the GROUP BY clause that are redundant due to
    3048             :  *      being functionally dependent on other GROUP BY columns.
    3049             :  *
    3050             :  * Since some other DBMSes do not allow references to ungrouped columns, it's
    3051             :  * not unusual to find all columns listed in GROUP BY even though listing the
    3052             :  * primary-key columns would be sufficient.  Deleting such excess columns
    3053             :  * avoids redundant sorting work, so it's worth doing.  When we do this, we
    3054             :  * must mark the plan as dependent on the pkey constraint (compare the
    3055             :  * parser's check_ungrouped_columns() and check_functional_grouping()).
    3056             :  *
    3057             :  * In principle, we could treat any NOT-NULL columns appearing in a UNIQUE
    3058             :  * index as the determining columns.  But as with check_functional_grouping(),
    3059             :  * there's currently no way to represent dependency on a NOT NULL constraint,
    3060             :  * so we consider only the pkey for now.
    3061             :  */
    3062             : static void
    3063      300176 : remove_useless_groupby_columns(PlannerInfo *root)
    3064             : {
    3065      300176 :     Query      *parse = root->parse;
    3066             :     Bitmapset **groupbyattnos;
    3067             :     Bitmapset **surplusvars;
    3068             :     ListCell   *lc;
    3069             :     int         relid;
    3070             : 
    3071             :     /* No chance to do anything if there are less than two GROUP BY items */
    3072      300176 :     if (list_length(parse->groupClause) < 2)
    3073      299384 :         return;
    3074             : 
    3075             :     /* Don't fiddle with the GROUP BY clause if the query has grouping sets */
    3076         792 :     if (parse->groupingSets)
    3077         352 :         return;
    3078             : 
    3079             :     /*
    3080             :      * Scan the GROUP BY clause to find GROUP BY items that are simple Vars.
    3081             :      * Fill groupbyattnos[k] with a bitmapset of the column attnos of RTE k
    3082             :      * that are GROUP BY items.
    3083             :      */
    3084         440 :     groupbyattnos = (Bitmapset **) palloc0(sizeof(Bitmapset *) *
    3085         440 :                                            (list_length(parse->rtable) + 1));
    3086        1576 :     foreach(lc, parse->groupClause)
    3087             :     {
    3088        1136 :         SortGroupClause *sgc = lfirst_node(SortGroupClause, lc);
    3089        1136 :         TargetEntry *tle = get_sortgroupclause_tle(sgc, parse->targetList);
    3090        1136 :         Var        *var = (Var *) tle->expr;
    3091             : 
    3092             :         /*
    3093             :          * Ignore non-Vars and Vars from other query levels.
    3094             :          *
    3095             :          * XXX in principle, stable expressions containing Vars could also be
    3096             :          * removed, if all the Vars are functionally dependent on other GROUP
    3097             :          * BY items.  But it's not clear that such cases occur often enough to
    3098             :          * be worth troubling over.
    3099             :          */
    3100        2116 :         if (!IsA(var, Var) ||
    3101         980 :             var->varlevelsup > 0)
    3102         156 :             continue;
    3103             : 
    3104             :         /* OK, remember we have this Var */
    3105         980 :         relid = var->varno;
    3106             :         Assert(relid <= list_length(parse->rtable));
    3107        1960 :         groupbyattnos[relid] = bms_add_member(groupbyattnos[relid],
    3108         980 :                                               var->varattno - FirstLowInvalidHeapAttributeNumber);
    3109             :     }
    3110             : 
    3111             :     /*
    3112             :      * Consider each relation and see if it is possible to remove some of its
    3113             :      * Vars from GROUP BY.  For simplicity and speed, we do the actual removal
    3114             :      * in a separate pass.  Here, we just fill surplusvars[k] with a bitmapset
    3115             :      * of the column attnos of RTE k that are removable GROUP BY items.
    3116             :      */
    3117         440 :     surplusvars = NULL;         /* don't allocate array unless required */
    3118         440 :     relid = 0;
    3119        1444 :     foreach(lc, parse->rtable)
    3120             :     {
    3121        1004 :         RangeTblEntry *rte = lfirst_node(RangeTblEntry, lc);
    3122             :         Bitmapset  *relattnos;
    3123             :         Bitmapset  *pkattnos;
    3124             :         Oid         constraintOid;
    3125             : 
    3126        1004 :         relid++;
    3127             : 
    3128             :         /* Only plain relations could have primary-key constraints */
    3129        1004 :         if (rte->rtekind != RTE_RELATION)
    3130        1262 :             continue;
    3131             : 
    3132             :         /*
    3133             :          * We must skip inheritance parent tables as some of the child rels
    3134             :          * may cause duplicate rows.  This cannot happen with partitioned
    3135             :          * tables, however.
    3136             :          */
    3137         700 :         if (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE)
    3138           4 :             continue;
    3139             : 
    3140             :         /* Nothing to do unless this rel has multiple Vars in GROUP BY */
    3141         696 :         relattnos = groupbyattnos[relid];
    3142         696 :         if (bms_membership(relattnos) != BMS_MULTIPLE)
    3143         408 :             continue;
    3144             : 
    3145             :         /*
    3146             :          * Can't remove any columns for this rel if there is no suitable
    3147             :          * (i.e., nondeferrable) primary key constraint.
    3148             :          */
    3149         288 :         pkattnos = get_primary_key_attnos(rte->relid, false, &constraintOid);
    3150         288 :         if (pkattnos == NULL)
    3151         242 :             continue;
    3152             : 
    3153             :         /*
    3154             :          * If the primary key is a proper subset of relattnos then we have
    3155             :          * some items in the GROUP BY that can be removed.
    3156             :          */
    3157          46 :         if (bms_subset_compare(pkattnos, relattnos) == BMS_SUBSET1)
    3158             :         {
    3159             :             /*
    3160             :              * To easily remember whether we've found anything to do, we don't
    3161             :              * allocate the surplusvars[] array until we find something.
    3162             :              */
    3163          34 :             if (surplusvars == NULL)
    3164          30 :                 surplusvars = (Bitmapset **) palloc0(sizeof(Bitmapset *) *
    3165          30 :                                                      (list_length(parse->rtable) + 1));
    3166             : 
    3167             :             /* Remember the attnos of the removable columns */
    3168          34 :             surplusvars[relid] = bms_difference(relattnos, pkattnos);
    3169             : 
    3170             :             /* Also, mark the resulting plan as dependent on this constraint */
    3171          34 :             parse->constraintDeps = lappend_oid(parse->constraintDeps,
    3172             :                                                 constraintOid);
    3173             :         }
    3174             :     }
    3175             : 
    3176             :     /*
    3177             :      * If we found any surplus Vars, build a new GROUP BY clause without them.
    3178             :      * (Note: this may leave some TLEs with unreferenced ressortgroupref
    3179             :      * markings, but that's harmless.)
    3180             :      */
    3181         440 :     if (surplusvars != NULL)
    3182             :     {
    3183          30 :         List       *new_groupby = NIL;
    3184             : 
    3185         150 :         foreach(lc, parse->groupClause)
    3186             :         {
    3187         120 :             SortGroupClause *sgc = lfirst_node(SortGroupClause, lc);
    3188         120 :             TargetEntry *tle = get_sortgroupclause_tle(sgc, parse->targetList);
    3189         120 :             Var        *var = (Var *) tle->expr;
    3190             : 
    3191             :             /*
    3192             :              * New list must include non-Vars, outer Vars, and anything not
    3193             :              * marked as surplus.
    3194             :              */
    3195         240 :             if (!IsA(var, Var) ||
    3196         240 :                 var->varlevelsup > 0 ||
    3197         120 :                 !bms_is_member(var->varattno - FirstLowInvalidHeapAttributeNumber,
    3198         120 :                                surplusvars[var->varno]))
    3199          66 :                 new_groupby = lappend(new_groupby, sgc);
    3200             :         }
    3201             : 
    3202          30 :         parse->groupClause = new_groupby;
    3203             :     }
    3204             : }
    3205             : 
    3206             : /*
    3207             :  * preprocess_groupclause - do preparatory work on GROUP BY clause
    3208             :  *
    3209             :  * The idea here is to adjust the ordering of the GROUP BY elements
    3210             :  * (which in itself is semantically insignificant) to match ORDER BY,
    3211             :  * thereby allowing a single sort operation to both implement the ORDER BY
    3212             :  * requirement and set up for a Unique step that implements GROUP BY.
    3213             :  *
    3214             :  * In principle it might be interesting to consider other orderings of the
    3215             :  * GROUP BY elements, which could match the sort ordering of other
    3216             :  * possible plans (eg an indexscan) and thereby reduce cost.  We don't
    3217             :  * bother with that, though.  Hashed grouping will frequently win anyway.
    3218             :  *
    3219             :  * Note: we need no comparable processing of the distinctClause because
    3220             :  * the parser already enforced that that matches ORDER BY.
    3221             :  *
    3222             :  * For grouping sets, the order of items is instead forced to agree with that
    3223             :  * of the grouping set (and items not in the grouping set are skipped). The
    3224             :  * work of sorting the order of grouping set elements to match the ORDER BY if
    3225             :  * possible is done elsewhere.
    3226             :  */
    3227             : static List *
    3228        3544 : preprocess_groupclause(PlannerInfo *root, List *force)
    3229             : {
    3230        3544 :     Query      *parse = root->parse;
    3231        3544 :     List       *new_groupclause = NIL;
    3232             :     bool        partial_match;
    3233             :     ListCell   *sl;
    3234             :     ListCell   *gl;
    3235             : 
    3236             :     /* For grouping sets, we need to force the ordering */
    3237        3544 :     if (force)
    3238             :     {
    3239        4452 :         foreach(sl, force)
    3240             :         {
    3241        2612 :             Index       ref = lfirst_int(sl);
    3242        2612 :             SortGroupClause *cl = get_sortgroupref_clause(ref, parse->groupClause);
    3243             : 
    3244        2612 :             new_groupclause = lappend(new_groupclause, cl);
    3245             :         }
    3246             : 
    3247        1840 :         return new_groupclause;
    3248             :     }
    3249             : 
    3250             :     /* If no ORDER BY, nothing useful to do here */
    3251        1704 :     if (parse->sortClause == NIL)
    3252         762 :         return parse->groupClause;
    3253             : 
    3254             :     /*
    3255             :      * Scan the ORDER BY clause and construct a list of matching GROUP BY
    3256             :      * items, but only as far as we can make a matching prefix.
    3257             :      *
    3258             :      * This code assumes that the sortClause contains no duplicate items.
    3259             :      */
    3260        1852 :     foreach(sl, parse->sortClause)
    3261             :     {
    3262        1280 :         SortGroupClause *sc = lfirst_node(SortGroupClause, sl);
    3263             : 
    3264        1898 :         foreach(gl, parse->groupClause)
    3265             :         {
    3266        1528 :             SortGroupClause *gc = lfirst_node(SortGroupClause, gl);
    3267             : 
    3268        1528 :             if (equal(gc, sc))
    3269             :             {
    3270         910 :                 new_groupclause = lappend(new_groupclause, gc);
    3271         910 :                 break;
    3272             :             }
    3273             :         }
    3274        1280 :         if (gl == NULL)
    3275         370 :             break;              /* no match, so stop scanning */
    3276             :     }
    3277             : 
    3278             :     /* Did we match all of the ORDER BY list, or just some of it? */
    3279         942 :     partial_match = (sl != NULL);
    3280             : 
    3281             :     /* If no match at all, no point in reordering GROUP BY */
    3282         942 :     if (new_groupclause == NIL)
    3283         144 :         return parse->groupClause;
    3284             : 
    3285             :     /*
    3286             :      * Add any remaining GROUP BY items to the new list, but only if we were
    3287             :      * able to make a complete match.  In other words, we only rearrange the
    3288             :      * GROUP BY list if the result is that one list is a prefix of the other
    3289             :      * --- otherwise there's no possibility of a common sort.  Also, give up
    3290             :      * if there are any non-sortable GROUP BY items, since then there's no
    3291             :      * hope anyway.
    3292             :      */
    3293        1740 :     foreach(gl, parse->groupClause)
    3294             :     {
    3295         992 :         SortGroupClause *gc = lfirst_node(SortGroupClause, gl);
    3296             : 
    3297         992 :         if (list_member_ptr(new_groupclause, gc))
    3298         894 :             continue;           /* it matched an ORDER BY item */
    3299          98 :         if (partial_match)
    3300         100 :             return parse->groupClause;   /* give up, no common sort possible */
    3301          48 :         if (!OidIsValid(gc->sortop))
    3302           0 :             return parse->groupClause;   /* give up, GROUP BY can't be sorted */
    3303          48 :         new_groupclause = lappend(new_groupclause, gc);
    3304             :     }
    3305             : 
    3306             :     /* Success --- install the rearranged GROUP BY list */
    3307             :     Assert(list_length(parse->groupClause) == list_length(new_groupclause));
    3308         748 :     return new_groupclause;
    3309             : }
    3310             : 
    3311             : /*
    3312             :  * Extract lists of grouping sets that can be implemented using a single
    3313             :  * rollup-type aggregate pass each. Returns a list of lists of grouping sets.
    3314             :  *
    3315             :  * Input must be sorted with smallest sets first. Result has each sublist
    3316             :  * sorted with smallest sets first.
    3317             :  *
    3318             :  * We want to produce the absolute minimum possible number of lists here to
    3319             :  * avoid excess sorts. Fortunately, there is an algorithm for this; the problem
    3320             :  * of finding the minimal partition of a partially-ordered set into chains
    3321             :  * (which is what we need, taking the list of grouping sets as a poset ordered
    3322             :  * by set inclusion) can be mapped to the problem of finding the maximum
    3323             :  * cardinality matching on a bipartite graph, which is solvable in polynomial
    3324             :  * time with a worst case of no worse than O(n^2.5) and usually much
    3325             :  * better. Since our N is at most 4096, we don't need to consider fallbacks to
    3326             :  * heuristic or approximate methods.  (Planning time for a 12-d cube is under
    3327             :  * half a second on my modest system even with optimization off and assertions
    3328             :  * on.)
    3329             :  */
    3330             : static List *
    3331         428 : extract_rollup_sets(List *groupingSets)
    3332             : {
    3333         428 :     int         num_sets_raw = list_length(groupingSets);
    3334         428 :     int         num_empty = 0;
    3335         428 :     int         num_sets = 0;   /* distinct sets */
    3336         428 :     int         num_chains = 0;
    3337         428 :     List       *result = NIL;
    3338             :     List      **results;
    3339             :     List      **orig_sets;
    3340             :     Bitmapset **set_masks;
    3341             :     int        *chains;
    3342             :     short     **adjacency;
    3343             :     short      *adjacency_buf;
    3344             :     BipartiteMatchState *state;
    3345             :     int         i;
    3346             :     int         j;
    3347             :     int         j_size;
    3348         428 :     ListCell   *lc1 = list_head(groupingSets);
    3349             :     ListCell   *lc;
    3350             : 
    3351             :     /*
    3352             :      * Start by stripping out empty sets.  The algorithm doesn't require this,
    3353             :      * but the planner currently needs all empty sets to be returned in the
    3354             :      * first list, so we strip them here and add them back after.
    3355             :      */
    3356        1192 :     while (lc1 && lfirst(lc1) == NIL)
    3357             :     {
    3358         336 :         ++num_empty;
    3359         336 :         lc1 = lnext(groupingSets, lc1);
    3360             :     }
    3361             : 
    3362             :     /* bail out now if it turns out that all we had were empty sets. */
    3363         428 :     if (!lc1)
    3364          28 :         return list_make1(groupingSets);
    3365             : 
    3366             :     /*----------
    3367             :      * We don't strictly need to remove duplicate sets here, but if we don't,
    3368             :      * they tend to become scattered through the result, which is a bit
    3369             :      * confusing (and irritating if we ever decide to optimize them out).
    3370             :      * So we remove them here and add them back after.
    3371             :      *
    3372             :      * For each non-duplicate set, we fill in the following:
    3373             :      *
    3374             :      * orig_sets[i] = list of the original set lists
    3375             :      * set_masks[i] = bitmapset for testing inclusion
    3376             :      * adjacency[i] = array [n, v1, v2, ... vn] of adjacency indices
    3377             :      *
    3378             :      * chains[i] will be the result group this set is assigned to.
    3379             :      *
    3380             :      * We index all of these from 1 rather than 0 because it is convenient
    3381             :      * to leave 0 free for the NIL node in the graph algorithm.
    3382             :      *----------
    3383             :      */
    3384         400 :     orig_sets = palloc0((num_sets_raw + 1) * sizeof(List *));
    3385         400 :     set_masks = palloc0((num_sets_raw + 1) * sizeof(Bitmapset *));
    3386         400 :     adjacency = palloc0((num_sets_raw + 1) * sizeof(short *));
    3387         400 :     adjacency_buf = palloc((num_sets_raw + 1) * sizeof(short));
    3388             : 
    3389         400 :     j_size = 0;
    3390         400 :     j = 0;
    3391         400 :     i = 1;
    3392             : 
    3393        1348 :     for_each_cell(lc, groupingSets, lc1)
    3394             :     {
    3395         948 :         List       *candidate = (List *) lfirst(lc);
    3396         948 :         Bitmapset  *candidate_set = NULL;
    3397             :         ListCell   *lc2;
    3398         948 :         int         dup_of = 0;
    3399             : 
    3400        2264 :         foreach(lc2, candidate)
    3401             :         {
    3402        1316 :             candidate_set = bms_add_member(candidate_set, lfirst_int(lc2));
    3403             :         }
    3404             : 
    3405             :         /* we can only be a dup if we're the same length as a previous set */
    3406         948 :         if (j_size == list_length(candidate))
    3407             :         {
    3408             :             int         k;
    3409             : 
    3410         824 :             for (k = j; k < i; ++k)
    3411             :             {
    3412         528 :                 if (bms_equal(set_masks[k], candidate_set))
    3413             :                 {
    3414          52 :                     dup_of = k;
    3415          52 :                     break;
    3416             :                 }
    3417             :             }
    3418             :         }
    3419         600 :         else if (j_size < list_length(candidate))
    3420             :         {
    3421         600 :             j_size = list_length(candidate);
    3422         600 :             j = i;
    3423             :         }
    3424             : 
    3425         948 :         if (dup_of > 0)
    3426             :         {
    3427          52 :             orig_sets[dup_of] = lappend(orig_sets[dup_of], candidate);
    3428          52 :             bms_free(candidate_set);
    3429             :         }
    3430             :         else
    3431             :         {
    3432             :             int         k;
    3433         896 :             int         n_adj = 0;
    3434             : 
    3435         896 :             orig_sets[i] = list_make1(candidate);
    3436         896 :             set_masks[i] = candidate_set;
    3437             : 
    3438             :             /* fill in adjacency list; no need to compare equal-size sets */
    3439             : 
    3440        1360 :             for (k = j - 1; k > 0; --k)
    3441             :             {
    3442         464 :                 if (bms_is_subset(set_masks[k], candidate_set))
    3443         404 :                     adjacency_buf[++n_adj] = k;
    3444             :             }
    3445             : 
    3446         896 :             if (n_adj > 0)
    3447             :             {
    3448         232 :                 adjacency_buf[0] = n_adj;
    3449         232 :                 adjacency[i] = palloc((n_adj + 1) * sizeof(short));
    3450         232 :                 memcpy(adjacency[i], adjacency_buf, (n_adj + 1) * sizeof(short));
    3451             :             }
    3452             :             else
    3453         664 :                 adjacency[i] = NULL;
    3454             : 
    3455         896 :             ++i;
    3456             :         }
    3457             :     }
    3458             : 
    3459         400 :     num_sets = i - 1;
    3460             : 
    3461             :     /*
    3462             :      * Apply the graph matching algorithm to do the work.
    3463             :      */
    3464         400 :     state = BipartiteMatch(num_sets, num_sets, adjacency);
    3465             : 
    3466             :     /*
    3467             :      * Now, the state->pair* fields have the info we need to assign sets to
    3468             :      * chains. Two sets (u,v) belong to the same chain if pair_uv[u] = v or
    3469             :      * pair_vu[v] = u (both will be true, but we check both so that we can do
    3470             :      * it in one pass)
    3471             :      */
    3472         400 :     chains = palloc0((num_sets + 1) * sizeof(int));
    3473             : 
    3474        1296 :     for (i = 1; i <= num_sets; ++i)
    3475             :     {
    3476         896 :         int         u = state->pair_vu[i];
    3477         896 :         int         v = state->pair_uv[i];
    3478             : 
    3479         896 :         if (u > 0 && u < i)
    3480           0 :             chains[i] = chains[u];
    3481         896 :         else if (v > 0 && v < i)
    3482         232 :             chains[i] = chains[v];
    3483             :         else
    3484         664 :             chains[i] = ++num_chains;
    3485             :     }
    3486             : 
    3487             :     /* build result lists. */
    3488         400 :     results = palloc0((num_chains + 1) * sizeof(List *));
    3489             : 
    3490        1296 :     for (i = 1; i <= num_sets; ++i)
    3491             :     {
    3492         896 :         int         c = chains[i];
    3493             : 
    3494             :         Assert(c > 0);
    3495             : 
    3496         896 :         results[c] = list_concat(results[c], orig_sets[i]);
    3497             :     }
    3498             : 
    3499             :     /* push any empty sets back on the first list. */
    3500        1076 :     while (num_empty-- > 0)
    3501         276 :         results[1] = lcons(NIL, results[1]);
    3502             : 
    3503             :     /* make result list */
    3504        1064 :     for (i = 1; i <= num_chains; ++i)
    3505         664 :         result = lappend(result, results[i]);
    3506             : 
    3507             :     /*
    3508             :      * Free all the things.
    3509             :      *
    3510             :      * (This is over-fussy for small sets but for large sets we could have
    3511             :      * tied up a nontrivial amount of memory.)
    3512             :      */
    3513         400 :     BipartiteMatchFree(state);
    3514         400 :     pfree(results);
    3515         400 :     pfree(chains);
    3516        1296 :     for (i = 1; i <= num_sets; ++i)
    3517         896 :         if (adjacency[i])
    3518         232 :             pfree(adjacency[i]);
    3519         400 :     pfree(adjacency);
    3520         400 :     pfree(adjacency_buf);
    3521         400 :     pfree(orig_sets);
    3522        1296 :     for (i = 1; i <= num_sets; ++i)
    3523         896 :         bms_free(set_masks[i]);
    3524         400 :     pfree(set_masks);
    3525             : 
    3526         400 :     return result;
    3527             : }
    3528             : 
    3529             : /*
    3530             :  * Reorder the elements of a list of grouping sets such that they have correct
    3531             :  * prefix relationships. Also inserts the GroupingSetData annotations.
    3532             :  *
    3533             :  * The input must be ordered with smallest sets first; the result is returned
    3534             :  * with largest sets first.  Note that the result shares no list substructure
    3535             :  * with the input, so it's safe for the caller to modify it later.
    3536             :  *
    3537             :  * If we're passed in a sortclause, we follow its order of columns to the
    3538             :  * extent possible, to minimize the chance that we add unnecessary sorts.
    3539             :  * (We're trying here to ensure that GROUPING SETS ((a,b,c),(c)) ORDER BY c,b,a
    3540             :  * gets implemented in one pass.)
    3541             :  */
    3542             : static List *
    3543         692 : reorder_grouping_sets(List *groupingsets, List *sortclause)
    3544             : {
    3545             :     ListCell   *lc;
    3546         692 :     List       *previous = NIL;
    3547         692 :     List       *result = NIL;
    3548             : 
    3549        1976 :     foreach(lc, groupingsets)
    3550             :     {
    3551        1284 :         List       *candidate = (List *) lfirst(lc);
    3552        1284 :         List       *new_elems = list_difference_int(candidate, previous);
    3553        1284 :         GroupingSetData *gs = makeNode(GroupingSetData);
    3554             : 
    3555        2860 :         while (list_length(sortclause) > list_length(previous) &&
    3556         236 :                list_length(new_elems) > 0)
    3557             :         {
    3558         128 :             SortGroupClause *sc = list_nth(sortclause, list_length(previous));
    3559         128 :             int         ref = sc->tleSortGroupRef;
    3560             : 
    3561         128 :             if (list_member_int(new_elems, ref))
    3562             :             {
    3563          56 :                 previous = lappend_int(previous, ref);
    3564          56 :                 new_elems = list_delete_int(new_elems, ref);
    3565             :             }
    3566             :             else
    3567             :             {
    3568             :                 /* diverged from the sortclause; give up on it */
    3569          72 :                 sortclause = NIL;
    3570          72 :                 break;
    3571             :             }
    3572             :         }
    3573             : 
    3574        1284 :         previous = list_concat(previous, new_elems);
    3575             : 
    3576        1284 :         gs->set = list_copy(previous);
    3577        1284 :         result = lcons(gs, result);
    3578             :     }
    3579             : 
    3580         692 :     list_free(previous);
    3581             : 
    3582         692 :     return result;
    3583             : }
    3584             : 
    3585             : /*
    3586             :  * Compute query_pathkeys and other pathkeys during plan generation
    3587             :  */
    3588             : static void
    3589      301338 : standard_qp_callback(PlannerInfo *root, void *extra)
    3590             : {
    3591      301338 :     Query      *parse = root->parse;
    3592      301338 :     standard_qp_extra *qp_extra = (standard_qp_extra *) extra;
    3593      301338 :     List       *tlist = root->processed_tlist;
    3594      301338 :     List       *activeWindows = qp_extra->activeWindows;
    3595             : 
    3596             :     /*
    3597             :      * Calculate pathkeys that represent grouping/ordering requirements.  The
    3598             :      * sortClause is certainly sort-able, but GROUP BY and DISTINCT might not
    3599             :      * be, in which case we just leave their pathkeys empty.
    3600             :      */
    3601      303442 :     if (qp_extra->groupClause &&
    3602        2104 :         grouping_is_sortable(qp_extra->groupClause))
    3603        2104 :         root->group_pathkeys =
    3604        2104 :             make_pathkeys_for_sortclauses(root,
    3605             :                                           qp_extra->groupClause,
    3606             :                                           tlist);
    3607             :     else
    3608      299234 :         root->group_pathkeys = NIL;
    3609             : 
    3610             :     /* We consider only the first (bottom) window in pathkeys logic */
    3611      301338 :     if (activeWindows != NIL)
    3612             :     {
    3613        1112 :         WindowClause *wc = linitial_node(WindowClause, activeWindows);
    3614             : 
    3615        1112 :         root->window_pathkeys = make_pathkeys_for_window(root,
    3616             :                                                          wc,
    3617             :                                                          tlist);
    3618             :     }
    3619             :     else
    3620      300226 :         root->window_pathkeys = NIL;
    3621             : 
    3622      301724 :     if (parse->distinctClause &&
    3623         386 :         grouping_is_sortable(parse->distinctClause))
    3624         382 :         root->distinct_pathkeys =
    3625         382 :             make_pathkeys_for_sortclauses(root,
    3626             :                                           parse->distinctClause,
    3627             :                                           tlist);
    3628             :     else
    3629      300956 :         root->distinct_pathkeys = NIL;
    3630             : 
    3631      301338 :     root->sort_pathkeys =
    3632      301338 :         make_pathkeys_for_sortclauses(root,
    3633             :                                       parse->sortClause,
    3634             :                                       tlist);
    3635             : 
    3636             :     /*
    3637             :      * Figure out whether we want a sorted result from query_planner.
    3638             :      *
    3639             :      * If we have a sortable GROUP BY clause, then we want a result sorted
    3640             :      * properly for grouping.  Otherwise, if we have window functions to
    3641             :      * evaluate, we try to sort for the first window.  Otherwise, if there's a
    3642             :      * sortable DISTINCT clause that's more rigorous than the ORDER BY clause,
    3643             :      * we try to produce output that's sufficiently well sorted for the
    3644             :      * DISTINCT.  Otherwise, if there is an ORDER BY clause, we want to sort
    3645             :      * by the ORDER BY clause.
    3646             :      *
    3647             :      * Note: if we have both ORDER BY and GROUP BY, and ORDER BY is a superset
    3648             :      * of GROUP BY, it would be tempting to request sort by ORDER BY --- but
    3649             :      * that might just leave us failing to exploit an available sort order at
    3650             :      * all.  Needs more thought.  The choice for DISTINCT versus ORDER BY is
    3651             :      * much easier, since we know that the parser ensured that one is a
    3652             :      * superset of the other.
    3653             :      */
    3654      301338 :     if (root->group_pathkeys)
    3655        2030 :         root->query_pathkeys = root->group_pathkeys;
    3656      299308 :     else if (root->window_pathkeys)
    3657         968 :         root->query_pathkeys = root->window_pathkeys;
    3658      596680 :     else if (list_length(root->distinct_pathkeys) >
    3659      298340 :              list_length(root->sort_pathkeys))
    3660         236 :         root->query_pathkeys = root->distinct_pathkeys;
    3661      298104 :     else if (root->sort_pathkeys)
    3662       34346 :         root->query_pathkeys = root->sort_pathkeys;
    3663             :     else
    3664      263758 :         root->query_pathkeys = NIL;
    3665      301338 : }
    3666             : 
    3667             : /*
    3668             :  * Estimate number of groups produced by grouping clauses (1 if not grouping)
    3669             :  *
    3670             :  * path_rows: number of output rows from scan/join step
    3671             :  * gd: grouping sets data including list of grouping sets and their clauses
    3672             :  * target_list: target list containing group clause references
    3673             :  *
    3674             :  * If doing grouping sets, we also annotate the gsets data with the estimates
    3675             :  * for each set and each individual rollup list, with a view to later
    3676             :  * determining whether some combination of them could be hashed instead.
    3677             :  */
    3678             : static double
    3679       25780 : get_number_of_groups(PlannerInfo *root,
    3680             :                      double path_rows,
    3681             :                      grouping_sets_data *gd,
    3682             :                      List *target_list)
    3683             : {
    3684       25780 :     Query      *parse = root->parse;
    3685             :     double      dNumGroups;
    3686             : 
    3687       25780 :     if (parse->groupClause)
    3688             :     {
    3689             :         List       *groupExprs;
    3690             : 
    3691        3658 :         if (parse->groupingSets)
    3692             :         {
    3693             :             /* Add up the estimates for each grouping set */
    3694             :             ListCell   *lc;
    3695             :             ListCell   *lc2;
    3696             : 
    3697             :             Assert(gd);         /* keep Coverity happy */
    3698             : 
    3699         404 :             dNumGroups = 0;
    3700             : 
    3701        1068 :             foreach(lc, gd->rollups)
    3702             :             {
    3703         664 :                 RollupData *rollup = lfirst_node(RollupData, lc);
    3704             :                 ListCell   *lc;
    3705             : 
    3706         664 :                 groupExprs = get_sortgrouplist_exprs(rollup->groupClause,
    3707             :                                                      target_list);
    3708             : 
    3709         664 :                 rollup->numGroups = 0.0;
    3710             : 
    3711        1888 :                 forboth(lc, rollup->gsets, lc2, rollup->gsets_data)
    3712             :                 {
    3713        1224 :                     List       *gset = (List *) lfirst(lc);
    3714        1224 :                     GroupingSetData *gs = lfirst_node(GroupingSetData, lc2);
    3715        1224 :                     double      numGroups = estimate_num_groups(root,
    3716             :                                                                 groupExprs,
    3717             :                                                                 path_rows,
    3718             :                                                                 &gset);
    3719             : 
    3720        1224 :                     gs->numGroups = numGroups;
    3721        1224 :                     rollup->numGroups += numGroups;
    3722             :                 }
    3723             : 
    3724         664 :                 dNumGroups += rollup->numGroups;
    3725             :             }
    3726             : 
    3727         404 :             if (gd->hash_sets_idx)
    3728             :             {
    3729             :                 ListCell   *lc;
    3730             : 
    3731          24 :                 gd->dNumHashGroups = 0;
    3732             : 
    3733          24 :                 groupExprs = get_sortgrouplist_exprs(parse->groupClause,
    3734             :                                                      target_list);
    3735             : 
    3736          52 :                 forboth(lc, gd->hash_sets_idx, lc2, gd->unsortable_sets)
    3737             :                 {
    3738          28 :                     List       *gset = (List *) lfirst(lc);
    3739          28 :                     GroupingSetData *gs = lfirst_node(GroupingSetData, lc2);
    3740          28 :                     double      numGroups = estimate_num_groups(root,
    3741             :                                                                 groupExprs,
    3742             :                                                                 path_rows,
    3743             :                                                                 &gset);
    3744             : 
    3745          28 :                     gs->numGroups = numGroups;
    3746          28 :                     gd->dNumHashGroups += numGroups;
    3747             :                 }
    3748             : 
    3749          24 :                 dNumGroups += gd->dNumHashGroups;
    3750             :             }
    3751             :         }
    3752             :         else
    3753             :         {
    3754             :             /* Plain GROUP BY */
    3755        3254 :             groupExprs = get_sortgrouplist_exprs(parse->groupClause,
    3756             :                                                  target_list);
    3757             : 
    3758        3254 :             dNumGroups = estimate_num_groups(root, groupExprs, path_rows,
    3759             :                                              NULL);
    3760             :         }
    3761             :     }
    3762       22122 :     else if (parse->groupingSets)
    3763             :     {
    3764             :         /* Empty grouping sets ... one result row for each one */
    3765          28 :         dNumGroups = list_length(parse->groupingSets);
    3766             :     }
    3767       22094 :     else if (parse->hasAggs || root->hasHavingQual)
    3768             :     {
    3769             :         /* Plain aggregation, one result row */
    3770       22094 :         dNumGroups = 1;
    3771             :     }
    3772             :     else
    3773             :     {
    3774             :         /* Not grouping */
    3775           0 :         dNumGroups = 1;
    3776             :     }
    3777             : 
    3778       25780 :     return dNumGroups;
    3779             : }
    3780             : 
    3781             : /*
    3782             :  * create_grouping_paths
    3783             :  *
    3784             :  * Build a new upperrel containing Paths for grouping and/or aggregation.
    3785             :  * Along the way, we also build an upperrel for Paths which are partially
    3786             :  * grouped and/or aggregated.  A partially grouped and/or aggregated path
    3787             :  * needs a FinalizeAggregate node to complete the aggregation.  Currently,
    3788             :  * the only partially grouped paths we build are also partial paths; that
    3789             :  * is, they need a Gather and then a FinalizeAggregate.
    3790             :  *
    3791             :  * input_rel: contains the source-data Paths
    3792             :  * target: the pathtarget for the result Paths to compute
    3793             :  * agg_costs: cost info about all aggregates in query (in AGGSPLIT_SIMPLE mode)
    3794             :  * gd: grouping sets data including list of grouping sets and their clauses
    3795             :  *
    3796             :  * Note: all Paths in input_rel are expected to return the target computed
    3797             :  * by make_group_input_target.
    3798             :  */
    3799             : static RelOptInfo *
    3800       23820 : create_grouping_paths(PlannerInfo *root,
    3801             :                       RelOptInfo *input_rel,
    3802             :                       PathTarget *target,
    3803             :                       bool target_parallel_safe,
    3804             :                       const AggClauseCosts *agg_costs,
    3805             :                       grouping_sets_data *gd)
    3806             : {
    3807       23820 :     Query      *parse = root->parse;
    3808             :     RelOptInfo *grouped_rel;
    3809             :     RelOptInfo *partially_grouped_rel;
    3810             : 
    3811             :     /*
    3812             :      * Create grouping relation to hold fully aggregated grouping and/or
    3813             :      * aggregation paths.
    3814             :      */
    3815       23820 :     grouped_rel = make_grouping_rel(root, input_rel, target,
    3816             :                                     target_parallel_safe, parse->havingQual);
    3817             : 
    3818             :     /*
    3819             :      * Create either paths for a degenerate grouping or paths for ordinary
    3820             :      * grouping, as appropriate.
    3821             :      */
    3822       23820 :     if (is_degenerate_grouping(root))
    3823          12 :         create_degenerate_grouping_paths(root, input_rel, grouped_rel);
    3824             :     else
    3825             :     {
    3826       23808 :         int         flags = 0;
    3827             :         GroupPathExtraData extra;
    3828             : 
    3829             :         /*
    3830             :          * Determine whether it's possible to perform sort-based
    3831             :          * implementations of grouping.  (Note that if groupClause is empty,
    3832             :          * grouping_is_sortable() is trivially true, and all the
    3833             :          * pathkeys_contained_in() tests will succeed too, so that we'll
    3834             :          * consider every surviving input path.)
    3835             :          *
    3836             :          * If we have grouping sets, we might be able to sort some but not all
    3837             :          * of them; in this case, we need can_sort to be true as long as we
    3838             :          * must consider any sorted-input plan.
    3839             :          */
    3840       23808 :         if ((gd && gd->rollups != NIL)
    3841       23380 :             || grouping_is_sortable(parse->groupClause))
    3842       23804 :             flags |= GROUPING_CAN_USE_SORT;
    3843             : 
    3844             :         /*
    3845             :          * Determine whether we should consider hash-based implementations of
    3846             :          * grouping.
    3847             :          *
    3848             :          * Hashed aggregation only applies if we're grouping. If we have
    3849             :          * grouping sets, some groups might be hashable but others not; in
    3850             :          * this case we set can_hash true as long as there is nothing globally
    3851             :          * preventing us from hashing (and we should therefore consider plans
    3852             :          * with hashes).
    3853             :          *
    3854             :          * Executor doesn't support hashed aggregation with DISTINCT or ORDER
    3855             :          * BY aggregates.  (Doing so would imply storing *all* the input
    3856             :          * values in the hash table, and/or running many sorts in parallel,
    3857             :          * either of which seems like a certain loser.)  We similarly don't
    3858             :          * support ordered-set aggregates in hashed aggregation, but that case
    3859             :          * is also included in the numOrderedAggs count.
    3860             :          *
    3861             :          * Note: grouping_is_hashable() is much more expensive to check than
    3862             :          * the other gating conditions, so we want to do it last.
    3863             :          */
    3864       25916 :         if ((parse->groupClause != NIL &&
    3865        6028 :              agg_costs->numOrderedAggs == 0 &&
    3866        1960 :              (gd ? gd->any_hashable : grouping_is_hashable(parse->groupClause))))
    3867        1956 :             flags |= GROUPING_CAN_USE_HASH;
    3868             : 
    3869             :         /*
    3870             :          * Determine whether partial aggregation is possible.
    3871             :          */
    3872       23808 :         if (can_partial_agg(root, agg_costs))
    3873        8144 :             flags |= GROUPING_CAN_PARTIAL_AGG;
    3874             : 
    3875       23808 :         extra.flags = flags;
    3876       23808 :         extra.target_parallel_safe = target_parallel_safe;
    3877       23808 :         extra.havingQual = parse->havingQual;
    3878       23808 :         extra.targetList = parse->targetList;
    3879       23808 :         extra.partial_costs_set = false;
    3880             : 
    3881             :         /*
    3882             :          * Determine whether partitionwise aggregation is in theory possible.
    3883             :          * It can be disabled by the user, and for now, we don't try to
    3884             :          * support grouping sets.  create_ordinary_grouping_paths() will check
    3885             :          * additional conditions, such as whether input_rel is partitioned.
    3886             :          */
    3887       23808 :         if (enable_partitionwise_aggregate && !parse->groupingSets)
    3888         302 :             extra.patype = PARTITIONWISE_AGGREGATE_FULL;
    3889             :         else
    3890       23506 :             extra.patype = PARTITIONWISE_AGGREGATE_NONE;
    3891             : 
    3892       23808 :         create_ordinary_grouping_paths(root, input_rel, grouped_rel,
    3893             :                                        agg_costs, gd, &extra,
    3894             :                                        &partially_grouped_rel);
    3895             :     }
    3896             : 
    3897       23816 :     set_cheapest(grouped_rel);
    3898       23816 :     return grouped_rel;
    3899             : }
    3900             : 
    3901             : /*
    3902             :  * make_grouping_rel
    3903             :  *
    3904             :  * Create a new grouping rel and set basic properties.
    3905             :  *
    3906             :  * input_rel represents the underlying scan/join relation.
    3907             :  * target is the output expected from the grouping relation.
    3908             :  */
    3909             : static RelOptInfo *
    3910       24762 : make_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
    3911             :                   PathTarget *target, bool target_parallel_safe,
    3912             :                   Node *havingQual)
    3913             : {
    3914             :     RelOptInfo *grouped_rel;
    3915             : 
    3916       24762 :     if (IS_OTHER_REL(input_rel))
    3917             :     {
    3918         942 :         grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG,
    3919             :                                       input_rel->relids);
    3920         942 :         grouped_rel->reloptkind = RELOPT_OTHER_UPPER_REL;
    3921             :     }
    3922             :     else
    3923             :     {
    3924             :         /*
    3925             :          * By tradition, the relids set for the main grouping relation is
    3926             :          * NULL.  (This could be changed, but might require adjustments
    3927             :          * elsewhere.)
    3928             :          */
    3929       23820 :         grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG, NULL);
    3930             :     }
    3931             : 
    3932             :     /* Set target. */
    3933       24762 :     grouped_rel->reltarget = target;
    3934             : 
    3935             :     /*
    3936             :      * If the input relation is not parallel-safe, then the grouped relation
    3937             :      * can't be parallel-safe, either.  Otherwise, it's parallel-safe if the
    3938             :      * target list and HAVING quals are parallel-safe.
    3939             :      */
    3940       36172 :     if (input_rel->consider_parallel && target_parallel_safe &&
    3941       11410 :         is_parallel_safe(root, (Node *) havingQual))
    3942       11398 :         grouped_rel->consider_parallel = true;
    3943             : 
    3944             :     /*
    3945             :      * If the input rel belongs to a single FDW, so does the grouped rel.
    3946             :      */
    3947       24762 :     grouped_rel->serverid = input_rel->serverid;
    3948       24762 :     grouped_rel->userid = input_rel->userid;
    3949       24762 :     grouped_rel->useridiscurrent = input_rel->useridiscurrent;
    3950       24762 :     grouped_rel->fdwroutine = input_rel->fdwroutine;
    3951             : 
    3952       24762 :     return grouped_rel;
    3953             : }
    3954             : 
    3955             : /*
    3956             :  * is_degenerate_grouping
    3957             :  *
    3958             :  * A degenerate grouping is one in which the query has a HAVING qual and/or
    3959             :  * grouping sets, but no aggregates and no GROUP BY (which implies that the
    3960             :  * grouping sets are all empty).
    3961             :  */
    3962             : static bool
    3963       23820 : is_degenerate_grouping(PlannerInfo *root)
    3964             : {
    3965       23820 :     Query      *parse = root->parse;
    3966             : 
    3967       48036 :     return (root->hasHavingQual || parse->groupingSets) &&
    3968       24648 :         !parse->hasAggs && parse->groupClause == NIL;
    3969             : }
    3970             : 
    3971             : /*
    3972             :  * create_degenerate_grouping_paths
    3973             :  *
    3974             :  * When the grouping is degenerate (see is_degenerate_grouping), we are
    3975             :  * supposed to emit either zero or one row for each grouping set depending on
    3976             :  * whether HAVING succeeds.  Furthermore, there cannot be any variables in
    3977             :  * either HAVING or the targetlist, so we actually do not need the FROM table
    3978             :  * at all! We can just throw away the plan-so-far and generate a Result node.
    3979             :  * This is a sufficiently unusual corner case that it's not worth contorting
    3980             :  * the structure of this module to avoid having to generate the earlier paths
    3981             :  * in the first place.
    3982             :  */
    3983             : static void
    3984          12 : create_degenerate_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel,
    3985             :                                  RelOptInfo *grouped_rel)
    3986             : {
    3987          12 :     Query      *parse = root->parse;
    3988             :     int         nrows;
    3989             :     Path       *path;
    3990             : 
    3991          12 :     nrows = list_length(parse->groupingSets);
    3992          12 :     if (nrows > 1)
    3993             :     {
    3994             :         /*
    3995             :          * Doesn't seem worthwhile writing code to cons up a generate_series
    3996             :          * or a values scan to emit multiple rows. Instead just make N clones
    3997             :          * and append them.  (With a volatile HAVING clause, this means you
    3998             :          * might get between 0 and N output rows. Offhand I think that's
    3999             :          * desired.)
    4000             :          */
    4001           0 :         List       *paths = NIL;
    4002             : 
    4003           0 :         while (--nrows >= 0)
    4004             :         {
    4005           0 :             path = (Path *)
    4006             :                 create_group_result_path(root, grouped_rel,
    4007           0 :                                          grouped_rel->reltarget,
    4008           0 :                                          (List *) parse->havingQual);
    4009           0 :             paths = lappend(paths, path);
    4010             :         }
    4011           0 :         path = (Path *)
    4012             :             create_append_path(root,
    4013             :                                grouped_rel,
    4014             :                                paths,
    4015             :                                NIL,
    4016             :                                NIL,
    4017             :                                NULL,
    4018             :                                0,
    4019             :                                false,
    4020             :                                NIL,
    4021             :                                -1);
    4022             :     }
    4023             :     else
    4024             :     {
    4025             :         /* No grouping sets, or just one, so one output row */
    4026          12 :         path = (Path *)
    4027             :             create_group_result_path(root, grouped_rel,
    4028          12 :                                      grouped_rel->reltarget,
    4029          12 :                                      (List *) parse->havingQual);
    4030             :     }
    4031             : 
    4032          12 :     add_path(grouped_rel, path);
    4033          12 : }
    4034             : 
    4035             : /*
    4036             :  * create_ordinary_grouping_paths
    4037             :  *
    4038             :  * Create grouping paths for the ordinary (that is, non-degenerate) case.
    4039             :  *
    4040             :  * We need to consider sorted and hashed aggregation in the same function,
    4041             :  * because otherwise (1) it would be harder to throw an appropriate error
    4042             :  * message if neither way works, and (2) we should not allow hashtable size
    4043             :  * considerations to dissuade us from using hashing if sorting is not possible.
    4044             :  *
    4045             :  * *partially_grouped_rel_p will be set to the partially grouped rel which this
    4046             :  * function creates, or to NULL if it doesn't create one.
    4047             :  */
    4048             : static void
    4049       24750 : create_ordinary_grouping_paths(PlannerInfo *root, RelOptInfo *input_rel,
    4050             :                                RelOptInfo *grouped_rel,
    4051             :                                const AggClauseCosts *agg_costs,
    4052             :                                grouping_sets_data *gd,
    4053             :                                GroupPathExtraData *extra,
    4054             :                                RelOptInfo **partially_grouped_rel_p)
    4055             : {
    4056       24750 :     Path       *cheapest_path = input_rel->cheapest_total_path;
    4057       24750 :     RelOptInfo *partially_grouped_rel = NULL;
    4058             :     double      dNumGroups;
    4059       24750 :     PartitionwiseAggregateType patype = PARTITIONWISE_AGGREGATE_NONE;
    4060             : 
    4061             :     /*
    4062             :      * If this is the topmost grouping relation or if the parent relation is
    4063             :      * doing some form of partitionwise aggregation, then we may be able to do
    4064             :      * it at this level also.  However, if the input relation is not
    4065             :      * partitioned, partitionwise aggregate is impossible.
    4066             :      */
    4067       25994 :     if (extra->patype != PARTITIONWISE_AGGREGATE_NONE &&
    4068        1650 :         IS_PARTITIONED_REL(input_rel))
    4069             :     {
    4070             :         /*
    4071             :          * If this is the topmost relation or if the parent relation is doing
    4072             :          * full partitionwise aggregation, then we can do full partitionwise
    4073             :          * aggregation provided that the GROUP BY clause contains all of the
    4074             :          * partitioning columns at this level.  Otherwise, we can do at most
    4075             :          * partial partitionwise aggregation.  But if partial aggregation is
    4076             :          * not supported in general then we can't use it for partitionwise
    4077             :          * aggregation either.
    4078             :          */
    4079         716 :         if (extra->patype == PARTITIONWISE_AGGREGATE_FULL &&
    4080         342 :             group_by_has_partkey(input_rel, extra->targetList,
    4081         342 :                                  root->parse->groupClause))
    4082         192 :             patype = PARTITIONWISE_AGGREGATE_FULL;
    4083         182 :         else if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
    4084         154 :             patype = PARTITIONWISE_AGGREGATE_PARTIAL;
    4085             :         else
    4086          28 :             patype = PARTITIONWISE_AGGREGATE_NONE;
    4087             :     }
    4088             : 
    4089             :     /*
    4090             :      * Before generating paths for grouped_rel, we first generate any possible
    4091             :      * partially grouped paths; that way, later code can easily consider both
    4092             :      * parallel and non-parallel approaches to grouping.
    4093             :      */
    4094       24750 :     if ((extra->flags & GROUPING_CAN_PARTIAL_AGG) != 0)
    4095             :     {
    4096             :         bool        force_rel_creation;
    4097             : 
    4098             :         /*
    4099             :          * If we're doing partitionwise aggregation at this level, force
    4100             :          * creation of a partially_grouped_rel so we can add partitionwise
    4101             :          * paths to it.
    4102             :          */
    4103        9038 :         force_rel_creation = (patype == PARTITIONWISE_AGGREGATE_PARTIAL);
    4104             : 
    4105        9038 :         partially_grouped_rel =
    4106        9038 :             create_partial_grouping_paths(root,
    4107             :                                           grouped_rel,
    4108             :                                           input_rel,
    4109             :                                           gd,
    4110             :                                           extra,
    4111             :                                           force_rel_creation);
    4112             :     }
    4113             : 
    4114             :     /* Set out parameter. */
    4115       24750 :     *partially_grouped_rel_p = partially_grouped_rel;
    4116             : 
    4117             :     /* Apply partitionwise aggregation technique, if possible. */
    4118       24750 :     if (patype != PARTITIONWISE_AGGREGATE_NONE)
    4119         346 :         create_partitionwise_grouping_paths(root, input_rel, grouped_rel,
    4120             :                                             partially_grouped_rel, agg_costs,
    4121             :                                             gd, patype, extra);
    4122             : 
    4123             :     /* If we are doing partial aggregation only, return. */
    4124       24750 :     if (extra->patype == PARTITIONWISE_AGGREGATE_PARTIAL)
    4125             :     {
    4126             :         Assert(partially_grouped_rel);
    4127             : 
    4128         398 :         if (partially_grouped_rel->pathlist)
    4129         398 :             set_cheapest(partially_grouped_rel);
    4130             : 
    4131         398 :         return;
    4132             :     }
    4133             : 
    4134             :     /* Gather any partially grouped partial paths. */
    4135       24352 :     if (partially_grouped_rel && partially_grouped_rel->partial_pathlist)
    4136             :     {
    4137         830 :         gather_grouping_paths(root, partially_grouped_rel);
    4138         830 :         set_cheapest(partially_grouped_rel);
    4139             :     }
    4140             : 
    4141             :     /*
    4142             :      * Estimate number of groups.
    4143             :      */
    4144       24352 :     dNumGroups = get_number_of_groups(root,
    4145             :                                       cheapest_path->rows,
    4146             :                                       gd,
    4147             :                                       extra->targetList);
    4148             : 
    4149             :     /* Build final grouping paths */
    4150       24352 :     add_paths_to_grouping_rel(root, input_rel, grouped_rel,
    4151             :                               partially_grouped_rel, agg_costs, gd,
    4152             :                               dNumGroups, extra);
    4153             : 
    4154             :     /* Give a helpful error if we failed to find any implementation */
    4155       24352 :     if (grouped_rel->pathlist == NIL)
    4156           4 :         ereport(ERROR,
    4157             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4158             :                  errmsg("could not implement GROUP BY"),
    4159             :                  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
    4160             : 
    4161             :     /*
    4162             :      * If there is an FDW that's responsible for all baserels of the query,
    4163             :      * let it consider adding ForeignPaths.
    4164             :      */
    4165       24622 :     if (grouped_rel->fdwroutine &&
    4166         274 :         grouped_rel->fdwroutine->GetForeignUpperPaths)
    4167         274 :         grouped_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_GROUP_AGG,
    4168             :                                                       input_rel, grouped_rel,
    4169             :                                                       extra);
    4170             : 
    4171             :     /* Let extensions possibly add some more paths */
    4172       24348 :     if (create_upper_paths_hook)
    4173           0 :         (*create_upper_paths_hook) (root, UPPERREL_GROUP_AGG,
    4174             :                                     input_rel, grouped_rel,
    4175             :                                     extra);
    4176             : }
    4177             : 
    4178             : /*
    4179             :  * For a given input path, consider the possible ways of doing grouping sets on
    4180             :  * it, by combinations of hashing and sorting.  This can be called multiple
    4181             :  * times, so it's important that it not scribble on input.  No result is
    4182             :  * returned, but any generated paths are added to grouped_rel.
    4183             :  */
    4184             : static void
    4185         844 : consider_groupingsets_paths(PlannerInfo *root,
    4186             :                             RelOptInfo *grouped_rel,
    4187             :                             Path *path,
    4188             :                             bool is_sorted,
    4189             :                             bool can_hash,
    4190             :                             grouping_sets_data *gd,
    4191             :                             const AggClauseCosts *agg_costs,
    4192             :                             double dNumGroups)
    4193             : {
    4194         844 :     Query      *parse = root->parse;
    4195             : 
    4196             :     /*
    4197             :      * If we're not being offered sorted input, then only consider plans that
    4198             :      * can be done entirely by hashing.
    4199             :      *
    4200             :      * We can hash everything if it looks like it'll fit in work_mem. But if
    4201             :      * the input is actually sorted despite not being advertised as such, we
    4202             :      * prefer to make use of that in order to use less memory.
    4203             :      *
    4204             :      * If none of the grouping sets are sortable, then ignore the work_mem
    4205             :      * limit and generate a path anyway, since otherwise we'll just fail.
    4206             :      */
    4207         844 :     if (!is_sorted)
    4208             :     {
    4209         380 :         List       *new_rollups = NIL;
    4210         380 :         RollupData *unhashed_rollup = NULL;
    4211             :         List       *sets_data;
    4212         380 :         List       *empty_sets_data = NIL;
    4213         380 :         List       *empty_sets = NIL;
    4214             :         ListCell   *lc;
    4215         380 :         ListCell   *l_start = list_head(gd->rollups);
    4216         380 :         AggStrategy strat = AGG_HASHED;
    4217             :         double      hashsize;
    4218         380 :         double      exclude_groups = 0.0;
    4219             : 
    4220             :         Assert(can_hash);
    4221             : 
    4222             :         /*
    4223             :          * If the input is coincidentally sorted usefully (which can happen
    4224             :          * even if is_sorted is false, since that only means that our caller
    4225             :          * has set up the sorting for us), then save some hashtable space by
    4226             :          * making use of that. But we need to watch out for degenerate cases:
    4227             :          *
    4228             :          * 1) If there are any empty grouping sets, then group_pathkeys might
    4229             :          * be NIL if all non-empty grouping sets are unsortable. In this case,
    4230             :          * there will be a rollup containing only empty groups, and the
    4231             :          * pathkeys_contained_in test is vacuously true; this is ok.
    4232             :          *
    4233             :          * XXX: the above relies on the fact that group_pathkeys is generated
    4234             :          * from the first rollup. If we add the ability to consider multiple
    4235             :          * sort orders for grouping input, this assumption might fail.
    4236             :          *
    4237             :          * 2) If there are no empty sets and only unsortable sets, then the
    4238             :          * rollups list will be empty (and thus l_start == NULL), and
    4239             :          * group_pathkeys will be NIL; we must ensure that the vacuously-true
    4240             :          * pathkeys_contained_in test doesn't cause us to crash.
    4241             :          */
    4242         756 :         if (l_start != NULL &&
    4243         376 :             pathkeys_contained_in(root->group_pathkeys, path->pathkeys))
    4244             :         {
    4245           8 :             unhashed_rollup = lfirst_node(RollupData, l_start);
    4246           8 :             exclude_groups = unhashed_rollup->numGroups;
    4247           8 :             l_start = lnext(gd->rollups, l_start);
    4248             :         }
    4249             : 
    4250         380 :         hashsize = estimate_hashagg_tablesize(path,
    4251             :                                               agg_costs,
    4252             :                                               dNumGroups - exclude_groups);
    4253             : 
    4254             :         /*
    4255             :          * gd->rollups is empty if we have only unsortable columns to work
    4256             :          * with.  Override work_mem in that case; otherwise, we'll rely on the
    4257             :          * sorted-input case to generate usable mixed paths.
    4258             :          */
    4259         380 :         if (hashsize > work_mem * 1024L && gd->rollups)
    4260          12 :             return;             /* nope, won't fit */
    4261             : 
    4262             :         /*
    4263             :          * We need to burst the existing rollups list into individual grouping
    4264             :          * sets and recompute a groupClause for each set.
    4265             :          */
    4266         368 :         sets_data = list_copy(gd->unsortable_sets);
    4267             : 
    4268         904 :         for_each_cell(lc, gd->rollups, l_start)
    4269             :         {
    4270         552 :             RollupData *rollup = lfirst_node(RollupData, lc);
    4271             : 
    4272             :             /*
    4273             :              * If we find an unhashable rollup that's not been skipped by the
    4274             :              * "actually sorted" check above, we can't cope; we'd need sorted
    4275             :              * input (with a different sort order) but we can't get that here.
    4276             :              * So bail out; we'll get a valid path from the is_sorted case
    4277             :              * instead.
    4278             :              *
    4279             :              * The mere presence of empty grouping sets doesn't make a rollup
    4280             :              * unhashable (see preprocess_grouping_sets), we handle those
    4281             :              * specially below.
    4282             :              */
    4283         552 :             if (!rollup->hashable)
    4284          32 :                 return;
    4285             : 
    4286         536 :             sets_data = list_concat(sets_data, rollup->gsets_data);
    4287             :         }
    4288        1420 :         foreach(lc, sets_data)
    4289             :         {
    4290        1068 :             GroupingSetData *gs = lfirst_node(GroupingSetData, lc);
    4291        1068 :             List       *gset = gs->set;
    4292             :             RollupData *rollup;
    4293             : 
    4294        1068 :             if (gset == NIL)
    4295             :             {
    4296             :                 /* Empty grouping sets can't be hashed. */
    4297         252 :                 empty_sets_data = lappend(empty_sets_data, gs);
    4298         252 :                 empty_sets = lappend(empty_sets, NIL);
    4299             :             }
    4300             :             else
    4301             :             {
    4302         816 :                 rollup = makeNode(RollupData);
    4303             : 
    4304         816 :                 rollup->groupClause = preprocess_groupclause(root, gset);
    4305         816 :                 rollup->gsets_data = list_make1(gs);
    4306         816 :                 rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
    4307             :                                                          rollup->gsets_data,
    4308             :                                                          gd->tleref_to_colnum_map);
    4309         816 :                 rollup->numGroups = gs->numGroups;
    4310         816 :                 rollup->hashable = true;
    4311         816 :                 rollup->is_hashed = true;
    4312         816 :                 new_rollups = lappend(new_rollups, rollup);
    4313             :             }
    4314             :         }
    4315             : 
    4316             :         /*
    4317             :          * If we didn't find anything nonempty to hash, then bail.  We'll
    4318             :          * generate a path from the is_sorted case.
    4319             :          */
    4320         352 :         if (new_rollups == NIL)
    4321           0 :             return;
    4322             : 
    4323             :         /*
    4324             :          * If there were empty grouping sets they should have been in the
    4325             :          * first rollup.
    4326             :          */
    4327             :         Assert(!unhashed_rollup || !empty_sets);
    4328             : 
    4329         352 :         if (unhashed_rollup)
    4330             :         {
    4331           8 :             new_rollups = lappend(new_rollups, unhashed_rollup);
    4332           8 :             strat = AGG_MIXED;
    4333             :         }
    4334         344 :         else if (empty_sets)
    4335             :         {
    4336         220 :             RollupData *rollup = makeNode(RollupData);
    4337             : 
    4338         220 :             rollup->groupClause = NIL;
    4339         220 :             rollup->gsets_data = empty_sets_data;
    4340         220 :             rollup->gsets = empty_sets;
    4341         220 :             rollup->numGroups = list_length(empty_sets);
    4342         220 :             rollup->hashable = false;
    4343         220 :             rollup->is_hashed = false;
    4344         220 :             new_rollups = lappend(new_rollups, rollup);
    4345         220 :             strat = AGG_MIXED;
    4346             :         }
    4347             : 
    4348         352 :         add_path(grouped_rel, (Path *)
    4349         352 :                  create_groupingsets_path(root,
    4350             :                                           grouped_rel,
    4351             :                                           path,
    4352         352 :                                           (List *) parse->havingQual,
    4353             :                                           strat,
    4354             :                                           new_rollups,
    4355             :                                           agg_costs,
    4356             :                                           dNumGroups));
    4357         352 :         return;
    4358             :     }
    4359             : 
    4360             :     /*
    4361             :      * If we have sorted input but nothing we can do with it, bail.
    4362             :      */
    4363         464 :     if (list_length(gd->rollups) == 0)
    4364           0 :         return;
    4365             : 
    4366             :     /*
    4367             :      * Given sorted input, we try and make two paths: one sorted and one mixed
    4368             :      * sort/hash. (We need to try both because hashagg might be disabled, or
    4369             :      * some columns might not be sortable.)
    4370             :      *
    4371             :      * can_hash is passed in as false if some obstacle elsewhere (such as
    4372             :      * ordered aggs) means that we shouldn't consider hashing at all.
    4373             :      */
    4374         464 :     if (can_hash && gd->any_hashable)
    4375             :     {
    4376         412 :         List       *rollups = NIL;
    4377         412 :         List       *hash_sets = list_copy(gd->unsortable_sets);
    4378         412 :         double      availspace = (work_mem * 1024.0);
    4379             :         ListCell   *lc;
    4380             : 
    4381             :         /*
    4382             :          * Account first for space needed for groups we can't sort at all.
    4383             :          */
    4384         412 :         availspace -= estimate_hashagg_tablesize(path,
    4385             :                                                  agg_costs,
    4386             :                                                  gd->dNumHashGroups);
    4387             : 
    4388         412 :         if (availspace > 0 && list_length(gd->rollups) > 1)
    4389             :         {
    4390             :             double      scale;
    4391         208 :             int         num_rollups = list_length(gd->rollups);
    4392             :             int         k_capacity;
    4393         208 :             int        *k_weights = palloc(num_rollups * sizeof(int));
    4394         208 :             Bitmapset  *hash_items = NULL;
    4395             :             int         i;
    4396             : 
    4397             :             /*
    4398             :              * We treat this as a knapsack problem: the knapsack capacity
    4399             :              * represents work_mem, the item weights are the estimated memory
    4400             :              * usage of the hashtables needed to implement a single rollup,
    4401             :              * and we really ought to use the cost saving as the item value;
    4402             :              * however, currently the costs assigned to sort nodes don't
    4403             :              * reflect the comparison costs well, and so we treat all items as
    4404             :              * of equal value (each rollup we hash instead saves us one sort).
    4405             :              *
    4406             :              * To use the discrete knapsack, we need to scale the values to a
    4407             :              * reasonably small bounded range.  We choose to allow a 5% error
    4408             :              * margin; we have no more than 4096 rollups in the worst possible
    4409             :              * case, which with a 5% error margin will require a bit over 42MB
    4410             :              * of workspace. (Anyone wanting to plan queries that complex had
    4411             :              * better have the memory for it.  In more reasonable cases, with
    4412             :              * no more than a couple of dozen rollups, the memory usage will
    4413             :              * be negligible.)
    4414             :              *
    4415             :              * k_capacity is naturally bounded, but we clamp the values for
    4416             :              * scale and weight (below) to avoid overflows or underflows (or
    4417             :              * uselessly trying to use a scale factor less than 1 byte).
    4418             :              */
    4419         208 :             scale = Max(availspace / (20.0 * num_rollups), 1.0);
    4420         208 :             k_capacity = (int) floor(availspace / scale);
    4421             : 
    4422             :             /*
    4423             :              * We leave the first rollup out of consideration since it's the
    4424             :              * one that matches the input sort order.  We assign indexes "i"
    4425             :              * to only those entries considered for hashing; the second loop,
    4426             :              * below, must use the same condition.
    4427             :              */
    4428         208 :             i = 0;
    4429         544 :             for_each_cell(lc, gd->rollups, list_second_cell(gd->rollups))
    4430             :             {
    4431         336 :                 RollupData *rollup = lfirst_node(RollupData, lc);
    4432             : 
    4433         336 :                 if (rollup->hashable)
    4434             :                 {
    4435         336 :                     double      sz = estimate_hashagg_tablesize(path,
    4436             :                                                                 agg_costs,
    4437             :                                                                 rollup->numGroups);
    4438             : 
    4439             :                     /*
    4440             :                      * If sz is enormous, but work_mem (and hence scale) is
    4441             :                      * small, avoid integer overflow here.
    4442             :                      */
    4443         336 :                     k_weights[i] = (int) Min(floor(sz / scale),
    4444             :                                              k_capacity + 1.0);
    4445         336 :                     ++i;
    4446             :                 }
    4447             :             }
    4448             : 
    4449             :             /*
    4450             :              * Apply knapsack algorithm; compute the set of items which
    4451             :              * maximizes the value stored (in this case the number of sorts
    4452             :              * saved) while keeping the total size (approximately) within
    4453             :              * capacity.
    4454             :              */
    4455         208 :             if (i > 0)
    4456         208 :                 hash_items = DiscreteKnapsack(k_capacity, i, k_weights, NULL);
    4457             : 
    4458         208 :             if (!bms_is_empty(hash_items))
    4459             :             {
    4460         208 :                 rollups = list_make1(linitial(gd->rollups));
    4461             : 
    4462         208 :                 i = 0;
    4463         544 :                 for_each_cell(lc, gd->rollups, list_second_cell(gd->rollups))
    4464             :                 {
    4465         336 :                     RollupData *rollup = lfirst_node(RollupData, lc);
    4466             : 
    4467         336 :                     if (rollup->hashable)
    4468             :                     {
    4469         336 :                         if (bms_is_member(i, hash_items))
    4470         312 :                             hash_sets = list_concat(hash_sets,
    4471         312 :                                                     rollup->gsets_data);
    4472             :                         else
    4473          24 :                             rollups = lappend(rollups, rollup);
    4474         336 :                         ++i;
    4475             :                     }
    4476             :                     else
    4477           0 :                         rollups = lappend(rollups, rollup);
    4478             :                 }
    4479             :             }
    4480             :         }
    4481             : 
    4482         412 :         if (!rollups && hash_sets)
    4483          16 :             rollups = list_copy(gd->rollups);
    4484             : 
    4485         772 :         foreach(lc, hash_sets)
    4486             :         {
    4487         360 :             GroupingSetData *gs = lfirst_node(GroupingSetData, lc);
    4488         360 :             RollupData *rollup = makeNode(RollupData);
    4489             : 
    4490             :             Assert(gs->set != NIL);
    4491             : 
    4492         360 :             rollup->groupClause = preprocess_groupclause(root, gs->set);
    4493         360 :             rollup->gsets_data = list_make1(gs);
    4494         360 :             rollup->gsets = remap_to_groupclause_idx(rollup->groupClause,
    4495             :                                                      rollup->gsets_data,
    4496             :                                                      gd->tleref_to_colnum_map);
    4497         360 :             rollup->numGroups = gs->numGroups;
    4498         360 :             rollup->hashable = true;
    4499         360 :             rollup->is_hashed = true;
    4500         360 :             rollups = lcons(rollup, rollups);
    4501             :         }
    4502             : 
    4503         412 :         if (rollups)
    4504             :         {
    4505         224 :             add_path(grouped_rel, (Path *)
    4506         224 :                      create_groupingsets_path(root,
    4507             :                                               grouped_rel,
    4508             :                                               path,
    4509         224 :                                               (List *) parse->havingQual,
    4510             :                                               AGG_MIXED,
    4511             :                                               rollups,
    4512             :                                               agg_costs,
    4513             :                                               dNumGroups));
    4514             :         }
    4515             :     }
    4516             : 
    4517             :     /*
    4518             :      * Now try the simple sorted case.
    4519             :      */
    4520         464 :     if (!gd->unsortable_sets)
    4521         444 :         add_path(grouped_rel, (Path *)
    4522         888 :                  create_groupingsets_path(root,
    4523             :                                           grouped_rel,
    4524             :                                           path,
    4525         444 :                                           (List *) parse->havingQual,
    4526             :                                           AGG_SORTED,
    4527             :                                           gd->rollups,
    4528             :                                           agg_costs,
    4529             :                                           dNumGroups));
    4530             : }
    4531             : 
    4532             : /*
    4533             :  * create_window_paths
    4534             :  *
    4535             :  * Build a new upperrel containing Paths for window-function evaluation.
    4536             :  *
    4537             :  * input_rel: contains the source-data Paths
    4538             :  * input_target: result of make_window_input_target
    4539             :  * output_target: what the topmost WindowAggPath should return
    4540             :  * wflists: result of find_window_functions
    4541             :  * activeWindows: result of select_active_windows
    4542             :  *
    4543             :  * Note: all Paths in input_rel are expected to return input_target.
    4544             :  */
    4545             : static RelOptInfo *
    4546        1112 : create_window_paths(PlannerInfo *root,
    4547             :                     RelOptInfo *input_rel,
    4548             :                     PathTarget *input_target,
    4549             :                     PathTarget *output_target,
    4550             :                     bool output_target_parallel_safe,
    4551             :                     WindowFuncLists *wflists,
    4552             :                     List *activeWindows)
    4553             : {
    4554             :     RelOptInfo *window_rel;
    4555             :     ListCell   *lc;
    4556             : 
    4557             :     /* For now, do all work in the (WINDOW, NULL) upperrel */
    4558        1112 :     window_rel = fetch_upper_rel(root, UPPERREL_WINDOW, NULL);
    4559             : 
    4560             :     /*
    4561             :      * If the input relation is not parallel-safe, then the window relation
    4562             :      * can't be parallel-safe, either.  Otherwise, we need to examine the
    4563             :      * target list and active windows for non-parallel-safe constructs.
    4564             :      */
    4565        1112 :     if (input_rel->consider_parallel && output_target_parallel_safe &&
    4566           0 :         is_parallel_safe(root, (Node *) activeWindows))
    4567           0 :         window_rel->consider_parallel = true;
    4568             : 
    4569             :     /*
    4570             :      * If the input rel belongs to a single FDW, so does the window rel.
    4571             :      */
    4572        1112 :     window_rel->serverid = input_rel->serverid;
    4573        1112 :     window_rel->userid = input_rel->userid;
    4574        1112 :     window_rel->useridiscurrent = input_rel->useridiscurrent;
    4575        1112 :     window_rel->fdwroutine = input_rel->fdwroutine;
    4576             : 
    4577             :     /*
    4578             :      * Consider computing window functions starting from the existing
    4579             :      * cheapest-total path (which will likely require a sort) as well as any
    4580             :      * existing paths that satisfy root->window_pathkeys (which won't).
    4581             :      */
    4582        2324 :     foreach(lc, input_rel->pathlist)
    4583             :     {
    4584        1212 :         Path       *path = (Path *) lfirst(lc);
    4585             : 
    4586        1312 :         if (path == input_rel->cheapest_total_path ||
    4587         100 :             pathkeys_contained_in(root->window_pathkeys, path->pathkeys))
    4588        1156 :             create_one_window_path(root,
    4589             :                                    window_rel,
    4590             :                                    path,
    4591             :                                    input_target,
    4592             :                                    output_target,
    4593             :                                    wflists,
    4594             :                                    activeWindows);
    4595             :     }
    4596             : 
    4597             :     /*
    4598             :      * If there is an FDW that's responsible for all baserels of the query,
    4599             :      * let it consider adding ForeignPaths.
    4600             :      */
    4601        1124 :     if (window_rel->fdwroutine &&
    4602          12 :         window_rel->fdwroutine->GetForeignUpperPaths)
    4603          12 :         window_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_WINDOW,
    4604             :                                                      input_rel, window_rel,
    4605             :                                                      NULL);
    4606             : 
    4607             :     /* Let extensions possibly add some more paths */
    4608        1112 :     if (create_upper_paths_hook)
    4609           0 :         (*create_upper_paths_hook) (root, UPPERREL_WINDOW,
    4610             :                                     input_rel, window_rel, NULL);
    4611             : 
    4612             :     /* Now choose the best path(s) */
    4613        1112 :     set_cheapest(window_rel);
    4614             : 
    4615        1112 :     return window_rel;
    4616             : }
    4617             : 
    4618             : /*
    4619             :  * Stack window-function implementation steps atop the given Path, and
    4620             :  * add the result to window_rel.
    4621             :  *
    4622             :  * window_rel: upperrel to contain result
    4623             :  * path: input Path to use (must return input_target)
    4624             :  * input_target: result of make_window_input_target
    4625             :  * output_target: what the topmost WindowAggPath should return
    4626             :  * wflists: result of find_window_functions
    4627             :  * activeWindows: result of select_active_windows
    4628             :  */
    4629             : static void
    4630        1156 : create_one_window_path(PlannerInfo *root,
    4631             :                        RelOptInfo *window_rel,
    4632             :                        Path *path,
    4633             :                        PathTarget *input_target,
    4634             :                        PathTarget *output_target,
    4635             :                        WindowFuncLists *wflists,
    4636             :                        List *activeWindows)
    4637             : {
    4638             :     PathTarget *window_target;
    4639             :     ListCell   *l;
    4640             : 
    4641             :     /*
    4642             :      * Since each window clause could require a different sort order, we stack
    4643             :      * up a WindowAgg node for each clause, with sort steps between them as
    4644             :      * needed.  (We assume that select_active_windows chose a good order for
    4645             :      * executing the clauses in.)
    4646             :      *
    4647             :      * input_target should contain all Vars and Aggs needed for the result.
    4648             :      * (In some cases we wouldn't need to propagate all of these all the way
    4649             :      * to the top, since they might only be needed as inputs to WindowFuncs.
    4650             :      * It's probably not worth trying to optimize that though.)  It must also
    4651             :      * contain all window partitioning and sorting expressions, to ensure
    4652             :      * they're computed only once at the bottom of the stack (that's critical
    4653             :      * for volatile functions).  As we climb up the stack, we'll add outputs
    4654             :      * for the WindowFuncs computed at each level.
    4655             :      */
    4656        1156 :     window_target = input_target;
    4657             : 
    4658        2360 :     foreach(l, activeWindows)
    4659             :     {
    4660        1204 :         WindowClause *wc = lfirst_node(WindowClause, l);
    4661             :         List       *window_pathkeys;
    4662             : 
    4663        1204 :         window_pathkeys = make_pathkeys_for_window(root,
    4664             :                                                    wc,
    4665             :                                                    root->processed_tlist);
    4666             : 
    4667             :         /* Sort if necessary */
    4668        1204 :         if (!pathkeys_contained_in(window_pathkeys, path->pathkeys))
    4669             :         {
    4670         952 :             path = (Path *) create_sort_path(root, window_rel,
    4671             :                                              path,
    4672             :                                              window_pathkeys,
    4673             :                                              -1.0);
    4674             :         }
    4675             : 
    4676        1204 :         if (lnext(activeWindows, l))
    4677             :         {
    4678             :             /*
    4679             :              * Add the current WindowFuncs to the output target for this
    4680             :              * intermediate WindowAggPath.  We must copy window_target to
    4681             :              * avoid changing the previous path's target.
    4682             :              *
    4683             :              * Note: a WindowFunc adds nothing to the target's eval costs; but
    4684             :              * we do need to account for the increase in tlist width.
    4685             :              */
    4686             :             ListCell   *lc2;
    4687             : 
    4688          48 :             window_target = copy_pathtarget(window_target);
    4689          96 :             foreach(lc2, wflists->windowFuncs[wc->winref])
    4690             :             {
    4691          48 :                 WindowFunc *wfunc = lfirst_node(WindowFunc, lc2);
    4692             : 
    4693          48 :                 add_column_to_pathtarget(window_target, (Expr *) wfunc, 0);
    4694          48 :                 window_target->width += get_typavgwidth(wfunc->wintype, -1);
    4695             :             }
    4696             :         }
    4697             :         else
    4698             :         {
    4699             :             /* Install the goal target in the topmost WindowAgg */
    4700        1156 :             window_target = output_target;
    4701             :         }
    4702             : 
    4703        1204 :         path = (Path *)
    4704        1204 :             create_windowagg_path(root, window_rel, path, window_target,
    4705        1204 :                                   wflists->windowFuncs[wc->winref],
    4706             :                                   wc);
    4707             :     }
    4708             : 
    4709        1156 :     add_path(window_rel, path);
    4710        1156 : }
    4711             : 
    4712             : /*
    4713             :  * create_distinct_paths
    4714             :  *
    4715             :  * Build a new upperrel containing Paths for SELECT DISTINCT evaluation.
    4716             :  *
    4717             :  * input_rel: contains the source-data Paths
    4718             :  *
    4719             :  * Note: input paths should already compute the desired pathtarget, since
    4720             :  * Sort/Unique won't project anything.
    4721             :  */
    4722             : static RelOptInfo *
    4723         386 : create_distinct_paths(PlannerInfo *root,
    4724             :                       RelOptInfo *input_rel)
    4725             : {
    4726         386 :     Query      *parse = root->parse;
    4727         386 :     Path       *cheapest_input_path = input_rel->cheapest_total_path;
    4728             :     RelOptInfo *distinct_rel;
    4729             :     double      numDistinctRows;
    4730             :     bool        allow_hash;
    4731             :     Path       *path;
    4732             :     ListCell   *lc;
    4733             : 
    4734             :     /* For now, do all work in the (DISTINCT, NULL) upperrel */
    4735         386 :     distinct_rel = fetch_upper_rel(root, UPPERREL_DISTINCT, NULL);
    4736             : 
    4737             :     /*
    4738             :      * We don't compute anything at this level, so distinct_rel will be
    4739             :      * parallel-safe if the input rel is parallel-safe.  In particular, if
    4740             :      * there is a DISTINCT ON (...) clause, any path for the input_rel will
    4741             :      * output those expressions, and will not be parallel-safe unless those
    4742             :      * expressions are parallel-safe.
    4743             :      */
    4744         386 :     distinct_rel->consider_parallel = input_rel->consider_parallel;
    4745             : 
    4746             :     /*
    4747             :      * If the input rel belongs to a single FDW, so does the distinct_rel.
    4748             :      */
    4749         386 :     distinct_rel->serverid = input_rel->serverid;
    4750         386 :     distinct_rel->userid = input_rel->userid;
    4751         386 :     distinct_rel->useridiscurrent = input_rel->useridiscurrent;
    4752         386 :     distinct_rel->fdwroutine = input_rel->fdwroutine;
    4753             : 
    4754             :     /* Estimate number of distinct rows there will be */
    4755         748 :     if (parse->groupClause || parse->groupingSets || parse->hasAggs ||
    4756         362 :         root->hasHavingQual)
    4757             :     {
    4758             :         /*
    4759             :          * If there was grouping or aggregation, use the number of input rows
    4760             :          * as the estimated number of DISTINCT rows (ie, assume the input is
    4761             :          * already mostly unique).
    4762             :          */
    4763          24 :         numDistinctRows = cheapest_input_path->rows;
    4764             :     }
    4765             :     else
    4766             :     {
    4767             :         /*
    4768             :          * Otherwise, the UNIQUE filter has effects comparable to GROUP BY.
    4769             :          */
    4770             :         List       *distinctExprs;
    4771             : 
    4772         362 :         distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
    4773             :                                                 parse->targetList);
    4774         362 :         numDistinctRows = estimate_num_groups(root, distinctExprs,
    4775             :                                               cheapest_input_path->rows,
    4776             :                                               NULL);
    4777             :     }
    4778             : 
    4779             :     /*
    4780             :      * Consider sort-based implementations of DISTINCT, if possible.
    4781             :      */
    4782         386 :     if (grouping_is_sortable(parse->distinctClause))
    4783             :     {
    4784             :         /*
    4785             :          * First, if we have any adequately-presorted paths, just stick a
    4786             :          * Unique node on those.  Then consider doing an explicit sort of the
    4787             :          * cheapest input path and Unique'ing that.
    4788             :          *
    4789             :          * When we have DISTINCT ON, we must sort by the more rigorous of
    4790             :          * DISTINCT and ORDER BY, else it won't have the desired behavior.
    4791             :          * Also, if we do have to do an explicit sort, we might as well use
    4792             :          * the more rigorous ordering to avoid a second sort later.  (Note
    4793             :          * that the parser will have ensured that one clause is a prefix of
    4794             :          * the other.)
    4795             :          */
    4796             :         List       *needed_pathkeys;
    4797             : 
    4798         418 :         if (parse->hasDistinctOn &&
    4799          36 :             list_length(root->distinct_pathkeys) <
    4800          36 :             list_length(root->sort_pathkeys))
    4801          20 :             needed_pathkeys = root->sort_pathkeys;
    4802             :         else
    4803         362 :             needed_pathkeys = root->distinct_pathkeys;
    4804             : 
    4805         804 :         foreach(lc, input_rel->pathlist)
    4806             :         {
    4807         422 :             Path       *path = (Path *) lfirst(lc);
    4808             : 
    4809         422 :             if (pathkeys_contained_in(needed_pathkeys, path->pathkeys))
    4810             :             {
    4811          30 :                 add_path(distinct_rel, (Path *)
    4812          30 :                          create_upper_unique_path(root, distinct_rel,
    4813             :                                                   path,
    4814          30 :                                                   list_length(root->distinct_pathkeys),
    4815             :                                                   numDistinctRows));
    4816             :             }
    4817             :         }
    4818             : 
    4819             :         /* For explicit-sort case, always use the more rigorous clause */
    4820         764 :         if (list_length(root->distinct_pathkeys) <
    4821         382 :             list_length(root->sort_pathkeys))
    4822             :         {
    4823          20 :             needed_pathkeys = root->sort_pathkeys;
    4824             :             /* Assert checks that parser didn't mess up... */
    4825             :             Assert(pathkeys_contained_in(root->distinct_pathkeys,
    4826             :                                          needed_pathkeys));
    4827             :         }
    4828             :         else
    4829         362 :             needed_pathkeys = root->distinct_pathkeys;
    4830             : 
    4831         382 :         path = cheapest_input_path;
    4832         382 :         if (!pathkeys_contained_in(needed_pathkeys, path->pathkeys))
    4833         372 :             path = (Path *) create_sort_path(root, distinct_rel,
    4834             :                                              path,
    4835             :                                              needed_pathkeys,
    4836             :                                              -1.0);
    4837             : 
    4838         382 :         add_path(distinct_rel, (Path *)
    4839         382 :                  create_upper_unique_path(root, distinct_rel,
    4840             :                                           path,
    4841         382 :                                           list_length(root->distinct_pathkeys),
    4842             :                                           numDistinctRows));
    4843             :     }
    4844             : 
    4845             :     /*
    4846             :      * Consider hash-based implementations of DISTINCT, if possible.
    4847             :      *
    4848             :      * If we were not able to make any other types of path, we *must* hash or
    4849             :      * die trying.  If we do have other choices, there are several things that
    4850             :      * should prevent selection of hashing: if the query uses DISTINCT ON
    4851             :      * (because it won't really have the expected behavior if we hash), or if
    4852             :      * enable_hashagg is off, or if it looks like the hashtable will exceed
    4853             :      * work_mem.
    4854             :      *
    4855             :      * Note: grouping_is_hashable() is much more expensive to check than the
    4856             :      * other gating conditions, so we want to do it last.
    4857             :      */
    4858         386 :     if (distinct_rel->pathlist == NIL)
    4859           4 :         allow_hash = true;      /* we have no alternatives */
    4860         382 :     else if (parse->hasDistinctOn || !enable_hashagg)
    4861          36 :         allow_hash = false;     /* policy-based decision not to hash */
    4862             :     else
    4863             :     {
    4864             :         Size        hashentrysize;
    4865             : 
    4866             :         /* Estimate per-hash-entry space at tuple width... */
    4867         346 :         hashentrysize = MAXALIGN(cheapest_input_path->pathtarget->width) +
    4868             :             MAXALIGN(SizeofMinimalTupleHeader);
    4869             :         /* plus the per-hash-entry overhead */
    4870         346 :         hashentrysize += hash_agg_entry_size(0);
    4871             : 
    4872             :         /* Allow hashing only if hashtable is predicted to fit in work_mem */
    4873         346 :         allow_hash = (hashentrysize * numDistinctRows <= work_mem * 1024L);
    4874             :     }
    4875             : 
    4876         386 :     if (allow_hash && grouping_is_hashable(parse->distinctClause))
    4877             :     {
    4878             :         /* Generate hashed aggregate path --- no sort needed */
    4879         350 :         add_path(distinct_rel, (Path *)
    4880         350 :                  create_agg_path(root,
    4881             :                                  distinct_rel,
    4882             :                                  cheapest_input_path,
    4883             :                                  cheapest_input_path->pathtarget,
    4884             :                                  AGG_HASHED,
    4885             :                                  AGGSPLIT_SIMPLE,
    4886             :                                  parse->distinctClause,
    4887             :                                  NIL,
    4888             :                                  NULL,
    4889             :                                  numDistinctRows));
    4890             :     }
    4891             : 
    4892             :     /* Give a helpful error if we failed to find any implementation */
    4893         386 :     if (distinct_rel->pathlist == NIL)
    4894           0 :         ereport(ERROR,
    4895             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4896             :                  errmsg("could not implement DISTINCT"),
    4897             :                  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
    4898             : 
    4899             :     /*
    4900             :      * If there is an FDW that's responsible for all baserels of the query,
    4901             :      * let it consider adding ForeignPaths.
    4902             :      */
    4903         402 :     if (distinct_rel->fdwroutine &&
    4904          16 :         distinct_rel->fdwroutine->GetForeignUpperPaths)
    4905          16 :         distinct_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_DISTINCT,
    4906             :                                                        input_rel, distinct_rel,
    4907             :                                                        NULL);
    4908             : 
    4909             :     /* Let extensions possibly add some more paths */
    4910         386 :     if (create_upper_paths_hook)
    4911           0 :         (*create_upper_paths_hook) (root, UPPERREL_DISTINCT,
    4912             :                                     input_rel, distinct_rel, NULL);
    4913             : 
    4914             :     /* Now choose the best path(s) */
    4915         386 :     set_cheapest(distinct_rel);
    4916             : 
    4917         386 :     return distinct_rel;
    4918             : }
    4919             : 
    4920             : /*
    4921             :  * create_ordered_paths
    4922             :  *
    4923             :  * Build a new upperrel containing Paths for ORDER BY evaluation.
    4924             :  *
    4925             :  * All paths in the result must satisfy the ORDER BY ordering.
    4926             :  * The only new path we need consider is an explicit sort on the
    4927             :  * cheapest-total existing path.
    4928             :  *
    4929             :  * input_rel: contains the source-data Paths
    4930             :  * target: the output tlist the result Paths must emit
    4931             :  * limit_tuples: estimated bound on the number of output tuples,
    4932             :  *      or -1 if no LIMIT or couldn't estimate
    4933             :  */
    4934             : static RelOptInfo *
    4935       36116 : create_ordered_paths(PlannerInfo *root,
    4936             :                      RelOptInfo *input_rel,
    4937             :                      PathTarget *target,
    4938             :                      bool target_parallel_safe,
    4939             :                      double limit_tuples)
    4940             : {
    4941       36116 :     Path       *cheapest_input_path = input_rel->cheapest_total_path;
    4942             :     RelOptInfo *ordered_rel;
    4943             :     ListCell   *lc;
    4944             : 
    4945             :     /* For now, do all work in the (ORDERED, NULL) upperrel */
    4946       36116 :     ordered_rel = fetch_upper_rel(root, UPPERREL_ORDERED, NULL);
    4947             : 
    4948             :     /*
    4949             :      * If the input relation is not parallel-safe, then the ordered relation
    4950             :      * can't be parallel-safe, either.  Otherwise, it's parallel-safe if the
    4951             :      * target list is parallel-safe.
    4952             :      */
    4953       36116 :     if (input_rel->consider_parallel && target_parallel_safe)
    4954       15430 :         ordered_rel->consider_parallel = true;
    4955             : 
    4956             :     /*
    4957             :      * If the input rel belongs to a single FDW, so does the ordered_rel.
    4958             :      */
    4959       36116 :     ordered_rel->serverid = input_rel->serverid;
    4960       36116 :     ordered_rel->userid = input_rel->userid;
    4961       36116 :     ordered_rel->useridiscurrent = input_rel->useridiscurrent;
    4962       36116 :     ordered_rel->fdwroutine = input_rel->fdwroutine;
    4963             : 
    4964       85988 :     foreach(lc, input_rel->pathlist)
    4965             :     {
    4966       49872 :         Path       *path = (Path *) lfirst(lc);
    4967             :         bool        is_sorted;
    4968             : 
    4969       49872 :         is_sorted = pathkeys_contained_in(root->sort_pathkeys,
    4970             :                                           path->pathkeys);
    4971       49872 :         if (path == cheapest_input_path || is_sorted)
    4972             :         {
    4973       48600 :             if (!is_sorted)
    4974             :             {
    4975             :                 /* An explicit sort here can take advantage of LIMIT */
    4976       28816 :                 path = (Path *) create_sort_path(root,
    4977             :                                                  ordered_rel,
    4978             :                                                  path,
    4979             :                                                  root->sort_pathkeys,
    4980             :                                                  limit_tuples);
    4981             :             }
    4982             : 
    4983             :             /* Add projection step if needed */
    4984       48600 :             if (path->pathtarget != target)
    4985        8810 :                 path = apply_projection_to_path(root, ordered_rel,
    4986             :                                                 path, target);
    4987             : 
    4988       48600 :             add_path(ordered_rel, path);
    4989             :         }
    4990             :     }
    4991             : 
    4992             :     /*
    4993             :      * generate_gather_paths() will have already generated a simple Gather
    4994             :      * path for the best parallel path, if any, and the loop above will have
    4995             :      * considered sorting it.  Similarly, generate_gather_paths() will also
    4996             :      * have generated order-preserving Gather Merge plans which can be used
    4997             :      * without sorting if they happen to match the sort_pathkeys, and the loop
    4998             :      * above will have handled those as well.  However, there's one more
    4999             :      * possibility: it may make sense to sort the cheapest partial path
    5000             :      * according to the required output order and then use Gather Merge.
    5001             :      */
    5002       51438 :     if (ordered_rel->consider_parallel && root->sort_pathkeys != NIL &&
    5003       15322 :         input_rel->partial_pathlist != NIL)
    5004             :     {
    5005             :         Path       *cheapest_partial_path;
    5006             : 
    5007        1822 :         cheapest_partial_path = linitial(input_rel->partial_pathlist);
    5008             : 
    5009             :         /*
    5010             :          * If cheapest partial path doesn't need a sort, this is redundant
    5011             :          * with what's already been tried.
    5012             :          */
    5013        1822 :         if (!pathkeys_contained_in(root->sort_pathkeys,
    5014             :                                    cheapest_partial_path->pathkeys))
    5015             :         {
    5016             :             Path       *path;
    5017             :             double      total_groups;
    5018             : 
    5019        1814 :             path = (Path *) create_sort_path(root,
    5020             :                                              ordered_rel,
    5021             :                                              cheapest_partial_path,
    5022             :                                              root->sort_pathkeys,
    5023             :                                              limit_tuples);
    5024             : 
    5025        3628 :             total_groups = cheapest_partial_path->rows *
    5026        1814 :                 cheapest_partial_path->parallel_workers;
    5027        1814 :             path = (Path *)
    5028        1814 :                 create_gather_merge_path(root, ordered_rel,
    5029             :                                          path,
    5030             :                                          path->pathtarget,
    5031             :                                          root->sort_pathkeys, NULL,
    5032             :                                          &total_groups);
    5033             : 
    5034             :             /* Add projection step if needed */
    5035        1814 :             if (path->pathtarget != target)
    5036        1242 :                 path = apply_projection_to_path(root, ordered_rel,
    5037             :                                                 path, target);
    5038             : 
    5039        1814 :             add_path(ordered_rel, path);
    5040             :         }
    5041             :     }
    5042             : 
    5043             :     /*
    5044             :      * If there is an FDW that's responsible for all baserels of the query,
    5045             :      * let it consider adding ForeignPaths.
    5046             :      */
    5047       36436 :     if (ordered_rel->fdwroutine &&
    5048         320 :         ordered_rel->fdwroutine->GetForeignUpperPaths)
    5049         306 :         ordered_rel->fdwroutine->GetForeignUpperPaths(root, UPPERREL_ORDERED,
    5050             :                                                       input_rel, ordered_rel,
    5051             :                                                       NULL);
    5052             : 
    5053             :     /* Let extensions possibly add some more paths */
    5054       36116 :     if (create_upper_paths_hook)
    5055           0 :         (*create_upper_paths_hook) (root, UPPERREL_ORDERED,
    5056             :                                     input_rel, ordered_rel, NULL);
    5057             : 
    5058             :     /*
    5059             :      * No need to bother with set_cheapest here; grouping_planner does not
    5060             :      * need us to do it.
    5061             :      */
    5062             :     Assert(ordered_rel->pathlist != NIL);
    5063             : 
    5064       36116 :     return ordered_rel;
    5065             : }
    5066             : 
    5067             : 
    5068             : /*
    5069             :  * make_group_input_target
    5070             :  *    Generate appropriate PathTarget for initial input to grouping nodes.
    5071             :  *
    5072             :  * If there is grouping or aggregation, the scan/join subplan cannot emit
    5073             :  * the query's final targetlist; for example, it certainly can't emit any
    5074             :  * aggregate function calls.  This routine generates the correct target
    5075             :  * for the scan/join subplan.
    5076             :  *
    5077             :  * The query target list passed from the parser already contains entries
    5078             :  * for all ORDER BY and GROUP BY expressions, but it will not have entries
    5079             :  * for variables used only in HAVING clauses; so we need to add those
    5080             :  * variables to the subplan target list.  Also, we flatten all expressions
    5081             :  * except GROUP BY items into their component variables; other expressions
    5082             :  * will be computed by the upper plan nodes rather than by the subplan.
    5083             :  * For example, given a query like
    5084             :  *      SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
    5085             :  * we want to pass this targetlist to the subplan:
    5086             :  *      a+b,c,d
    5087             :  * where the a+b target will be used by the Sort/Group steps, and the
    5088             :  * other targets will be used for computing the final results.
    5089             :  *
    5090             :  * 'final_target' is the query's final target list (in PathTarget form)
    5091             :  *
    5092             :  * The result is the PathTarget to be computed by the Paths returned from
    5093             :  * query_planner().
    5094             :  */
    5095             : static PathTarget *
    5096       23820 : make_group_input_target(PlannerInfo *root, PathTarget *final_target)
    5097             : {
    5098       23820 :     Query      *parse = root->parse;
    5099             :     PathTarget *input_target;
    5100             :     List       *non_group_cols;
    5101             :     List       *non_group_vars;
    5102             :     int         i;
    5103             :     ListCell   *lc;
    5104             : 
    5105             :     /*
    5106             :      * We must build a target containing all grouping columns, plus any other
    5107             :      * Vars mentioned in the query's targetlist and HAVING qual.
    5108             :      */
    5109       23820 :     input_target = create_empty_pathtarget();
    5110       23820 :     non_group_cols = NIL;
    5111             : 
    5112       23820 :     i = 0;
    5113       53476 :     foreach(lc, final_target->exprs)
    5114             :     {
    5115       29656 :         Expr       *expr = (Expr *) lfirst(lc);
    5116       29656 :         Index       sgref = get_pathtarget_sortgroupref(final_target, i);
    5117             : 
    5118       33770 :         if (sgref && parse->groupClause &&
    5119        4114 :             get_sortgroupref_clause_noerr(sgref, parse->groupClause) != NULL)
    5120             :         {
    5121             :             /*
    5122             :              * It's a grouping column, so add it to the input target as-is.
    5123             :              */
    5124        3242 :             add_column_to_pathtarget(input_target, expr, sgref);
    5125             :         }
    5126             :         else
    5127             :         {
    5128             :             /*
    5129             :              * Non-grouping column, so just remember the expression for later
    5130             :              * call to pull_var_clause.
    5131             :              */
    5132       26414 :             non_group_cols = lappend(non_group_cols, expr);
    5133             :         }
    5134             : 
    5135       29656 :         i++;
    5136             :     }
    5137             : 
    5138             :     /*
    5139             :      * If there's a HAVING clause, we'll need the Vars it uses, too.
    5140             :      */
    5141       23820 :     if (parse->havingQual)
    5142         324 :         non_group_cols = lappend(non_group_cols, parse->havingQual);
    5143             : 
    5144             :     /*
    5145             :      * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
    5146             :      * add them to the input target if not already present.  (A Var used
    5147             :      * directly as a GROUP BY item will be present already.)  Note this
    5148             :      * includes Vars used in resjunk items, so we are covering the needs of
    5149             :      * ORDER BY and window specifications.  Vars used within Aggrefs and
    5150             :      * WindowFuncs will be pulled out here, too.
    5151             :      */
    5152       23820 :     non_group_vars = pull_var_clause((Node *) non_group_cols,
    5153             :                                      PVC_RECURSE_AGGREGATES |
    5154             :                                      PVC_RECURSE_WINDOWFUNCS |
    5155             :                                      PVC_INCLUDE_PLACEHOLDERS);
    5156       23820 :     add_new_columns_to_pathtarget(input_target, non_group_vars);
    5157             : 
    5158             :     /* clean up cruft */
    5159       23820 :     list_free(non_group_vars);
    5160       23820 :     list_free(non_group_cols);
    5161             : 
    5162             :     /* XXX this causes some redundant cost calculation ... */
    5163       23820 :     return set_pathtarget_cost_width(root, input_target);
    5164             : }
    5165             : 
    5166             : /*
    5167             :  * make_partial_grouping_target
    5168             :  *    Generate appropriate PathTarget for output of partial aggregate
    5169             :  *    (or partial grouping, if there are no aggregates) nodes.
    5170             :  *
    5171             :  * A partial aggregation node needs to emit all the same aggregates that
    5172             :  * a regular aggregation node would, plus any aggregates used in HAVING;
    5173             :  * except that the Aggref nodes should be marked as partial aggregates.
    5174             :  *
    5175             :  * In addition, we'd better emit any Vars and PlaceHolderVars that are
    5176             :  * used outside of Aggrefs in the aggregation tlist and HAVING.  (Presumably,
    5177             :  * these would be Vars that are grouped by or used in grouping expressions.)
    5178             :  *
    5179             :  * grouping_target is the tlist to be emitted by the topmost aggregation step.
    5180             :  * havingQual represents the HAVING clause.
    5181             :  */
    5182             : static PathTarget *
    5183        1286 : make_partial_grouping_target(PlannerInfo *root,
    5184             :                              PathTarget *grouping_target,
    5185             :                              Node *havingQual)
    5186             : {
    5187        1286 :     Query      *parse = root->parse;
    5188             :     PathTarget *partial_target;
    5189             :     List       *non_group_cols;
    5190             :     List       *non_group_exprs;
    5191             :     int         i;
    5192             :     ListCell   *lc;
    5193             : 
    5194        1286 :     partial_target = create_empty_pathtarget();
    5195        1286 :     non_group_cols = NIL;
    5196             : 
    5197        1286 :     i = 0;
    5198        4692 :     foreach(lc, grouping_target->exprs)
    5199             :     {
    5200        3406 :         Expr       *expr = (Expr *) lfirst(lc);
    5201        3406 :         Index       sgref = get_pathtarget_sortgroupref(grouping_target, i);
    5202             : 
    5203        5822 :         if (sgref && parse->groupClause &&
    5204        2416 :             get_sortgroupref_clause_noerr(sgref, parse->groupClause) != NULL)
    5205             :         {
    5206             :             /*
    5207             :              * It's a grouping column, so add it to the partial_target as-is.
    5208             :              * (This allows the upper agg step to repeat the grouping calcs.)
    5209             :              */
    5210        1192 :             add_column_to_pathtarget(partial_target, expr, sgref);
    5211             :         }
    5212             :         else
    5213             :         {
    5214             :             /*
    5215             :              * Non-grouping column, so just remember the expression for later
    5216             :              * call to pull_var_clause.
    5217             :              */
    5218        2214 :             non_group_cols = lappend(non_group_cols, expr);
    5219             :         }
    5220             : 
    5221        3406 :         i++;
    5222             :     }
    5223             : 
    5224             :     /*
    5225             :      * If there's a HAVING clause, we'll need the Vars/Aggrefs it uses, too.
    5226             :      */
    5227        1286 :     if (havingQual)
    5228         552 :         non_group_cols = lappend(non_group_cols, havingQual);
    5229             : 
    5230             :     /*
    5231             :      * Pull out all the Vars, PlaceHolderVars, and Aggrefs mentioned in
    5232             :      * non-group cols (plus HAVING), and add them to the partial_target if not
    5233             :      * already present.  (An expression used directly as a GROUP BY item will
    5234             :      * be present already.)  Note this includes Vars used in resjunk items, so
    5235             :      * we are covering the needs of ORDER BY and window specifications.
    5236             :      */
    5237        1286 :     non_group_exprs = pull_var_clause((Node *) non_group_cols,
    5238             :                                       PVC_INCLUDE_AGGREGATES |
    5239             :                                       PVC_RECURSE_WINDOWFUNCS |
    5240             :                                       PVC_INCLUDE_PLACEHOLDERS);
    5241             : 
    5242        1286 :     add_new_columns_to_pathtarget(partial_target, non_group_exprs);
    5243             : 
    5244             :     /*
    5245             :      * Adjust Aggrefs to put them in partial mode.  At this point all Aggrefs
    5246             :      * are at the top level of the target list, so we can just scan the list
    5247             :      * rather than recursing through the expression trees.
    5248             :      */
    5249        5100 :     foreach(lc, partial_target->exprs)
    5250             :     {
    5251        3814 :         Aggref     *aggref = (Aggref *) lfirst(lc);
    5252             : 
    5253        3814 :         if (IsA(aggref, Aggref))
    5254             :         {
    5255             :             Aggref     *newaggref;
    5256             : 
    5257             :             /*
    5258             :              * We shouldn't need to copy the substructure of the Aggref node,
    5259             :              * but flat-copy the node itself to avoid damaging other trees.
    5260             :              */
    5261        2622 :             newaggref = makeNode(Aggref);
    5262        2622 :             memcpy(newaggref, aggref, sizeof(Aggref));
    5263             : 
    5264             :             /* For now, assume serialization is required */
    5265        2622 :             mark_partial_aggref(newaggref, AGGSPLIT_INITIAL_SERIAL);
    5266             : 
    5267        2622 :             lfirst(lc) = newaggref;
    5268             :         }
    5269             :     }
    5270             : 
    5271             :     /* clean up cruft */
    5272        1286 :     list_free(non_group_exprs);
    5273        1286 :     list_free(non_group_cols);
    5274             : 
    5275             :     /* XXX this causes some redundant cost calculation ... */
    5276        1286 :     return set_pathtarget_cost_width(root, partial_target);
    5277             : }
    5278             : 
    5279             : /*
    5280             :  * mark_partial_aggref
    5281             :  *    Adjust an Aggref to make it represent a partial-aggregation step.
    5282             :  *
    5283             :  * The Aggref node is modified in-place; caller must do any copying required.
    5284             :  */
    5285             : void
    5286        4238 : mark_partial_aggref(Aggref *agg, AggSplit aggsplit)
    5287             : {
    5288             :     /* aggtranstype should be computed by this point */
    5289             :     Assert(OidIsValid(agg->aggtranstype));
    5290             :     /* ... but aggsplit should still be as the parser left it */
    5291             :     Assert(agg->aggsplit == AGGSPLIT_SIMPLE);
    5292             : 
    5293             :     /* Mark the Aggref with the intended partial-aggregation mode */
    5294        4238 :     agg->aggsplit = aggsplit;
    5295             : 
    5296             :     /*
    5297             :      * Adjust result type if needed.  Normally, a partial aggregate returns
    5298             :      * the aggregate's transition type; but if that's INTERNAL and we're
    5299             :      * serializing, it returns BYTEA instead.
    5300             :      */
    5301        4238 :     if (DO_AGGSPLIT_SKIPFINAL(aggsplit))
    5302             :     {
    5303        3430 :         if (agg->aggtranstype == INTERNALOID && DO_AGGSPLIT_SERIALIZE(aggsplit))
    5304          48 :             agg->aggtype = BYTEAOID;
    5305             :         else
    5306        3382 :             agg->aggtype = agg->aggtranstype;
    5307             :     }
    5308        4238 : }
    5309             : 
    5310             : /*
    5311             :  * postprocess_setop_tlist
    5312             :  *    Fix up targetlist returned by plan_set_operations().
    5313             :  *
    5314             :  * We need to transpose sort key info from the orig_tlist into new_tlist.
    5315             :  * NOTE: this would not be good enough if we supported resjunk sort keys
    5316             :  * for results of set operations --- then, we'd need to project a whole
    5317             :  * new tlist to evaluate the resjunk columns.  For now, just ereport if we
    5318             :  * find any resjunk columns in orig_tlist.
    5319             :  */
    5320             : static List *
    5321        1248 : postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
    5322             : {
    5323             :     ListCell   *l;
    5324        1248 :     ListCell   *orig_tlist_item = list_head(orig_tlist);
    5325             : 
    5326        3886 :     foreach(l, new_tlist)
    5327             :     {
    5328        2638 :         TargetEntry *new_tle = lfirst_node(TargetEntry, l);
    5329             :         TargetEntry *orig_tle;
    5330             : 
    5331             :         /* ignore resjunk columns in setop result */
    5332        2638 :         if (new_tle->resjunk)
    5333         200 :             continue;
    5334             : 
    5335             :         Assert(orig_tlist_item != NULL);
    5336        2438 :         orig_tle = lfirst_node(TargetEntry, orig_tlist_item);
    5337        2438 :         orig_tlist_item = lnext(orig_tlist, orig_tlist_item);
    5338        2438 :         if (orig_tle->resjunk)   /* should not happen */
    5339           0 :             elog(ERROR, "resjunk output columns are not implemented");
    5340             :         Assert(new_tle->resno == orig_tle->resno);
    5341        2438 :         new_tle->ressortgroupref = orig_tle->ressortgroupref;
    5342             :     }
    5343        1248 :     if (orig_tlist_item != NULL)
    5344           0 :         elog(ERROR, "resjunk output columns are not implemented");
    5345        1248 :     return new_tlist;
    5346             : }
    5347             : 
    5348             : /*
    5349             :  * select_active_windows
    5350             :  *      Create a list of the "active" window clauses (ie, those referenced
    5351             :  *      by non-deleted WindowFuncs) in the order they are to be executed.
    5352             :  */
    5353             : static List *
    5354        1112 : select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
    5355             : {
    5356        1112 :     List       *windowClause = root->parse->windowClause;
    5357        1112 :     List       *result = NIL;
    5358             :     ListCell   *lc;
    5359        1112 :     int         nActive = 0;
    5360        1112 :     WindowClauseSortData *actives = palloc(sizeof(WindowClauseSortData)
    5361        1112 :                                            * list_length(windowClause));
    5362             : 
    5363             :     /* First, construct an array of the active windows */
    5364        2288 :     foreach(lc, windowClause)
    5365             :     {
    5366        1176 :         WindowClause *wc = lfirst_node(WindowClause, lc);
    5367             : 
    5368             :         /* It's only active if wflists shows some related WindowFuncs */
    5369             :         Assert(wc->winref <= wflists->maxWinRef);
    5370        1176 :         if (wflists->windowFuncs[wc->winref] == NIL)
    5371          16 :             continue;
    5372             : 
    5373        1160 :         actives[nActive].wc = wc;   /* original clause */
    5374             : 
    5375             :         /*
    5376             :          * For sorting, we want the list of partition keys followed by the
    5377             :          * list of sort keys. But pathkeys construction will remove duplicates
    5378             :          * between the two, so we can as well (even though we can't detect all
    5379             :          * of the duplicates, since some may come from ECs - that might mean
    5380             :          * we miss optimization chances here). We must, however, ensure that
    5381             :          * the order of entries is preserved with respect to the ones we do
    5382             :          * keep.
    5383             :          *
    5384             :          * partitionClause and orderClause had their own duplicates removed in
    5385             :          * parse analysis, so we're only concerned here with removing
    5386             :          * orderClause entries that also appear in partitionClause.
    5387             :          */
    5388        2320 :         actives[nActive].uniqueOrder =
    5389        1160 :             list_concat_unique(list_copy(wc->partitionClause),
    5390        1160 :                                wc->orderClause);
    5391        1160 :         nActive++;
    5392             :     }
    5393             : 
    5394             :     /*
    5395             :      * Sort active windows by their partitioning/ordering clauses, ignoring
    5396             :      * any framing clauses, so that the windows that need the same sorting are
    5397             :      * adjacent in the list. When we come to generate paths, this will avoid
    5398             :      * inserting additional Sort nodes.
    5399             :      *
    5400             :      * This is how we implement a specific requirement from the SQL standard,
    5401             :      * which says that when two or more windows are order-equivalent (i.e.
    5402             :      * have matching partition and order clauses, even if their names or
    5403             :      * framing clauses differ), then all peer rows must be presented in the
    5404             :      * same order in all of them. If we allowed multiple sort nodes for such
    5405             :      * cases, we'd risk having the peer rows end up in different orders in
    5406             :      * equivalent windows due to sort instability. (See General Rule 4 of
    5407             :      * <window clause> in SQL2008 - SQL2016.)
    5408             :      *
    5409             :      * Additionally, if the entire list of clauses of one window is a prefix
    5410             :      * of another, put first the window with stronger sorting requirements.
    5411             :      * This way we will first sort for stronger window, and won't have to sort
    5412             :      * again for the weaker one.
    5413             :      */
    5414        1112 :     qsort(actives, nActive, sizeof(WindowClauseSortData), common_prefix_cmp);
    5415             : 
    5416             :     /* build ordered list of the original WindowClause nodes */
    5417        2272 :     for (int i = 0; i < nActive; i++)
    5418        1160 :         result = lappend(result, actives[i].wc);
    5419             : 
    5420        1112 :     pfree(actives);
    5421             : 
    5422        1112 :     return result;
    5423             : }
    5424             : 
    5425             : /*
    5426             :  * common_prefix_cmp
    5427             :  *    QSort comparison function for WindowClauseSortData
    5428             :  *
    5429             :  * Sort the windows by the required sorting clauses. First, compare the sort
    5430             :  * clauses themselves. Second, if one window's clauses are a prefix of another
    5431             :  * one's clauses, put the window with more sort clauses first.
    5432             :  */
    5433             : static int
    5434          48 : common_prefix_cmp(const void *a, const void *b)
    5435             : {
    5436          48 :     const WindowClauseSortData *wcsa = a;
    5437          48 :     const WindowClauseSortData *wcsb = b;
    5438             :     ListCell   *item_a;
    5439             :     ListCell   *item_b;
    5440             : 
    5441          84 :     forboth(item_a, wcsa->uniqueOrder, item_b, wcsb->uniqueOrder)
    5442             :     {
    5443          56 :         SortGroupClause *sca = lfirst_node(SortGroupClause, item_a);
    5444          56 :         SortGroupClause *scb = lfirst_node(SortGroupClause, item_b);
    5445             : 
    5446          56 :         if (sca->tleSortGroupRef > scb->tleSortGroupRef)
    5447          20 :             return -1;
    5448          56 :         else if (sca->tleSortGroupRef < scb->tleSortGroupRef)
    5449          12 :             return 1;
    5450          44 :         else if (sca->sortop > scb->sortop)
    5451           0 :             return -1;
    5452          44 :         else if (sca->sortop < scb->sortop)
    5453           8 :             return 1;
    5454          36 :         else if (sca->nulls_first && !scb->nulls_first)
    5455           0 :             return -1;
    5456          36 :         else if (!sca->nulls_first && scb->nulls_first)
    5457           0 :             return 1;
    5458             :         /* no need to compare eqop, since it is fully determined by sortop */
    5459             :     }
    5460             : 
    5461          28 :     if (list_length(wcsa->uniqueOrder) > list_length(wcsb->uniqueOrder))
    5462           4 :         return -1;
    5463          24 :     else if (list_length(wcsa->uniqueOrder) < list_length(wcsb->uniqueOrder))
    5464           8 :         return 1;
    5465             : 
    5466          16 :     return 0;
    5467             : }
    5468             : 
    5469             : /*
    5470             :  * make_window_input_target
    5471             :  *    Generate appropriate PathTarget for initial input to WindowAgg nodes.
    5472             :  *
    5473             :  * When the query has window functions, this function computes the desired
    5474             :  * target to be computed by the node just below the first WindowAgg.
    5475             :  * This tlist must contain all values needed to evaluate the window functions,
    5476             :  * compute the final target list, and perform any required final sort step.
    5477             :  * If multiple WindowAggs are needed, each intermediate one adds its window
    5478             :  * function results onto this base tlist; only the topmost WindowAgg computes
    5479             :  * the actual desired target list.
    5480             :  *
    5481             :  * This function is much like make_group_input_target, though not quite enough
    5482             :  * like it to share code.  As in that function, we flatten most expressions
    5483             :  * into their component variables.  But we do not want to flatten window
    5484             :  * PARTITION BY/ORDER BY clauses, since that might result in multiple
    5485             :  * evaluations of them, which would be bad (possibly even resulting in
    5486             :  * inconsistent answers, if they contain volatile functions).
    5487             :  * Also, we must not flatten GROUP BY clauses that were left unflattened by
    5488             :  * make_group_input_target, because we may no longer have access to the
    5489             :  * individual Vars in them.
    5490             :  *
    5491             :  * Another key difference from make_group_input_target is that we don't
    5492             :  * flatten Aggref expressions, since those are to be computed below the
    5493             :  * window functions and just referenced like Vars above that.
    5494             :  *
    5495             :  * 'final_target' is the query's final target list (in PathTarget form)
    5496             :  * 'activeWindows' is the list of active windows previously identified by
    5497             :  *          select_active_windows.
    5498             :  *
    5499             :  * The result is the PathTarget to be computed by the plan node immediately
    5500             :  * below the first WindowAgg node.
    5501             :  */
    5502             : static PathTarget *
    5503        1112 : make_window_input_target(PlannerInfo *root,
    5504             :                          PathTarget *final_target,
    5505             :                          List *activeWindows)
    5506             : {
    5507        1112 :     Query      *parse = root->parse;
    5508             :     PathTarget *input_target;
    5509             :     Bitmapset  *sgrefs;
    5510             :     List       *flattenable_cols;
    5511             :     List       *flattenable_vars;
    5512             :     int         i;
    5513             :     ListCell   *lc;
    5514             : 
    5515             :     Assert(parse->hasWindowFuncs);
    5516             : 
    5517             :     /*
    5518             :      * Collect the sortgroupref numbers of window PARTITION/ORDER BY clauses
    5519             :      * into a bitmapset for convenient reference below.
    5520             :      */
    5521        1112 :     sgrefs = NULL;
    5522        2272 :     foreach(lc, activeWindows)
    5523             :     {
    5524        1160 :         WindowClause *wc = lfirst_node(WindowClause, lc);
    5525             :         ListCell   *lc2;
    5526             : 
    5527        1512 :         foreach(lc2, wc->partitionClause)
    5528             :         {
    5529         352 :             SortGroupClause *sortcl = lfirst_node(SortGroupClause, lc2);
    5530             : 
    5531         352 :             sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
    5532             :         }
    5533        2216 :         foreach(lc2, wc->orderClause)
    5534             :         {
    5535        1056 :             SortGroupClause *sortcl = lfirst_node(SortGroupClause, lc2);
    5536             : 
    5537        1056 :             sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
    5538             :         }
    5539             :     }
    5540             : 
    5541             :     /* Add in sortgroupref numbers of GROUP BY clauses, too */
    5542        1224 :     foreach(lc, parse->groupClause)
    5543             :     {
    5544         112 :         SortGroupClause *grpcl = lfirst_node(SortGroupClause, lc);
    5545             : 
    5546         112 :         sgrefs = bms_add_member(sgrefs, grpcl->tleSortGroupRef);
    5547             :     }
    5548             : 
    5549             :     /*
    5550             :      * Construct a target containing all the non-flattenable targetlist items,
    5551             :      * and save aside the others for a moment.
    5552             :      */
    5553        1112 :     input_target = create_empty_pathtarget();
    5554        1112 :     flattenable_cols = NIL;
    5555             : 
    5556        1112 :     i = 0;
    5557        4776 :     foreach(lc, final_target->exprs)
    5558             :     {
    5559        3664 :         Expr       *expr = (Expr *) lfirst(lc);
    5560        3664 :         Index       sgref = get_pathtarget_sortgroupref(final_target, i);
    5561             : 
    5562             :         /*
    5563             :          * Don't want to deconstruct window clauses or GROUP BY items.  (Note
    5564             :          * that such items can't contain window functions, so it's okay to
    5565             :          * compute them below the WindowAgg nodes.)
    5566             :          */
    5567        3664 :         if (sgref != 0 && bms_is_member(sgref, sgrefs))
    5568             :         {
    5569             :             /*
    5570             :              * Don't want to deconstruct this value, so add it to the input
    5571             :              * target as-is.
    5572             :              */
    5573        1368 :             add_column_to_pathtarget(input_target, expr, sgref);
    5574             :         }
    5575             :         else
    5576             :         {
    5577             :             /*
    5578             :              * Column is to be flattened, so just remember the expression for
    5579             :              * later call to pull_var_clause.
    5580             :              */
    5581        2296 :             flattenable_cols = lappend(flattenable_cols, expr);
    5582             :         }
    5583             : 
    5584        3664 :         i++;
    5585             :     }
    5586             : 
    5587             :     /*
    5588             :      * Pull out all the Vars and Aggrefs mentioned in flattenable columns, and
    5589             :      * add them to the input target if not already present.  (Some might be
    5590             :      * there already because they're used directly as window/group clauses.)
    5591             :      *
    5592             :      * Note: it's essential to use PVC_INCLUDE_AGGREGATES here, so that any
    5593             :      * Aggrefs are placed in the Agg node's tlist and not left to be computed
    5594             :      * at higher levels.  On the other hand, we should recurse into
    5595             :      * WindowFuncs to make sure their input expressions are available.
    5596             :      */
    5597        1112 :     flattenable_vars = pull_var_clause((Node *) flattenable_cols,
    5598             :                                        PVC_INCLUDE_AGGREGATES |
    5599             :                                        PVC_RECURSE_WINDOWFUNCS |
    5600             :                                        PVC_INCLUDE_PLACEHOLDERS);
    5601        1112 :     add_new_columns_to_pathtarget(input_target, flattenable_vars);
    5602             : 
    5603             :     /* clean up cruft */
    5604        1112 :     list_free(flattenable_vars);
    5605        1112 :     list_free(flattenable_cols);
    5606             : 
    5607             :     /* XXX this causes some redundant cost calculation ... */
    5608        1112 :     return set_pathtarget_cost_width(root, input_target);
    5609             : }
    5610             : 
    5611             : /*
    5612             :  * make_pathkeys_for_window
    5613             :  *      Create a pathkeys list describing the required input ordering
    5614             :  *      for the given WindowClause.
    5615             :  *
    5616             :  * The required ordering is first the PARTITION keys, then the ORDER keys.
    5617             :  * In the future we might try to implement windowing using hashing, in which
    5618             :  * case the ordering could be relaxed, but for now we always sort.
    5619             :  */
    5620             : static List *
    5621        2316 : make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc,
    5622             :                          List *tlist)
    5623             : {
    5624             :     List       *window_pathkeys;
    5625             :     List       *window_sortclauses;
    5626             : 
    5627             :     /* Throw error if can't sort */
    5628        2316 :     if (!grouping_is_sortable(wc->partitionClause))
    5629           0 :         ereport(ERROR,
    5630             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5631             :                  errmsg("could not implement window PARTITION BY"),
    5632             :                  errdetail("Window partitioning columns must be of sortable datatypes.")));
    5633        2316 :     if (!grouping_is_sortable(wc->orderClause))
    5634           0 :         ereport(ERROR,
    5635             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5636             :                  errmsg("could not implement window ORDER BY"),
    5637             :                  errdetail("Window ordering columns must be of sortable datatypes.")));
    5638             : 
    5639             :     /* Okay, make the combined pathkeys */
    5640        2316 :     window_sortclauses = list_concat_copy(wc->partitionClause, wc->orderClause);
    5641        2316 :     window_pathkeys = make_pathkeys_for_sortclauses(root,
    5642             :                                                     window_sortclauses,
    5643             :                                                     tlist);
    5644        2316 :     list_free(window_sortclauses);
    5645        2316 :     return window_pathkeys;
    5646             : }
    5647             : 
    5648             : /*
    5649             :  * make_sort_input_target
    5650             :  *    Generate appropriate PathTarget for initial input to Sort step.
    5651             :  *
    5652             :  * If the query has ORDER BY, this function chooses the target to be computed
    5653             :  * by the node just below the Sort (and DISTINCT, if any, since Unique can't
    5654             :  * project) steps.  This might or might not be identical to the query's final
    5655             :  * output target.
    5656             :  *
    5657             :  * The main argument for keeping the sort-input tlist the same as the final
    5658             :  * is that we avoid a separate projection node (which will be needed if
    5659             :  * they're different, because Sort can't project).  However, there are also
    5660             :  * advantages to postponing tlist evaluation till after the Sort: it ensures
    5661             :  * a consistent order of evaluation for any volatile functions in the tlist,
    5662             :  * and if there's also a LIMIT, we can stop the query without ever computing
    5663             :  * tlist functions for later rows, which is beneficial for both volatile and
    5664             :  * expensive functions.
    5665             :  *
    5666             :  * Our current policy is to postpone volatile expressions till after the sort
    5667             :  * unconditionally (assuming that that's possible, ie they are in plain tlist
    5668             :  * columns and not ORDER BY/GROUP BY/DISTINCT columns).  We also prefer to
    5669             :  * postpone set-returning expressions, because running them beforehand would
    5670             :  * bloat the sort dataset, and because it might cause unexpected output order
    5671             :  * if the sort isn't stable.  However there's a constraint on that: all SRFs
    5672             :  * in the tlist should be evaluated at the same plan step, so that they can
    5673             :  * run in sync in nodeProjectSet.  So if any SRFs are in sort columns, we
    5674             :  * mustn't postpone any SRFs.  (Note that in principle that policy should
    5675             :  * probably get applied to the group/window input targetlists too, but we
    5676             :  * have not done that historically.)  Lastly, expensive expressions are
    5677             :  * postponed if there is a LIMIT, or if root->tuple_fraction shows that
    5678             :  * partial evaluation of the query is possible (if neither is true, we expect
    5679             :  * to have to evaluate the expressions for every row anyway), or if there are
    5680             :  * any volatile or set-returning expressions (since once we've put in a
    5681             :  * projection at all, it won't cost any more to postpone more stuff).
    5682             :  *
    5683             :  * Another issue that could potentially be considered here is that
    5684             :  * evaluating tlist expressions could result in data that's either wider
    5685             :  * or narrower than the input Vars, thus changing the volume of data that
    5686             :  * has to go through the Sort.  However, we usually have only a very bad
    5687             :  * idea of the output width of any expression more complex than a Var,
    5688             :  * so for now it seems too risky to try to optimize on that basis.
    5689             :  *
    5690             :  * Note that if we do produce a modified sort-input target, and then the
    5691             :  * query ends up not using an explicit Sort, no particular harm is done:
    5692             :  * we'll initially use the modified target for the preceding path nodes,
    5693             :  * but then change them to the final target with apply_projection_to_path.
    5694             :  * Moreover, in such a case the guarantees about evaluation order of
    5695             :  * volatile functions still hold, since the rows are sorted already.
    5696             :  *
    5697             :  * This function has some things in common with make_group_input_target and
    5698             :  * make_window_input_target, though the detailed rules for what to do are
    5699             :  * different.  We never flatten/postpone any grouping or ordering columns;
    5700             :  * those are needed before the sort.  If we do flatten a particular
    5701             :  * expression, we leave Aggref and WindowFunc nodes alone, since those were
    5702             :  * computed earlier.
    5703             :  *
    5704             :  * 'final_target' is the query's final target list (in PathTarget form)
    5705             :  * 'have_postponed_srfs' is an output argument, see below
    5706             :  *
    5707             :  * The result is the PathTarget to be computed by the plan node immediately
    5708             :  * below the Sort step (and the Distinct step, if any).  This will be
    5709             :  * exactly final_target if we decide a projection step wouldn't be helpful.
    5710             :  *
    5711             :  * In addition, *have_postponed_srfs is set to true if we choose to postpone
    5712             :  * any set-returning functions to after the Sort.
    5713             :  */
    5714             : static PathTarget *
    5715       35756 : make_sort_input_target(PlannerInfo *root,
    5716             :                        PathTarget *final_target,
    5717             :                        bool *have_postponed_srfs)
    5718             : {
    5719       35756 :     Query      *parse = root->parse;
    5720             :     PathTarget *input_target;
    5721             :     int         ncols;
    5722             :     bool       *col_is_srf;
    5723             :     bool       *postpone_col;
    5724             :     bool        have_srf;
    5725             :     bool        have_volatile;
    5726             :     bool        have_expensive;
    5727             :     bool        have_srf_sortcols;
    5728             :     bool        postpone_srfs;
    5729             :     List       *postponable_cols;
    5730             :     List       *postponable_vars;
    5731             :     int         i;
    5732             :     ListCell   *lc;
    5733             : 
    5734             :     /* Shouldn't get here unless query has ORDER BY */
    5735             :     Assert(parse->sortClause);
    5736             : 
    5737       35756 :     *have_postponed_srfs = false;   /* default result */
    5738             : 
    5739             :     /* Inspect tlist and collect per-column information */
    5740       35756 :     ncols = list_length(final_target->exprs);
    5741       35756 :     col_is_srf = (bool *) palloc0(ncols * sizeof(bool));
    5742       35756 :     postpone_col = (bool *) palloc0(ncols * sizeof(bool));
    5743       35756 :     have_srf = have_volatile = have_expensive = have_srf_sortcols = false;
    5744             : 
    5745       35756 :     i = 0;
    5746      278418 :     foreach(lc, final_target->exprs)
    5747             :     {
    5748      242662 :         Expr       *expr = (Expr *) lfirst(lc);
    5749             : 
    5750             :         /*
    5751             :          * If the column has a sortgroupref, assume it has to be evaluated
    5752             :          * before sorting.  Generally such columns would be ORDER BY, GROUP
    5753             :          * BY, etc targets.  One exception is columns that were removed from
    5754             :          * GROUP BY by remove_useless_groupby_columns() ... but those would
    5755             :          * only be Vars anyway.  There don't seem to be any cases where it
    5756             :          * would be worth the trouble to double-check.
    5757             :          */
    5758      242662 :         if (get_pathtarget_sortgroupref(final_target, i) == 0)
    5759             :         {
    5760             :             /*
    5761             :              * Check for SRF or volatile functions.  Check the SRF case first
    5762             :              * because we must know whether we have any postponed SRFs.
    5763             :              */
    5764      395872 :             if (parse->hasTargetSRFs &&
    5765         124 :                 expression_returns_set((Node *) expr))
    5766             :             {
    5767             :                 /* We'll decide below whether these are postponable */
    5768          56 :                 col_is_srf[i] = true;
    5769          56 :                 have_srf = true;
    5770             :             }
    5771      197818 :             else if (contain_volatile_functions((Node *) expr))
    5772             :             {
    5773             :                 /* Unconditionally postpone */
    5774          64 :                 postpone_col[i] = true;
    5775          64 :                 have_volatile = true;
    5776             :             }
    5777             :             else
    5778             :             {
    5779             :                 /*
    5780             :                  * Else check the cost.  XXX it's annoying to have to do this
    5781             :                  * when set_pathtarget_cost_width() just did it.  Refactor to
    5782             :                  * allow sharing the work?
    5783             :                  */
    5784             :                 QualCost    cost;
    5785             : 
    5786      197754 :                 cost_qual_eval_node(&cost, (Node *) expr, root);
    5787             : 
    5788             :                 /*
    5789             :                  * We arbitrarily define "expensive" as "more than 10X
    5790             :                  * cpu_operator_cost".  Note this will take in any PL function
    5791             :                  * with default cost.
    5792             :                  */
    5793      197754 :                 if (cost.per_tuple > 10 * cpu_operator_cost)
    5794             :                 {
    5795       18208 :                     postpone_col[i] = true;
    5796       18208 :                     have_expensive = true;
    5797             :                 }
    5798             :             }
    5799             :         }
    5800             :         else
    5801             :         {
    5802             :             /* For sortgroupref cols, just check if any contain SRFs */
    5803       89576 :             if (!have_srf_sortcols &&
    5804       44984 :                 parse->hasTargetSRFs &&
    5805         196 :                 expression_returns_set((Node *) expr))
    5806          80 :                 have_srf_sortcols = true;
    5807             :         }
    5808             : 
    5809      242662 :         i++;
    5810             :     }
    5811             : 
    5812             :     /*
    5813             :      * We can postpone SRFs if we have some but none are in sortgroupref cols.
    5814             :      */
    5815       35756 :     postpone_srfs = (have_srf && !have_srf_sortcols);
    5816             : 
    5817             :     /*
    5818             :      * If we don't need a post-sort projection, just return final_target.
    5819             :      */
    5820       71412 :     if (!(postpone_srfs || have_volatile ||
    5821       46910 :           (have_expensive &&
    5822       22500 :            (parse->limitCount || root->tuple_fraction > 0))))
    5823       35648 :         return final_target;
    5824             : 
    5825             :     /*
    5826             :      * Report whether the post-sort projection will contain set-returning
    5827             :      * functions.  This is important because it affects whether the Sort can
    5828             :      * rely on the query's LIMIT (if any) to bound the number of rows it needs
    5829             :      * to return.
    5830             :      */
    5831         108 :     *have_postponed_srfs = postpone_srfs;
    5832             : 
    5833             :     /*
    5834             :      * Construct the sort-input target, taking all non-postponable columns and
    5835             :      * then adding Vars, PlaceHolderVars, Aggrefs, and WindowFuncs found in
    5836             :      * the postponable ones.
    5837             :      */
    5838         108 :     input_target = create_empty_pathtarget();
    5839         108 :     postponable_cols = NIL;
    5840             : 
    5841         108 :     i = 0;
    5842         684 :     foreach(lc, final_target->exprs)
    5843             :     {
    5844         576 :         Expr       *expr = (Expr *) lfirst(lc);
    5845             : 
    5846         576 :         if (postpone_col[i] || (postpone_srfs && col_is_srf[i]))
    5847         112 :             postponable_cols = lappend(postponable_cols, expr);
    5848             :         else
    5849         928 :             add_column_to_pathtarget(input_target, expr,
    5850         928 :                                      get_pathtarget_sortgroupref(final_target, i));
    5851             : 
    5852         576 :         i++;
    5853             :     }
    5854             : 
    5855             :     /*
    5856             :      * Pull out all the Vars, Aggrefs, and WindowFuncs mentioned in
    5857             :      * postponable columns, and add them to the sort-input target if not
    5858             :      * already present.  (Some might be there already.)  We mustn't
    5859             :      * deconstruct Aggrefs or WindowFuncs here, since the projection node
    5860             :      * would be unable to recompute them.
    5861             :      */
    5862         108 :     postponable_vars = pull_var_clause((Node *) postponable_cols,
    5863             :                                        PVC_INCLUDE_AGGREGATES |
    5864             :                                        PVC_INCLUDE_WINDOWFUNCS |
    5865             :                                        PVC_INCLUDE_PLACEHOLDERS);
    5866         108 :     add_new_columns_to_pathtarget(input_target, postponable_vars);
    5867             : 
    5868             :     /* clean up cruft */
    5869         108 :     list_free(postponable_vars);
    5870         108 :     list_free(postponable_cols);
    5871             : 
    5872             :     /* XXX this represents even more redundant cost calculation ... */
    5873         108 :     return set_pathtarget_cost_width(root, input_target);
    5874             : }
    5875             : 
    5876             : /*
    5877             :  * get_cheapest_fractional_path
    5878             :  *    Find the cheapest path for retrieving a specified fraction of all
    5879             :  *    the tuples expected to be returned by the given relation.
    5880             :  *
    5881             :  * We interpret tuple_fraction the same way as grouping_planner.
    5882             :  *
    5883             :  * We assume set_cheapest() has been run on the given rel.
    5884             :  */
    5885             : Path *
    5886      292680 : get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
    5887             : {
    5888      292680 :     Path       *best_path = rel->cheapest_total_path;
    5889             :     ListCell   *l;
    5890             : 
    5891             :     /* If all tuples will be retrieved, just return the cheapest-total path */
    5892      292680 :     if (tuple_fraction <= 0.0)
    5893      288818 :         return best_path;
    5894             : 
    5895             :     /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
    5896        3862 :     if (tuple_fraction >= 1.0 && best_path->rows > 0)
    5897        1600 :         tuple_fraction /= best_path->rows;
    5898             : 
    5899        9404 :     foreach(l, rel->pathlist)
    5900             :     {
    5901        5542 :         Path       *path = (Path *) lfirst(l);
    5902             : 
    5903        7222 :         if (path == rel->cheapest_total_path ||
    5904        1680 :             compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
    5905        5072 :             continue;
    5906             : 
    5907         470 :         best_path = path;
    5908             :     }
    5909             : 
    5910        3862 :     return best_path;
    5911             : }
    5912             : 
    5913             : /*
    5914             :  * adjust_paths_for_srfs
    5915             :  *      Fix up the Paths of the given upperrel to handle tSRFs properly.
    5916             :  *
    5917             :  * The executor can only handle set-returning functions that appear at the
    5918             :  * top level of the targetlist of a ProjectSet plan node.  If we have any SRFs
    5919             :  * that are not at top level, we need to split up the evaluation into multiple
    5920             :  * plan levels in which each level satisfies this constraint.  This function
    5921             :  * modifies each Path of an upperrel that (might) compute any SRFs in its
    5922             :  * output tlist to insert appropriate projection steps.
    5923             :  *
    5924             :  * The given targets and targets_contain_srfs lists are from
    5925             :  * split_pathtarget_at_srfs().  We assume the existing Paths emit the first
    5926             :  * target in targets.
    5927             :  */
    5928             : static void
    5929        3894 : adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel,
    5930             :                       List *targets, List *targets_contain_srfs)
    5931             : {
    5932             :     ListCell   *lc;
    5933             : 
    5934             :     Assert(list_length(targets) == list_length(targets_contain_srfs));
    5935             :     Assert(!linitial_int(targets_contain_srfs));
    5936             : 
    5937             :     /* If no SRFs appear at this plan level, nothing to do */
    5938        3894 :     if (list_length(targets) == 1)
    5939         212 :         return;
    5940             : 
    5941             :     /*
    5942             :      * Stack SRF-evaluation nodes atop each path for the rel.
    5943             :      *
    5944             :      * In principle we should re-run set_cheapest() here to identify the
    5945             :      * cheapest path, but it seems unlikely that adding the same tlist eval
    5946             :      * costs to all the paths would change that, so we don't bother. Instead,
    5947             :      * just assume that the cheapest-startup and cheapest-total paths remain
    5948             :      * so.  (There should be no parameterized paths anymore, so we needn't
    5949             :      * worry about updating cheapest_parameterized_paths.)
    5950             :      */
    5951        7388 :     foreach(lc, rel->pathlist)
    5952             :     {
    5953        3706 :         Path       *subpath = (Path *) lfirst(lc);
    5954        3706 :         Path       *newpath = subpath;
    5955             :         ListCell   *lc1,
    5956             :                    *lc2;
    5957             : 
    5958             :         Assert(subpath->param_info == NULL);
    5959       11790 :         forboth(lc1, targets, lc2, targets_contain_srfs)
    5960             :         {
    5961        8084 :             PathTarget *thistarget = lfirst_node(PathTarget, lc1);
    5962        8084 :             bool        contains_srfs = (bool) lfirst_int(lc2);
    5963             : 
    5964             :             /* If this level doesn't contain SRFs, do regular projection */
    5965        8084 :             if (contains_srfs)
    5966        3746 :                 newpath = (Path *) create_set_projection_path(root,
    5967             :                                                               rel,
    5968             :                                                               newpath,
    5969             :                                                               thistarget);
    5970             :             else
    5971        4338 :                 newpath = (Path *) apply_projection_to_path(root,
    5972             :                                                             rel,
    5973             :                                                             newpath,
    5974             :                                                             thistarget);
    5975             :         }
    5976        3706 :         lfirst(lc) = newpath;
    5977        3706 :         if (subpath == rel->cheapest_startup_path)
    5978          52 :             rel->cheapest_startup_path = newpath;
    5979        3706 :         if (subpath == rel->cheapest_total_path)
    5980          52 :             rel->cheapest_total_path = newpath;
    5981             :     }
    5982             : 
    5983             :     /* Likewise for partial paths, if any */
    5984        3686 :     foreach(lc, rel->partial_pathlist)
    5985             :     {
    5986           4 :         Path       *subpath = (Path *) lfirst(lc);
    5987           4 :         Path       *newpath = subpath;
    5988             :         ListCell   *lc1,
    5989             :                    *lc2;
    5990             : 
    5991             :         Assert(subpath->param_info == NULL);
    5992          16 :         forboth(lc1, targets, lc2, targets_contain_srfs)
    5993             :         {
    5994          12 :             PathTarget *thistarget = lfirst_node(PathTarget, lc1);
    5995          12 :             bool        contains_srfs = (bool) lfirst_int(lc2);
    5996             : 
    5997             :             /* If this level doesn't contain SRFs, do regular projection */
    5998          12 :             if (contains_srfs)
    5999           4 :                 newpath = (Path *) create_set_projection_path(root,
    6000             :                                                               rel,
    6001             :                                                               newpath,
    6002             :                                                               thistarget);
    6003             :             else
    6004             :             {
    6005             :                 /* avoid apply_projection_to_path, in case of multiple refs */
    6006           8 :                 newpath = (Path *) create_projection_path(root,
    6007             :                                                           rel,
    6008             :                                                           newpath,
    6009             :                                                           thistarget);
    6010             :             }
    6011             :         }
    6012           4 :         lfirst(lc) = newpath;
    6013             :     }
    6014             : }
    6015             : 
    6016             : /*
    6017             :  * expression_planner
    6018             :  *      Perform planner's transformations on a standalone expression.
    6019             :  *
    6020             :  * Various utility commands need to evaluate expressions that are not part
    6021             :  * of a plannable query.  They can do so using the executor's regular
    6022             :  * expression-execution machinery, but first the expression has to be fed
    6023             :  * through here to transform it from parser output to something executable.
    6024             :  *
    6025             :  * Currently, we disallow sublinks in standalone expressions, so there's no
    6026             :  * real "planning" involved here.  (That might not always be true though.)
    6027             :  * What we must do is run eval_const_expressions to ensure that any function
    6028             :  * calls are converted to positional notation and function default arguments
    6029             :  * get inserted.  The fact that constant subexpressions get simplified is a
    6030             :  * side-effect that is useful when the expression will get evaluated more than
    6031             :  * once.  Also, we must fix operator function IDs.
    6032             :  *
    6033             :  * This does not return any information about dependencies of the expression.
    6034             :  * Hence callers should use the results only for the duration of the current
    6035             :  * query.  Callers that would like to cache the results for longer should use
    6036             :  * expression_planner_with_deps, probably via the plancache.
    6037             :  *
    6038             :  * Note: this must not make any damaging changes to the passed-in expression
    6039             :  * tree.  (It would actually be okay to apply fix_opfuncids to it, but since
    6040             :  * we first do an expression_tree_mutator-based walk, what is returned will
    6041             :  * be a new node tree.)  The result is constructed in the current memory
    6042             :  * context; beware that this can leak a lot of additional stuff there, too.
    6043             :  */
    6044             : Expr *
    6045       84960 : expression_planner(Expr *expr)
    6046             : {
    6047             :     Node       *result;
    6048             : 
    6049             :     /*
    6050             :      * Convert named-argument function calls, insert default arguments and
    6051             :      * simplify constant subexprs
    6052             :      */
    6053       84960 :     result = eval_const_expressions(NULL, (Node *) expr);
    6054             : 
    6055             :     /* Fill in opfuncid values if missing */
    6056       84960 :     fix_opfuncids(result);
    6057             : 
    6058       84960 :     return (Expr *) result;
    6059             : }
    6060             : 
    6061             : /*
    6062             :  * expression_planner_with_deps
    6063             :  *      Perform planner's transformations on a standalone expression,
    6064             :  *      returning expression dependency information along with the result.
    6065             :  *
    6066             :  * This is identical to expression_planner() except that it also returns
    6067             :  * information about possible dependencies of the expression, ie identities of
    6068             :  * objects whose definitions affect the result.  As in a PlannedStmt, these
    6069             :  * are expressed as a list of relation Oids and a list of PlanInvalItems.
    6070             :  */
    6071             : Expr *
    6072         456 : expression_planner_with_deps(Expr *expr,
    6073             :                              List **relationOids,
    6074             :                              List **invalItems)
    6075             : {
    6076             :     Node       *result;
    6077             :     PlannerGlobal glob;
    6078             :     PlannerInfo root;
    6079             : 
    6080             :     /* Make up dummy planner state so we can use setrefs machinery */
    6081         456 :     MemSet(&glob, 0, sizeof(glob));
    6082         456 :     glob.type = T_PlannerGlobal;
    6083         456 :     glob.relationOids = NIL;
    6084         456 :     glob.invalItems = NIL;
    6085             : 
    6086         456 :     MemSet(&root, 0, sizeof(root));
    6087         456 :     root.type = T_PlannerInfo;
    6088         456 :     root.glob = &glob;
    6089             : 
    6090             :     /*
    6091             :      * Convert named-argument function calls, insert default arguments and
    6092             :      * simplify constant subexprs.  Collect identities of inlined functions
    6093             :      * and elided domains, too.
    6094             :      */
    6095         456 :     result = eval_const_expressions(&root, (Node *) expr);
    6096             : 
    6097             :     /* Fill in opfuncid values if missing */
    6098         456 :     fix_opfuncids(result);
    6099             : 
    6100             :     /*
    6101             :      * Now walk the finished expression to find anything else we ought to
    6102             :      * record as an expression dependency.
    6103             :      */
    6104         456 :     (void) extract_query_dependencies_walker(result, &root);
    6105             : 
    6106         456 :     *relationOids = glob.relationOids;
    6107         456 :     *invalItems = glob.invalItems;
    6108             : 
    6109         456 :     return (Expr *) result;
    6110             : }
    6111             : 
    6112             : 
    6113             : /*
    6114             :  * plan_cluster_use_sort
    6115             :  *      Use the planner to decide how CLUSTER should implement sorting
    6116             :  *
    6117             :  * tableOid is the OID of a table to be clustered on its index indexOid
    6118             :  * (which is already known to be a btree index).  Decide whether it's
    6119             :  * cheaper to do an indexscan or a seqscan-plus-sort to execute the CLUSTER.
    6120             :  * Return true to use sorting, false to use an indexscan.
    6121             :  *
    6122             :  * Note: caller had better already hold some type of lock on the table.
    6123             :  */
    6124             : bool
    6125          74 : plan_cluster_use_sort(Oid tableOid, Oid indexOid)
    6126             : {
    6127             :     PlannerInfo *root;
    6128             :     Query      *query;
    6129             :     PlannerGlobal *glob;
    6130             :     RangeTblEntry *rte;
    6131             :     RelOptInfo *rel;
    6132             :     IndexOptInfo *indexInfo;
    6133             :     QualCost    indexExprCost;
    6134             :     Cost        comparisonCost;
    6135             :     Path       *seqScanPath;
    6136             :     Path        seqScanAndSortPath;
    6137             :     IndexPath  *indexScanPath;
    6138             :     ListCell   *lc;
    6139             : 
    6140             :     /* We can short-circuit the cost comparison if indexscans are disabled */
    6141          74 :     if (!enable_indexscan)
    6142          20 :         return true;            /* use sort */
    6143             : 
    6144             :     /* Set up mostly-dummy planner state */
    6145          54 :     query = makeNode(Query);
    6146          54 :     query->commandType = CMD_SELECT;
    6147             : 
    6148          54 :     glob = makeNode(PlannerGlobal);
    6149             : 
    6150          54 :     root = makeNode(PlannerInfo);
    6151          54 :     root->parse = query;
    6152          54 :     root->glob = glob;
    6153          54 :     root->query_level = 1;
    6154          54 :     root->planner_cxt = CurrentMemoryContext;
    6155          54 :     root->wt_param_id = -1;
    6156             : 
    6157             :     /* Build a minimal RTE for the rel */
    6158          54 :     rte = makeNode(RangeTblEntry);
    6159          54 :     rte->rtekind = RTE_RELATION;
    6160          54 :     rte->relid = tableOid;
    6161          54 :     rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
    6162          54 :     rte->rellockmode = AccessShareLock;
    6163          54 :     rte->lateral = false;
    6164          54 :     rte->inh = false;
    6165          54 :     rte->inFromCl = true;
    6166          54 :     query->rtable = list_make1(rte);
    6167             : 
    6168             :     /* Set up RTE/RelOptInfo arrays */
    6169          54 :     setup_simple_rel_arrays(root);
    6170             : 
    6171             :     /* Build RelOptInfo */
    6172          54 :     rel = build_simple_rel(root, 1, NULL);
    6173             : 
    6174             :     /* Locate IndexOptInfo for the target index */
    6175          54 :     indexInfo = NULL;
    6176          86 :     foreach(lc, rel->indexlist)
    6177             :     {
    6178          86 :         indexInfo = lfirst_node(IndexOptInfo, lc);
    6179          86 :         if (indexInfo->indexoid == indexOid)
    6180          54 :             break;
    6181             :     }
    6182             : 
    6183             :     /*
    6184             :      * It's possible that get_relation_info did not generate an IndexOptInfo
    6185             :      * for the desired index; this could happen if it's not yet reached its
    6186             :      * indcheckxmin usability horizon, or if it's a system index and we're
    6187             :      * ignoring system indexes.  In such cases we should tell CLUSTER to not
    6188             :      * trust the index contents but use seqscan-and-sort.
    6189             :      */
    6190          54 :     if (lc == NULL)             /* not in the list? */
    6191           0 :         return true;            /* use sort */
    6192             : 
    6193             :     /*
    6194             :      * Rather than doing all the pushups that would be needed to use
    6195             :      * set_baserel_size_estimates, just do a quick hack for rows and width.
    6196             :      */
    6197          54 :     rel->rows = rel->tuples;
    6198          54 :     rel->reltarget->width = get_relation_data_width(tableOid, NULL);
    6199             : 
    6200          54 :     root->total_table_pages = rel->pages;
    6201             : 
    6202             :     /*
    6203             :      * Determine eval cost of the index expressions, if any.  We need to
    6204             :      * charge twice that amount for each tuple comparison that happens during
    6205             :      * the sort, since tuplesort.c will have to re-evaluate the index
    6206             :      * expressions each time.  (XXX that's pretty inefficient...)
    6207             :      */
    6208          54 :     cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
    6209          54 :     comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
    6210             : 
    6211             :     /* Estimate the cost of seq scan + sort */
    6212          54 :     seqScanPath = create_seqscan_path(root, rel, NULL, 0);
    6213         108 :     cost_sort(&seqScanAndSortPath, root, NIL,
    6214          54 :               seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
    6215             :               comparisonCost, maintenance_work_mem, -1.0);
    6216             : 
    6217             :     /* Estimate the cost of index scan */
    6218          54 :     indexScanPath = create_index_path(root, indexInfo,
    6219             :                                       NIL, NIL, NIL, NIL,
    6220             :                                       ForwardScanDirection, false,
    6221             :                                       NULL, 1.0, false);
    6222             : 
    6223          54 :     return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
    6224             : }
    6225             : 
    6226             : /*
    6227             :  * plan_create_index_workers
    6228             :  *      Use the planner to decide how many parallel worker processes
    6229             :  *      CREATE INDEX should request for use
    6230             :  *
    6231             :  * tableOid is the table on which the index is to be built.  indexOid is the
    6232             :  * OID of an index to be created or reindexed (which must be a btree index).
    6233             :  *
    6234             :  * Return value is the number of parallel worker processes to request.  It
    6235             :  * may be unsafe to proceed if this is 0.  Note that this does not include the
    6236             :  * leader participating as a worker (value is always a number of parallel
    6237             :  * worker processes).
    6238             :  *
    6239             :  * Note: caller had better already hold some type of lock on the table and
    6240             :  * index.
    6241             :  */
    6242             : int
    6243       22242 : plan_create_index_workers(Oid tableOid, Oid indexOid)
    6244             : {
    6245             :     PlannerInfo *root;
    6246             :     Query      *query;
    6247             :     PlannerGlobal *glob;
    6248             :     RangeTblEntry *rte;
    6249             :     Relation    heap;
    6250             :     Relation    index;
    6251             :     RelOptInfo *rel;
    6252             :     int         parallel_workers;
    6253             :     BlockNumber heap_blocks;
    6254             :     double      reltuples;
    6255             :     double      allvisfrac;
    6256             : 
    6257             :     /* Return immediately when parallelism disabled */
    6258       22242 :     if (max_parallel_maintenance_workers == 0)
    6259          80 :         return 0;
    6260             : 
    6261             :     /* Set up largely-dummy planner state */
    6262       22162 :     query = makeNode(Query);
    6263       22162 :     query->commandType = CMD_SELECT;
    6264             : 
    6265       22162 :     glob = makeNode(PlannerGlobal);
    6266             : 
    6267       22162 :     root = makeNode(PlannerInfo);
    6268       22162 :     root->parse = query;
    6269       22162 :     root->glob = glob;
    6270       22162 :     root->query_level = 1;
    6271       22162 :     root->planner_cxt = CurrentMemoryContext;
    6272       22162 :     root->wt_param_id = -1;
    6273             : 
    6274             :     /*
    6275             :      * Build a minimal RTE.
    6276             :      *
    6277             :      * Mark the RTE with inh = true.  This is a kludge to prevent
    6278             :      * get_relation_info() from fetching index info, which is necessary
    6279             :      * because it does not expect that any IndexOptInfo is currently
    6280             :      * undergoing REINDEX.
    6281             :      */
    6282       22162 :     rte = makeNode(RangeTblEntry);
    6283       22162 :     rte->rtekind = RTE_RELATION;
    6284       22162 :     rte->relid = tableOid;
    6285       22162 :     rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
    6286       22162 :     rte->rellockmode = AccessShareLock;
    6287       22162 :     rte->lateral = false;
    6288       22162 :     rte->inh = true;
    6289       22162 :     rte->inFromCl = true;
    6290       22162 :     query->rtable = list_make1(rte);
    6291             : 
    6292             :     /* Set up RTE/RelOptInfo arrays */
    6293       22162 :     setup_simple_rel_arrays(root);
    6294             : 
    6295             :     /* Build RelOptInfo */
    6296       22162 :     rel = build_simple_rel(root, 1, NULL);
    6297             : 
    6298             :     /* Rels are assumed already locked by the caller */
    6299       22162 :     heap = table_open(tableOid, NoLock);
    6300       22162 :     index = index_open(indexOid, NoLock);
    6301             : 
    6302             :     /*
    6303             :      * Determine if it's safe to proceed.
    6304             :      *
    6305             :      * Currently, parallel workers can't access the leader's temporary tables.
    6306             :      * Furthermore, any index predicate or index expressions must be parallel
    6307             :      * safe.
    6308             :      */
    6309       42796 :     if (heap->rd_rel->relpersistence == RELPERSISTENCE_TEMP ||
    6310       41252 :         !is_parallel_safe(root, (Node *) RelationGetIndexExpressions(index)) ||
    6311       20618 :         !is_parallel_safe(root, (Node *) RelationGetIndexPredicate(index)))
    6312             :     {
    6313        1544 :         parallel_workers = 0;
    6314        1544 :         goto done;
    6315             :     }
    6316             : 
    6317             :     /*
    6318             :      * If parallel_workers storage parameter is set for the table, accept that
    6319             :      * as the number of parallel worker processes to launch (though still cap
    6320             :      * at max_parallel_maintenance_workers).  Note that we deliberately do not
    6321             :      * consider any other factor when parallel_workers is set. (e.g., memory
    6322             :      * use by workers.)
    6323             :      */
    6324       20618 :     if (rel->rel_parallel_workers != -1)
    6325             :     {
    6326          14 :         parallel_workers = Min(rel->rel_parallel_workers,
    6327             :                                max_parallel_maintenance_workers);
    6328          14 :         goto done;
    6329             :     }
    6330             : 
    6331             :     /*
    6332             :      * Estimate heap relation size ourselves, since rel->pages cannot be
    6333             :      * trusted (heap RTE was marked as inheritance parent)
    6334             :      */
    6335       20604 :     estimate_rel_size(heap, NULL, &heap_blocks, &reltuples, &allvisfrac);
    6336             : 
    6337             :     /*
    6338             :      * Determine number of workers to scan the heap relation using generic
    6339             :      * model
    6340             :      */
    6341       20604 :     parallel_workers = compute_parallel_worker(rel, heap_blocks, -1,
    6342             :                                                max_parallel_maintenance_workers);
    6343             : 
    6344             :     /*
    6345             :      * Cap workers based on available maintenance_work_mem as needed.
    6346             :      *
    6347             :      * Note that each tuplesort participant receives an even share of the
    6348             :      * total maintenance_work_mem budget.  Aim to leave participants
    6349             :      * (including the leader as a participant) with no less than 32MB of
    6350             :      * memory.  This leaves cases where maintenance_work_mem is set to 64MB
    6351             :      * immediately past the threshold of being capable of launching a single
    6352             :      * parallel worker to sort.
    6353             :      */
    6354       41440 :     while (parallel_workers > 0 &&
    6355         158 :            maintenance_work_mem / (parallel_workers + 1) < 32768L)
    6356          74 :         parallel_workers--;
    6357             : 
    6358             : done:
    6359       22162 :     index_close(index, NoLock);
    6360       22162 :     table_close(heap, NoLock);
    6361             : 
    6362       22162 :     return parallel_workers;
    6363             : }
    6364             : 
    6365             : /*
    6366             :  * add_paths_to_grouping_rel
    6367             :  *
    6368             :  * Add non-partial paths to grouping relation.
    6369             :  */
    6370             : static void
    6371       24352 : add_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel,
    6372             :                           RelOptInfo *grouped_rel,
    6373             :                           RelOptInfo *partially_grouped_rel,
    6374             :                           const AggClauseCosts *agg_costs,
    6375             :                           grouping_sets_data *gd, double dNumGroups,
    6376             :                           GroupPathExtraData *extra)
    6377             : {
    6378       24352 :     Query      *parse = root->parse;
    6379       24352 :     Path       *cheapest_path = input_rel->cheapest_total_path;
    6380             :     ListCell   *lc;
    6381       24352 :     bool        can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
    6382       24352 :     bool        can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
    6383       24352 :     List       *havingQual = (List *) extra->havingQual;
    6384       24352 :     AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
    6385             : 
    6386       24352 :     if (can_sort)
    6387             :     {
    6388             :         /*
    6389             :          * Use any available suitably-sorted path as input, and also consider
    6390             :          * sorting the cheapest-total path.
    6391             :          */
    6392       50040 :         foreach(lc, input_rel->pathlist)
    6393             :         {
    6394       25692 :             Path       *path = (Path *) lfirst(lc);
    6395             :             bool        is_sorted;
    6396             : 
    6397       25692 :             is_sorted = pathkeys_contained_in(root->group_pathkeys,
    6398             :                                               path->pathkeys);
    6399       25692 :             if (path == cheapest_path || is_sorted)
    6400             :             {
    6401             :                 /* Sort the cheapest-total path if it isn't already sorted */
    6402       25514 :                 if (!is_sorted)
    6403        2538 :                     path = (Path *) create_sort_path(root,
    6404             :                                                      grouped_rel,
    6405             :                                                      path,
    6406             :                                                      root->group_pathkeys,
    6407             :                                                      -1.0);
    6408             : 
    6409             :                 /* Now decide what to stick atop it */
    6410       25514 :                 if (parse->groupingSets)
    6411             :                 {
    6412         464 :                     consider_groupingsets_paths(root, grouped_rel,
    6413             :                                                 path, true, can_hash,
    6414             :                                                 gd, agg_costs, dNumGroups);
    6415             :                 }
    6416       25050 :                 else if (parse->hasAggs)
    6417             :                 {
    6418             :                     /*
    6419             :                      * We have aggregation, possibly with plain GROUP BY. Make
    6420             :                      * an AggPath.
    6421             :                      */
    6422       24768 :                     add_path(grouped_rel, (Path *)
    6423       74304 :                              create_agg_path(root,
    6424             :                                              grouped_rel,
    6425             :                                              path,
    6426       24768 :                                              grouped_rel->reltarget,
    6427       24768 :                                              parse->groupClause ? AGG_SORTED : AGG_PLAIN,
    6428             :                                              AGGSPLIT_SIMPLE,
    6429             :                                              parse->groupClause,
    6430             :                                              havingQual,
    6431             :                                              agg_costs,
    6432             :                                              dNumGroups));
    6433             :                 }
    6434         282 :                 else if (parse->groupClause)
    6435             :                 {
    6436             :                     /*
    6437             :                      * We have GROUP BY without aggregation or grouping sets.
    6438             :                      * Make a GroupPath.
    6439             :                      */
    6440         282 :                     add_path(grouped_rel, (Path *)
    6441         282 :                              create_group_path(root,
    6442             :                                                grouped_rel,
    6443             :                                                path,
    6444             :                                                parse->groupClause,
    6445             :                                                havingQual,
    6446             :                                                dNumGroups));
    6447             :                 }
    6448             :                 else
    6449             :                 {
    6450             :                     /* Other cases should have been handled above */
    6451             :                     Assert(false);
    6452             :                 }
    6453             :             }
    6454             :         }
    6455             : 
    6456             :         /*
    6457             :          * Instead of operating directly on the input relation, we can
    6458             :          * consider finalizing a partially aggregated path.
    6459             :          */
    6460       24348 :         if (partially_grouped_rel != NULL)
    6461             :         {
    6462        2248 :             foreach(lc, partially_grouped_rel->pathlist)
    6463             :             {
    6464        1360 :                 Path       *path = (Path *) lfirst(lc);
    6465             : 
    6466             :                 /*
    6467             :                  * Insert a Sort node, if required.  But there's no point in
    6468             :                  * sorting anything but the cheapest path.
    6469             :                  */
    6470        1360 :                 if (!pathkeys_contained_in(root->group_pathkeys, path->pathkeys))
    6471             :                 {
    6472         352 :                     if (path != partially_grouped_rel->cheapest_total_path)
    6473          64 :                         continue;
    6474         288 :                     path = (Path *) create_sort_path(root,
    6475             :                                                      grouped_rel,
    6476             :                                                      path,
    6477             :                                                      root->group_pathkeys,
    6478             :                                                      -1.0);
    6479             :                 }
    6480             : 
    6481        1296 :                 if (parse->hasAggs)
    6482        1166 :                     add_path(grouped_rel, (Path *)
    6483        3498 :                              create_agg_path(root,
    6484             :                                              grouped_rel,
    6485             :                                              path,
    6486        1166 :                                              grouped_rel->reltarget,
    6487        1166 :                                              parse->groupClause ? AGG_SORTED : AGG_PLAIN,
    6488             :                                              AGGSPLIT_FINAL_DESERIAL,
    6489             :                                              parse->groupClause,
    6490             :                                              havingQual,
    6491             :                                              agg_final_costs,
    6492             :                                              dNumGroups));
    6493             :                 else
    6494         130 :                     add_path(grouped_rel, (Path *)
    6495         130 :                              create_group_path(root,
    6496             :                                                grouped_rel,
    6497             :                                                path,
    6498             :                                                parse->groupClause,
    6499             :                                                havingQual,
    6500             :                                                dNumGroups));
    6501             :             }
    6502             :         }
    6503             :     }
    6504             : 
    6505       24352 :     if (can_hash)
    6506             :     {
    6507             :         double      hashaggtablesize;
    6508             : 
    6509        2452 :         if (parse->groupingSets)
    6510             :         {
    6511             :             /*
    6512             :              * Try for a hash-only groupingsets path over unsorted input.
    6513             :              */
    6514         380 :             consider_groupingsets_paths(root, grouped_rel,
    6515             :                                         cheapest_path, false, true,
    6516             :                                         gd, agg_costs, dNumGroups);
    6517             :         }
    6518             :         else
    6519             :         {
    6520        2072 :             hashaggtablesize = estimate_hashagg_tablesize(cheapest_path,
    6521             :                                                           agg_costs,
    6522             :                                                           dNumGroups);
    6523             : 
    6524             :             /*
    6525             :              * Provided that the estimated size of the hashtable does not
    6526             :              * exceed work_mem, we'll generate a HashAgg Path, although if we
    6527             :              * were unable to sort above, then we'd better generate a Path, so
    6528             :              * that we at least have one.
    6529             :              */
    6530        2072 :             if (hashaggtablesize < work_mem * 1024L ||
    6531           0 :                 grouped_rel->pathlist == NIL)
    6532             :             {
    6533             :                 /*
    6534             :                  * We just need an Agg over the cheapest-total input path,
    6535             :                  * since input order won't matter.
    6536             :                  */
    6537        2072 :                 add_path(grouped_rel, (Path *)
    6538        4144 :                          create_agg_path(root, grouped_rel,
    6539             :                                          cheapest_path,
    6540        2072 :                                          grouped_rel->reltarget,
    6541             :                                          AGG_HASHED,
    6542             :                                          AGGSPLIT_SIMPLE,
    6543             :                                          parse->groupClause,
    6544             :                                          havingQual,
    6545             :                                          agg_costs,
    6546             :                                          dNumGroups));
    6547             :             }
    6548             :         }
    6549             : 
    6550             :         /*
    6551             :          * Generate a Finalize HashAgg Path atop of the cheapest partially
    6552             :          * grouped path, assuming there is one. Once again, we'll only do this
    6553             :          * if it looks as though the hash table won't exceed work_mem.
    6554             :          */
    6555        2452 :         if (partially_grouped_rel && partially_grouped_rel->pathlist)
    6556             :         {
    6557         466 :             Path       *path = partially_grouped_rel->cheapest_total_path;
    6558             : 
    6559         466 :             hashaggtablesize = estimate_hashagg_tablesize(path,
    6560             :                                                           agg_final_costs,
    6561             :                                                           dNumGroups);
    6562             : 
    6563         466 :             if (hashaggtablesize < work_mem * 1024L)
    6564         466 :                 add_path(grouped_rel, (Path *)
    6565         932 :                          create_agg_path(root,
    6566             :                                          grouped_rel,
    6567             :                                          path,
    6568         466 :                                          grouped_rel->reltarget,
    6569             :                                          AGG_HASHED,
    6570             :                                          AGGSPLIT_FINAL_DESERIAL,
    6571             :                                          parse->groupClause,
    6572             :                                          havingQual,
    6573             :                                          agg_final_costs,
    6574             :                                          dNumGroups));
    6575             :         }
    6576             :     }
    6577             : 
    6578             :     /*
    6579             :      * When partitionwise aggregate is used, we might have fully aggregated
    6580             :      * paths in the partial pathlist, because add_paths_to_append_rel() will
    6581             :      * consider a path for grouped_rel consisting of a Parallel Append of
    6582             :      * non-partial paths from each child.
    6583             :      */
    6584       24352 :     if (grouped_rel->partial_pathlist != NIL)
    6585         108 :         gather_grouping_paths(root, grouped_rel);
    6586       24352 : }
    6587             : 
    6588             : /*
    6589             :  * create_partial_grouping_paths
    6590             :  *
    6591             :  * Create a new upper relation representing the result of partial aggregation
    6592             :  * and populate it with appropriate paths.  Note that we don't finalize the
    6593             :  * lists of paths here, so the caller can add additional partial or non-partial
    6594             :  * paths and must afterward call gather_grouping_paths and set_cheapest on
    6595             :  * the returned upper relation.
    6596             :  *
    6597             :  * All paths for this new upper relation -- both partial and non-partial --
    6598             :  * have been partially aggregated but require a subsequent FinalizeAggregate
    6599             :  * step.
    6600             :  *
    6601             :  * NB: This function is allowed to return NULL if it determines that there is
    6602             :  * no real need to create a new RelOptInfo.
    6603             :  */
    6604             : static RelOptInfo *
    6605        9038 : create_partial_grouping_paths(PlannerInfo *root,
    6606             :                               RelOptInfo *grouped_rel,
    6607             :                               RelOptInfo *input_rel,
    6608             :                               grouping_sets_data *gd,
    6609             :                               GroupPathExtraData *extra,
    6610             :                               bool force_rel_creation)
    6611             : {
    6612        9038 :     Query      *parse = root->parse;
    6613             :     RelOptInfo *partially_grouped_rel;
    6614        9038 :     AggClauseCosts *agg_partial_costs = &extra->agg_partial_costs;
    6615        9038 :     AggClauseCosts *agg_final_costs = &extra->agg_final_costs;
    6616        9038 :     Path       *cheapest_partial_path = NULL;
    6617        9038 :     Path       *cheapest_total_path = NULL;
    6618        9038 :     double      dNumPartialGroups = 0;
    6619        9038 :     double      dNumPartialPartialGroups = 0;
    6620             :     ListCell   *lc;
    6621        9038 :     bool        can_hash = (extra->flags & GROUPING_CAN_USE_HASH) != 0;
    6622        9038 :     bool        can_sort = (extra->flags & GROUPING_CAN_USE_SORT) != 0;
    6623             : 
    6624             :     /*
    6625             :      * Consider whether we should generate partially aggregated non-partial
    6626             :      * paths.  We can only do this if we have a non-partial path, and only if
    6627             :      * the parent of the input rel is performing partial partitionwise
    6628             :      * aggregation.  (Note that extra->patype is the type of partitionwise
    6629             :      * aggregation being used at the parent level, not this level.)
    6630             :      */
    6631       18076 :     if (input_rel->pathlist != NIL &&
    6632        9038 :         extra->patype == PARTITIONWISE_AGGREGATE_PARTIAL)
    6633         398 :         cheapest_total_path = input_rel->cheapest_total_path;
    6634             : 
    6635             :     /*
    6636             :      * If parallelism is possible for grouped_rel, then we should consider
    6637             :      * generating partially-grouped partial paths.  However, if the input rel
    6638             :      * has no partial paths, then we can't.
    6639             :      */
    6640        9038 :     if (grouped_rel->consider_parallel && input_rel->partial_pathlist != NIL)
    6641        1030 :         cheapest_partial_path = linitial(input_rel->partial_pathlist);
    6642             : 
    6643             :     /*
    6644             :      * If we can't partially aggregate partial paths, and we can't partially
    6645             :      * aggregate non-partial paths, then don't bother creating the new
    6646             :      * RelOptInfo at all, unless the caller specified force_rel_creation.
    6647             :      */
    6648        9038 :     if (cheapest_total_path == NULL &&
    6649        7810 :         cheapest_partial_path == NULL &&
    6650        7810 :         !force_rel_creation)
    6651        7752 :         return NULL;
    6652             : 
    6653             :     /*
    6654             :      * Build a new upper relation to represent the result of partially
    6655             :      * aggregating the rows from the input relation.
    6656             :      */
    6657        1286 :     partially_grouped_rel = fetch_upper_rel(root,
    6658             :                                             UPPERREL_PARTIAL_GROUP_AGG,
    6659             :                                             grouped_rel->relids);
    6660        1286 :     partially_grouped_rel->consider_parallel =
    6661        1286 :         grouped_rel->consider_parallel;
    6662        1286 :     partially_grouped_rel->reloptkind = grouped_rel->reloptkind;
    6663        1286 :     partially_grouped_rel->serverid = grouped_rel->serverid;
    6664        1286 :     partially_grouped_rel->userid = grouped_rel->userid;
    6665        1286 :     partially_grouped_rel->useridiscurrent = grouped_rel->useridiscurrent;
    6666        1286 :     partially_grouped_rel->fdwroutine = grouped_rel->fdwroutine;
    6667             : 
    6668             :     /*
    6669             :      * Build target list for partial aggregate paths.  These paths cannot just
    6670             :      * emit the same tlist as regular aggregate paths, because (1) we must
    6671             :      * include Vars and Aggrefs needed in HAVING, which might not appear in
    6672             :      * the result tlist, and (2) the Aggrefs must be set in partial mode.
    6673             :      */
    6674        1286 :     partially_grouped_rel->reltarget =
    6675        1286 :         make_partial_grouping_target(root, grouped_rel->reltarget,
    6676             :                                      extra->havingQual);
    6677             : 
    6678        1286 :     if (!extra->partial_costs_set)
    6679             :     {
    6680             :         /*
    6681             :          * Collect statistics about aggregates for estimating costs of
    6682             :          * performing aggregation in parallel.
    6683             :          */
    6684         696 :         MemSet(agg_partial_costs, 0, sizeof(AggClauseCosts));
    6685         696 :         MemSet(agg_final_costs, 0, sizeof(AggClauseCosts));
    6686         696 :         if (parse->hasAggs)
    6687             :         {
    6688             :             List       *partial_target_exprs;
    6689             : 
    6690             :             /* partial phase */
    6691         632 :             partial_target_exprs = partially_grouped_rel->reltarget->exprs;
    6692         632 :             get_agg_clause_costs(root, (Node *) partial_target_exprs,
    6693             :                                  AGGSPLIT_INITIAL_SERIAL,
    6694             :                                  agg_partial_costs);
    6695             : 
    6696             :             /* final phase */
    6697         632 :             get_agg_clause_costs(root, (Node *) grouped_rel->reltarget->exprs,
    6698             :                                  AGGSPLIT_FINAL_DESERIAL,
    6699             :                                  agg_final_costs);
    6700         632 :             get_agg_clause_costs(root, extra->havingQual,
    6701             :                                  AGGSPLIT_FINAL_DESERIAL,
    6702             :                                  agg_final_costs);
    6703             :         }
    6704             : 
    6705         696 :         extra->partial_costs_set = true;
    6706             :     }
    6707             : 
    6708             :     /* Estimate number of partial groups. */
    6709        1286 :     if (cheapest_total_path != NULL)
    6710         398 :         dNumPartialGroups =
    6711         398 :             get_number_of_groups(root,
    6712             :                                  cheapest_total_path->rows,
    6713             :                                  gd,
    6714             :                                  extra->targetList);
    6715        1286 :     if (cheapest_partial_path != NULL)
    6716        1030 :         dNumPartialPartialGroups =
    6717        1030 :             get_number_of_groups(root,
    6718             :                                  cheapest_partial_path->rows,
    6719             :                                  gd,
    6720             :                                  extra->targetList);
    6721             : 
    6722        1286 :     if (can_sort && cheapest_total_path != NULL)
    6723             :     {
    6724             :         /* This should have been checked previously */
    6725             :         Assert(parse->hasAggs || parse->groupClause);
    6726             : 
    6727             :         /*
    6728             :          * Use any available suitably-sorted path as input, and also consider
    6729             :          * sorting the cheapest partial path.
    6730             :          */
    6731         802 :         foreach(lc, input_rel->pathlist)
    6732             :         {
    6733         404 :             Path       *path = (Path *) lfirst(lc);
    6734             :             bool        is_sorted;
    6735             : 
    6736         404 :             is_sorted = pathkeys_contained_in(root->group_pathkeys,
    6737             :                                               path->pathkeys);
    6738         404 :             if (path == cheapest_total_path || is_sorted)
    6739             :             {
    6740             :                 /* Sort the cheapest partial path, if it isn't already */
    6741         404 :                 if (!is_sorted)
    6742         398 :                     path = (Path *) create_sort_path(root,
    6743             :                                                      partially_grouped_rel,
    6744             :                                                      path,
    6745             :                                                      root->group_pathkeys,
    6746             :                                                      -1.0);
    6747             : 
    6748         404 :                 if (parse->hasAggs)
    6749         356 :                     add_path(partially_grouped_rel, (Path *)
    6750        1068 :                              create_agg_path(root,
    6751             :                                              partially_grouped_rel,
    6752             :                                              path,
    6753         356 :                                              partially_grouped_rel->reltarget,
    6754         356 :                                              parse->groupClause ? AGG_SORTED : AGG_PLAIN,
    6755             :                                              AGGSPLIT_INITIAL_SERIAL,
    6756             :                                              parse->groupClause,
    6757             :                                              NIL,
    6758             :                                              agg_partial_costs,
    6759             :                                              dNumPartialGroups));
    6760             :                 else
    6761          48 :                     add_path(partially_grouped_rel, (Path *)
    6762          48 :                              create_group_path(root,
    6763             :                                                partially_grouped_rel,
    6764             :                                                path,
    6765             :                                                parse->groupClause,
    6766             :                                                NIL,
    6767             :                                                dNumPartialGroups));
    6768             :             }
    6769             :         }
    6770             :     }
    6771             : 
    6772        1286 :     if (can_sort && cheapest_partial_path != NULL)
    6773             :     {
    6774             :         /* Similar to above logic, but for partial paths. */
    6775        2060 :         foreach(lc, input_rel->partial_pathlist)
    6776             :         {
    6777        1030 :             Path       *path = (Path *) lfirst(lc);
    6778             :             bool        is_sorted;
    6779             : 
    6780        1030 :             is_sorted = pathkeys_contained_in(root->group_pathkeys,
    6781             :                                               path->pathkeys);
    6782        1030 :             if (path == cheapest_partial_path || is_sorted)
    6783             :             {
    6784             :                 /* Sort the cheapest partial path, if it isn't already */
    6785        1030 :                 if (!is_sorted)
    6786         608 :                     path = (Path *) create_sort_path(root,
    6787             :                                                      partially_grouped_rel,
    6788             :                                                      path,
    6789             :                                                      root->group_pathkeys,
    6790             :                                                      -1.0);
    6791             : 
    6792        1030 :                 if (parse->hasAggs)
    6793         974 :                     add_partial_path(partially_grouped_rel, (Path *)
    6794        2922 :                                      create_agg_path(root,
    6795             :                                                      partially_grouped_rel,
    6796             :                                                      path,
    6797         974 :                                                      partially_grouped_rel->reltarget,
    6798         974 :                                                      parse->groupClause ? AGG_SORTED : AGG_PLAIN,
    6799             :                                                      AGGSPLIT_INITIAL_SERIAL,
    6800             :                                                      parse->groupClause,
    6801             :                                                      NIL,
    6802             :                                                      agg_partial_costs,
    6803             :                                                      dNumPartialPartialGroups));
    6804             :                 else
    6805          56 :                     add_partial_path(partially_grouped_rel, (Path *)
    6806          56 :                                      create_group_path(root,
    6807             :                                                        partially_grouped_rel,
    6808             :                                                        path,
    6809             :                                                        parse->groupClause,
    6810             :                                                        NIL,
    6811             :                                                        dNumPartialPartialGroups));
    6812             :             }
    6813             :         }
    6814             :     }
    6815             : 
    6816        1286 :     if (can_hash && cheapest_total_path != NULL)
    6817             :     {
    6818             :         double      hashaggtablesize;
    6819             : 
    6820             :         /* Checked above */
    6821             :         Assert(parse->hasAggs || parse->groupClause);
    6822             : 
    6823         398 :         hashaggtablesize =
    6824             :             estimate_hashagg_tablesize(cheapest_total_path,
    6825             :                                        agg_partial_costs,
    6826             :                                        dNumPartialGroups);
    6827             : 
    6828             :         /*
    6829             :          * Tentatively produce a partial HashAgg Path, depending on if it
    6830             :          * looks as if the hash table will fit in work_mem.
    6831             :          */
    6832         398 :         if (hashaggtablesize < work_mem * 1024L &&
    6833             :             cheapest_total_path != NULL)
    6834             :         {
    6835         398 :             add_path(partially_grouped_rel, (Path *)
    6836         796 :                      create_agg_path(root,
    6837             :                                      partially_grouped_rel,
    6838             :                                      cheapest_total_path,
    6839         398 :                                      partially_grouped_rel->reltarget,
    6840             :                                      AGG_HASHED,
    6841             :                                      AGGSPLIT_INITIAL_SERIAL,
    6842             :                                      parse->groupClause,
    6843             :                                      NIL,
    6844             :                                      agg_partial_costs,
    6845             :                                      dNumPartialGroups));
    6846             :         }
    6847             :     }
    6848             : 
    6849        1286 :     if (can_hash && cheapest_partial_path != NULL)
    6850             :     {
    6851             :         double      hashaggtablesize;
    6852             : 
    6853         608 :         hashaggtablesize =
    6854             :             estimate_hashagg_tablesize(cheapest_partial_path,
    6855             :                                        agg_partial_costs,
    6856             :                                        dNumPartialPartialGroups);
    6857             : 
    6858             :         /* Do the same for partial paths. */
    6859         608 :         if (hashaggtablesize < work_mem * 1024L &&
    6860             :             cheapest_partial_path != NULL)
    6861             :         {
    6862         608 :             add_partial_path(partially_grouped_rel, (Path *)
    6863        1216 :                              create_agg_path(root,
    6864             :                                              partially_grouped_rel,
    6865             :                                              cheapest_partial_path,
    6866         608 :                                              partially_grouped_rel->reltarget,
    6867             :                                              AGG_HASHED,
    6868             :                                              AGGSPLIT_INITIAL_SERIAL,
    6869             :                                              parse->groupClause,
    6870             :                                              NIL,
    6871             :                                              agg_partial_costs,
    6872             :                                              dNumPartialPartialGroups));
    6873             :         }
    6874             :     }
    6875             : 
    6876             :     /*
    6877             :      * If there is an FDW that's responsible for all baserels of the query,
    6878             :      * let it consider adding partially grouped ForeignPaths.
    6879             :      */
    6880        1292 :     if (partially_grouped_rel->fdwroutine &&
    6881           6 :         partially_grouped_rel->fdwroutine->GetForeignUpperPaths)
    6882             :     {
    6883           6 :         FdwRoutine *fdwroutine = partially_grouped_rel->fdwroutine;
    6884             : 
    6885           6 :         fdwroutine->GetForeignUpperPaths(root,
    6886             :                                          UPPERREL_PARTIAL_GROUP_AGG,
    6887             :                                          input_rel, partially_grouped_rel,
    6888             :                                          extra);
    6889             :     }
    6890             : 
    6891        1286 :     return partially_grouped_rel;
    6892             : }
    6893             : 
    6894             : /*
    6895             :  * Generate Gather and Gather Merge paths for a grouping relation or partial
    6896             :  * grouping relation.
    6897             :  *
    6898             :  * generate_gather_paths does most of the work, but we also consider a special
    6899             :  * case: we could try sorting the data by the group_pathkeys and then applying
    6900             :  * Gather Merge.
    6901             :  *
    6902             :  * NB: This function shouldn't be used for anything other than a grouped or
    6903             :  * partially grouped relation not only because of the fact that it explicitly
    6904             :  * references group_pathkeys but we pass "true" as the third argument to
    6905             :  * generate_gather_paths().
    6906             :  */
    6907             : static void
    6908         938 : gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
    6909             : {
    6910             :     Path       *cheapest_partial_path;
    6911             : 
    6912             :     /* Try Gather for unordered paths and Gather Merge for ordered ones. */
    6913         938 :     generate_gather_paths(root, rel, true);
    6914             : 
    6915             :     /* Try cheapest partial path + explicit Sort + Gather Merge. */
    6916         938 :     cheapest_partial_path = linitial(rel->partial_pathlist);
    6917         938 :     if (!pathkeys_contained_in(root->group_pathkeys,
    6918             :                                cheapest_partial_path->pathkeys))
    6919             :     {
    6920             :         Path       *path;
    6921             :         double      total_groups;
    6922             : 
    6923         470 :         total_groups =
    6924         470 :             cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
    6925         470 :         path = (Path *) create_sort_path(root, rel, cheapest_partial_path,
    6926             :                                          root->group_pathkeys,
    6927             :                                          -1.0);
    6928         470 :         path = (Path *)
    6929         470 :             create_gather_merge_path(root,
    6930             :                                      rel,
    6931             :                                      path,
    6932         470 :                                      rel->reltarget,
    6933             :                                      root->group_pathkeys,
    6934             :                                      NULL,
    6935             :                                      &total_groups);
    6936             : 
    6937         470 :         add_path(rel, path);
    6938             :     }
    6939         938 : }
    6940             : 
    6941             : /*
    6942             :  * can_partial_agg
    6943             :  *
    6944             :  * Determines whether or not partial grouping and/or aggregation is possible.
    6945             :  * Returns true when possible, false otherwise.
    6946             :  */
    6947             : static bool
    6948       23808 : can_partial_agg(PlannerInfo *root, const AggClauseCosts *agg_costs)
    6949             : {
    6950       23808 :     Query      *parse = root->parse;
    6951             : 
    6952       23808 :     if (!parse->hasAggs && parse->groupClause == NIL)
    6953             :     {
    6954             :         /*
    6955             :          * We don't know how to do parallel aggregation unless we have either
    6956             :          * some aggregates or a grouping clause.
    6957             :          */
    6958           0 :         return false;
    6959             :     }
    6960       23808 :     else if (parse->groupingSets)
    6961             :     {
    6962             :         /* We don't know how to do grouping sets in parallel. */
    6963         432 :         return false;
    6964             :     }
    6965       23376 :     else if (agg_costs->hasNonPartial || agg_costs->hasNonSerial)
    6966             :     {
    6967             :         /* Insufficient support for partial mode. */
    6968       15232 :         return false;
    6969             :     }
    6970             : 
    6971             :     /* Everything looks good. */
    6972        8144 :     return true;
    6973             : }
    6974             : 
    6975             : /*
    6976             :  * apply_scanjoin_target_to_paths
    6977             :  *
    6978             :  * Adjust the final scan/join relation, and recursively all of its children,
    6979             :  * to generate the final scan/join target.  It would be more correct to model
    6980             :  * this as a separate planning step with a new RelOptInfo at the toplevel and
    6981             :  * for each child relation, but doing it this way is noticeably cheaper.
    6982             :  * Maybe that problem can be solved at some point, but for now we do this.
    6983             :  *
    6984             :  * If tlist_same_exprs is true, then the scan/join target to be applied has
    6985             :  * the same expressions as the existing reltarget, so we need only insert the
    6986             :  * appropriate sortgroupref information.  By avoiding the creation of
    6987             :  * projection paths we save effort both immediately and at plan creation time.
    6988             :  */
    6989             : static void
    6990      312642 : apply_scanjoin_target_to_paths(PlannerInfo *root,
    6991             :                                RelOptInfo *rel,
    6992             :                                List *scanjoin_targets,
    6993             :                                List *scanjoin_targets_contain_srfs,
    6994             :                                bool scanjoin_target_parallel_safe,
    6995             :                                bool tlist_same_exprs)
    6996             : {
    6997      312642 :     bool        rel_is_partitioned = IS_PARTITIONED_REL(rel);
    6998             :     PathTarget *scanjoin_target;
    6999             :     ListCell   *lc;
    7000             : 
    7001             :     /* This recurses, so be paranoid. */
    7002      312642 :     check_stack_depth();
    7003             : 
    7004             :     /*
    7005             :      * If the rel is partitioned, we want to drop its existing paths and
    7006             :      * generate new ones.  This function would still be correct if we kept the
    7007             :      * existing paths: we'd modify them to generate the correct target above
    7008             :      * the partitioning Append, and then they'd compete on cost with paths
    7009             :      * generating the target below the Append.  However, in our current cost
    7010             :      * model the latter way is always the same or cheaper cost, so modifying
    7011             :      * the existing paths would just be useless work.  Moreover, when the cost
    7012             :      * is the same, varying roundoff errors might sometimes allow an existing
    7013             :      * path to be picked, resulting in undesirable cross-platform plan
    7014             :      * variations.  So we drop old paths and thereby force the work to be done
    7015             :      * below the Append, except in the case of a non-parallel-safe target.
    7016             :      *
    7017             :      * Some care is needed, because we have to allow generate_gather_paths to
    7018             :      * see the old partial paths in the next stanza.  Hence, zap the main
    7019             :      * pathlist here, then allow generate_gather_paths to add path(s) to the
    7020             :      * main list, and finally zap the partial pathlist.
    7021             :      */
    7022      312642 :     if (rel_is_partitioned)
    7023        6682 :         rel->pathlist = NIL;
    7024             : 
    7025             :     /*
    7026             :      * If the scan/join target is not parallel-safe, partial paths cannot
    7027             :      * generate it.
    7028             :      */
    7029      312642 :     if (!scanjoin_target_parallel_safe)
    7030             :     {
    7031             :         /*
    7032             :          * Since we can't generate the final scan/join target in parallel
    7033             :          * workers, this is our last opportunity to use any partial paths that
    7034             :          * exist; so build Gather path(s) that use them and emit whatever the
    7035             :          * current reltarget is.  We don't do this in the case where the
    7036             :          * target is parallel-safe, since we will be able to generate superior
    7037             :          * paths by doing it after the final scan/join target has been
    7038             :          * applied.
    7039             :          */
    7040       65226 :         generate_gather_paths(root, rel, false);
    7041             : 
    7042             :         /* Can't use parallel query above this level. */
    7043       65226 :         rel->partial_pathlist = NIL;
    7044       65226 :         rel->consider_parallel = false;
    7045             :     }
    7046             : 
    7047             :     /* Finish dropping old paths for a partitioned rel, per comment above */
    7048      312642 :     if (rel_is_partitioned)
    7049        6682 :         rel->partial_pathlist = NIL;
    7050             : 
    7051             :     /* Extract SRF-free scan/join target. */
    7052      312642 :     scanjoin_target = linitial_node(PathTarget, scanjoin_targets);
    7053             : 
    7054             :     /*
    7055             :      * Apply the SRF-free scan/join target to each existing path.
    7056             :      *
    7057             :      * If the tlist exprs are the same, we can just inject the sortgroupref
    7058             :      * information into the existing pathtargets.  Otherwise, replace each
    7059             :      * path with a projection path that generates the SRF-free scan/join
    7060             :      * target.  This can't change the ordering of paths within rel->pathlist,
    7061             :      * so we just modify the list in place.
    7062             :      */
    7063      634376 :     foreach(lc, rel->pathlist)
    7064             :     {
    7065      321734 :         Path       *subpath = (Path *) lfirst(lc);
    7066             : 
    7067             :         /* Shouldn't have any parameterized paths anymore */
    7068             :         Assert(subpath->param_info == NULL);
    7069             : 
    7070      321734 :         if (tlist_same_exprs)
    7071      204776 :             subpath->pathtarget->sortgrouprefs =
    7072      102388 :                 scanjoin_target->sortgrouprefs;
    7073             :         else
    7074             :         {
    7075             :             Path       *newpath;
    7076             : 
    7077      219346 :             newpath = (Path *) create_projection_path(root, rel, subpath,
    7078             :                                                       scanjoin_target);
    7079      219346 :             lfirst(lc) = newpath;
    7080             :         }
    7081             :     }
    7082             : 
    7083             :     /* Likewise adjust the targets for any partial paths. */
    7084      322792 :     foreach(lc, rel->partial_pathlist)
    7085             :     {
    7086       10150 :         Path       *subpath = (Path *) lfirst(lc);
    7087             : 
    7088             :         /* Shouldn't have any parameterized paths anymore */
    7089             :         Assert(subpath->param_info == NULL);
    7090             : 
    7091       10150 :         if (tlist_same_exprs)
    7092       16480 :             subpath->pathtarget->sortgrouprefs =
    7093        8240 :                 scanjoin_target->sortgrouprefs;
    7094             :         else
    7095             :         {
    7096             :             Path       *newpath;
    7097             : 
    7098        1910 :             newpath = (Path *) create_projection_path(root, rel, subpath,
    7099             :                                                       scanjoin_target);
    7100        1910 :             lfirst(lc) = newpath;
    7101             :         }
    7102             :     }
    7103             : 
    7104             :     /*
    7105             :      * Now, if final scan/join target contains SRFs, insert ProjectSetPath(s)
    7106             :      * atop each existing path.  (Note that this function doesn't look at the
    7107             :      * cheapest-path fields, which is a good thing because they're bogus right
    7108             :      * now.)
    7109             :      */
    7110      312642 :     if (root->parse->hasTargetSRFs)
    7111        3682 :         adjust_paths_for_srfs(root, rel,
    7112             :                               scanjoin_targets,
    7113             :                               scanjoin_targets_contain_srfs);
    7114             : 
    7115             :     /*
    7116             :      * Update the rel's target to be the final (with SRFs) scan/join target.
    7117             :      * This now matches the actual output of all the paths, and we might get
    7118             :      * confused in createplan.c if they don't agree.  We must do this now so
    7119             :      * that any append paths made in the next part will use the correct
    7120             :      * pathtarget (cf. create_append_path).
    7121             :      *
    7122             :      * Note that this is also necessary if GetForeignUpperPaths() gets called
    7123             :      * on the final scan/join relation or on any of its children, since the
    7124             :      * FDW might look at the rel's target to create ForeignPaths.
    7125             :      */
    7126      312642 :     rel->reltarget = llast_node(PathTarget, scanjoin_targets);
    7127             : 
    7128             :     /*
    7129             :      * If the relation is partitioned, recursively apply the scan/join target
    7130             :      * to all partitions, and generate brand-new Append paths in which the
    7131             :      * scan/join target is computed below the Append rather than above it.
    7132             :      * Since Append is not projection-capable, that might save a separate
    7133             :      * Result node, and it also is important for partitionwise aggregate.
    7134             :      */
    7135      312642 :     if (rel_is_partitioned)
    7136             :     {
    7137        6682 :         List       *live_children = NIL;
    7138             :         int         partition_idx;
    7139             : 
    7140             :         /* Adjust each partition. */
    7141       27230 :         for (partition_idx = 0; partition_idx < rel->nparts; partition_idx++)
    7142             :         {
    7143       20548 :             RelOptInfo *child_rel = rel->part_rels[partition_idx];
    7144             :             AppendRelInfo **appinfos;
    7145             :             int         nappinfos;
    7146       20548 :             List       *child_scanjoin_targets = NIL;
    7147             :             ListCell   *lc;
    7148             : 
    7149             :             /* Pruned or dummy children can be ignored. */
    7150       20548 :             if (child_rel == NULL || IS_DUMMY_REL(child_rel))
    7151        9242 :                 continue;
    7152             : 
    7153             :             /* Translate scan/join targets for this child. */
    7154       11306 :             appinfos = find_appinfos_by_relids(root, child_rel->relids,
    7155             :                                                &nappinfos);
    7156       22612 :             foreach(lc, scanjoin_targets)
    7157             :             {
    7158       11306 :                 PathTarget *target = lfirst_node(PathTarget, lc);
    7159             : 
    7160       11306 :                 target = copy_pathtarget(target);
    7161       11306 :                 target->exprs = (List *)
    7162       22612 :                     adjust_appendrel_attrs(root,
    7163       11306 :                                            (Node *) target->exprs,
    7164             :                                            nappinfos, appinfos);
    7165       11306 :                 child_scanjoin_targets = lappend(child_scanjoin_targets,
    7166             :                                                  target);
    7167             :             }
    7168       11306 :             pfree(appinfos);
    7169             : 
    7170             :             /* Recursion does the real work. */
    7171       11306 :             apply_scanjoin_target_to_paths(root, child_rel,
    7172             :                                            child_scanjoin_targets,
    7173             :                                            scanjoin_targets_contain_srfs,
    7174             :                                            scanjoin_target_parallel_safe,
    7175             :                                            tlist_same_exprs);
    7176             : 
    7177             :             /* Save non-dummy children for Append paths. */
    7178       11306 :             if (!IS_DUMMY_REL(child_rel))
    7179       11306 :                 live_children = lappend(live_children, child_rel);
    7180             :         }
    7181             : 
    7182             :         /* Build new paths for this relation by appending child paths. */
    7183        6682 :         add_paths_to_append_rel(root, rel, live_children);
    7184             :     }
    7185             : 
    7186             :     /*
    7187             :      * Consider generating Gather or Gather Merge paths.  We must only do this
    7188             :      * if the relation is parallel safe, and we don't do it for child rels to
    7189             :      * avoid creating multiple Gather nodes within the same plan. We must do
    7190             :      * this after all paths have been generated and before set_cheapest, since
    7191             :      * one of the generated paths may turn out to be the cheapest one.
    7192             :      */
    7193      312642 :     if (rel->consider_parallel && !IS_OTHER_REL(rel))
    7194       73160 :         generate_gather_paths(root, rel, false);
    7195             : 
    7196             :     /*
    7197             :      * Reassess which paths are the cheapest, now that we've potentially added
    7198             :      * new Gather (or Gather Merge) and/or Append (or MergeAppend) paths to
    7199             :      * this relation.
    7200             :      */
    7201      312642 :     set_cheapest(rel);
    7202      312642 : }
    7203             : 
    7204             : /*
    7205             :  * create_partitionwise_grouping_paths
    7206             :  *
    7207             :  * If the partition keys of input relation are part of the GROUP BY clause, all
    7208             :  * the rows belonging to a given group come from a single partition.  This
    7209             :  * allows aggregation/grouping over a partitioned relation to be broken down
    7210             :  * into aggregation/grouping on each partition.  This should be no worse, and
    7211             :  * often better, than the normal approach.
    7212             :  *
    7213             :  * However, if the GROUP BY clause does not contain all the partition keys,
    7214             :  * rows from a given group may be spread across multiple partitions. In that
    7215             :  * case, we perform partial aggregation for each group, append the results,
    7216             :  * and then finalize aggregation.  This is less certain to win than the
    7217             :  * previous case.  It may win if the PartialAggregate stage greatly reduces
    7218             :  * the number of groups, because fewer rows will pass through the Append node.
    7219             :  * It may lose if we have lots of small groups.
    7220             :  */
    7221             : static void
    7222         346 : create_partitionwise_grouping_paths(PlannerInfo *root,
    7223             :                                     RelOptInfo *input_rel,
    7224             :                                     RelOptInfo *grouped_rel,
    7225             :                                     RelOptInfo *partially_grouped_rel,
    7226             :                                     const AggClauseCosts *agg_costs,
    7227             :                                     grouping_sets_data *gd,
    7228             :                                     PartitionwiseAggregateType patype,
    7229             :                                     GroupPathExtraData *extra)
    7230             : {
    7231         346 :     int         nparts = input_rel->nparts;
    7232             :     int         cnt_parts;
    7233         346 :     List       *grouped_live_children = NIL;
    7234         346 :     List       *partially_grouped_live_children = NIL;
    7235         346 :     PathTarget *target = grouped_rel->reltarget;
    7236         346 :     bool        partial_grouping_valid = true;
    7237             : 
    7238             :     Assert(patype != PARTITIONWISE_AGGREGATE_NONE);
    7239             :     Assert(patype != PARTITIONWISE_AGGREGATE_PARTIAL ||
    7240             :            partially_grouped_rel != NULL);
    7241             : 
    7242             :     /* Add paths for partitionwise aggregation/grouping. */
    7243        1288 :     for (cnt_parts = 0; cnt_parts < nparts; cnt_parts++)
    7244             :     {
    7245         942 :         RelOptInfo *child_input_rel = input_rel->part_rels[cnt_parts];
    7246         942 :         PathTarget *child_target = copy_pathtarget(target);
    7247             :         AppendRelInfo **appinfos;
    7248             :         int         nappinfos;
    7249             :         GroupPathExtraData child_extra;
    7250             :         RelOptInfo *child_grouped_rel;
    7251             :         RelOptInfo *child_partially_grouped_rel;
    7252             : 
    7253             :         /* Pruned or dummy children can be ignored. */
    7254         942 :         if (child_input_rel == NULL || IS_DUMMY_REL(child_input_rel))
    7255           0 :             continue;
    7256             : 
    7257             :         /*
    7258             :          * Copy the given "extra" structure as is and then override the
    7259             :          * members specific to this child.
    7260             :          */
    7261         942 :         memcpy(&child_extra, extra, sizeof(child_extra));
    7262             : 
    7263         942 :         appinfos = find_appinfos_by_relids(root, child_input_rel->relids,
    7264             :                                            &nappinfos);
    7265             : 
    7266         942 :         child_target->exprs = (List *)
    7267        1884 :             adjust_appendrel_attrs(root,
    7268         942 :                                    (Node *) target->exprs,
    7269             :                                    nappinfos, appinfos);
    7270             : 
    7271             :         /* Translate havingQual and targetList. */
    7272         942 :         child_extra.havingQual = (Node *)
    7273             :             adjust_appendrel_attrs(root,
    7274             :                                    extra->havingQual,
    7275             :                                    nappinfos, appinfos);
    7276         942 :         child_extra.targetList = (List *)
    7277        1884 :             adjust_appendrel_attrs(root,
    7278         942 :                                    (Node *) extra->targetList,
    7279             :                                    nappinfos, appinfos);
    7280             : 
    7281             :         /*
    7282             :          * extra->patype was the value computed for our parent rel; patype is
    7283             :          * the value for this relation.  For the child, our value is its
    7284             :          * parent rel's value.
    7285             :          */
    7286         942 :         child_extra.patype = patype;
    7287             : 
    7288             :         /*
    7289             :          * Create grouping relation to hold fully aggregated grouping and/or
    7290             :          * aggregation paths for the child.
    7291             :          */
    7292        1884 :         child_grouped_rel = make_grouping_rel(root, child_input_rel,
    7293             :                                               child_target,
    7294         942 :                                               extra->target_parallel_safe,
    7295             :                                               child_extra.havingQual);
    7296             : 
    7297             :         /* Create grouping paths for this child relation. */
    7298         942 :         create_ordinary_grouping_paths(root, child_input_rel,
    7299             :                                        child_grouped_rel,
    7300             :                                        agg_costs, gd, &child_extra,
    7301             :                                        &child_partially_grouped_rel);
    7302             : 
    7303         942 :         if (child_partially_grouped_rel)
    7304             :         {
    7305         590 :             partially_grouped_live_children =
    7306         590 :                 lappend(partially_grouped_live_children,
    7307             :                         child_partially_grouped_rel);
    7308             :         }
    7309             :         else
    7310         352 :             partial_grouping_valid = false;
    7311             : 
    7312         942 :         if (patype == PARTITIONWISE_AGGREGATE_FULL)
    7313             :         {
    7314         544 :             set_cheapest(child_grouped_rel);
    7315         544 :             grouped_live_children = lappend(grouped_live_children,
    7316             :                                             child_grouped_rel);
    7317             :         }
    7318             : 
    7319         942 :         pfree(appinfos);
    7320             :     }
    7321             : 
    7322             :     /*
    7323             :      * Try to create append paths for partially grouped children. For full
    7324             :      * partitionwise aggregation, we might have paths in the partial_pathlist
    7325             :      * if parallel aggregation is possible.  For partial partitionwise
    7326             :      * aggregation, we may have paths in both pathlist and partial_pathlist.
    7327             :      *
    7328             :      * NB: We must have a partially grouped path for every child in order to
    7329             :      * generate a partially grouped path for this relation.
    7330             :      */
    7331         346 :     if (partially_grouped_rel && partial_grouping_valid)
    7332             :     {
    7333             :         Assert(partially_grouped_live_children != NIL);
    7334             : 
    7335         226 :         add_paths_to_append_rel(root, partially_grouped_rel,
    7336             :                                 partially_grouped_live_children);
    7337             : 
    7338             :         /*
    7339             :          * We need call set_cheapest, since the finalization step will use the
    7340             :          * cheapest path from the rel.
    7341             :          */
    7342         226 :         if (partially_grouped_rel->pathlist)
    7343         226 :             set_cheapest(partially_grouped_rel);
    7344             :     }
    7345             : 
    7346             :     /* If possible, create append paths for fully grouped children. */
    7347         346 :     if (patype == PARTITIONWISE_AGGREGATE_FULL)
    7348             :     {
    7349             :         Assert(grouped_live_children != NIL);
    7350             : 
    7351         192 :         add_paths_to_append_rel(root, grouped_rel, grouped_live_children);
    7352             :     }
    7353         346 : }
    7354             : 
    7355             : /*
    7356             :  * group_by_has_partkey
    7357             :  *
    7358             :  * Returns true, if all the partition keys of the given relation are part of
    7359             :  * the GROUP BY clauses, false otherwise.
    7360             :  */
    7361             : static bool
    7362         342 : group_by_has_partkey(RelOptInfo *input_rel,
    7363             :                      List *targetList,
    7364             :                      List *groupClause)
    7365             : {
    7366         342 :     List       *groupexprs = get_sortgrouplist_exprs(groupClause, targetList);
    7367         342 :     int         cnt = 0;
    7368             :     int         partnatts;
    7369             : 
    7370             :     /* Input relation should be partitioned. */
    7371             :     Assert(input_rel->part_scheme);
    7372             : 
    7373             :     /* Rule out early, if there are no partition keys present. */
    7374         342 :     if (!input_rel->partexprs)
    7375           0 :         return false;
    7376             : 
    7377         342 :     partnatts = input_rel->part_scheme->partnatts;
    7378             : 
    7379         558 :     for (cnt = 0; cnt < partnatts; cnt++)
    7380             :     {
    7381         366 :         List       *partexprs = input_rel->partexprs[cnt];
    7382             :         ListCell   *lc;
    7383         366 :         bool        found = false;
    7384             : 
    7385         512 :         foreach(lc, partexprs)
    7386             :         {
    7387         362 :             Expr       *partexpr = lfirst(lc);
    7388             : 
    7389         362 :             if (list_member(groupexprs, partexpr))
    7390             :             {
    7391         216 :                 found = true;
    7392         216 :                 break;
    7393             :             }
    7394             :         }
    7395             : 
    7396             :         /*
    7397             :          * If none of the partition key expressions match with any of the
    7398             :          * GROUP BY expression, return false.
    7399             :          */
    7400         366 :         if (!found)
    7401         150 :             return false;
    7402             :     }
    7403             : 
    7404         192 :     return true;
    7405             : }

Generated by: LCOV version 1.13