LCOV - code coverage report
Current view: top level - src/backend/optimizer/plan - planner.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12devel Lines: 1964 2026 96.9 %
Date: 2019-04-23 21:21:41 Functions: 52 52 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13