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

Generated by: LCOV version 1.13