LCOV - code coverage report
Current view: top level - src/backend/optimizer/plan - createplan.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 2281 2382 95.8 %
Date: 2025-07-04 00:16:42 Functions: 114 115 99.1 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * createplan.c
       4             :  *    Routines to create the desired plan for processing a query.
       5             :  *    Planning is complete, we just need to convert the selected
       6             :  *    Path into a Plan.
       7             :  *
       8             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
       9             :  * Portions Copyright (c) 1994, Regents of the University of California
      10             :  *
      11             :  *
      12             :  * IDENTIFICATION
      13             :  *    src/backend/optimizer/plan/createplan.c
      14             :  *
      15             :  *-------------------------------------------------------------------------
      16             :  */
      17             : #include "postgres.h"
      18             : 
      19             : #include <math.h>
      20             : 
      21             : #include "access/sysattr.h"
      22             : #include "catalog/pg_class.h"
      23             : #include "foreign/fdwapi.h"
      24             : #include "miscadmin.h"
      25             : #include "nodes/extensible.h"
      26             : #include "nodes/makefuncs.h"
      27             : #include "nodes/nodeFuncs.h"
      28             : #include "optimizer/clauses.h"
      29             : #include "optimizer/cost.h"
      30             : #include "optimizer/optimizer.h"
      31             : #include "optimizer/paramassign.h"
      32             : #include "optimizer/pathnode.h"
      33             : #include "optimizer/paths.h"
      34             : #include "optimizer/placeholder.h"
      35             : #include "optimizer/plancat.h"
      36             : #include "optimizer/planmain.h"
      37             : #include "optimizer/prep.h"
      38             : #include "optimizer/restrictinfo.h"
      39             : #include "optimizer/subselect.h"
      40             : #include "optimizer/tlist.h"
      41             : #include "parser/parse_clause.h"
      42             : #include "parser/parsetree.h"
      43             : #include "partitioning/partprune.h"
      44             : #include "tcop/tcopprot.h"
      45             : #include "utils/lsyscache.h"
      46             : 
      47             : 
      48             : /*
      49             :  * Flag bits that can appear in the flags argument of create_plan_recurse().
      50             :  * These can be OR-ed together.
      51             :  *
      52             :  * CP_EXACT_TLIST specifies that the generated plan node must return exactly
      53             :  * the tlist specified by the path's pathtarget (this overrides both
      54             :  * CP_SMALL_TLIST and CP_LABEL_TLIST, if those are set).  Otherwise, the
      55             :  * plan node is allowed to return just the Vars and PlaceHolderVars needed
      56             :  * to evaluate the pathtarget.
      57             :  *
      58             :  * CP_SMALL_TLIST specifies that a narrower tlist is preferred.  This is
      59             :  * passed down by parent nodes such as Sort and Hash, which will have to
      60             :  * store the returned tuples.
      61             :  *
      62             :  * CP_LABEL_TLIST specifies that the plan node must return columns matching
      63             :  * any sortgrouprefs specified in its pathtarget, with appropriate
      64             :  * ressortgroupref labels.  This is passed down by parent nodes such as Sort
      65             :  * and Group, which need these values to be available in their inputs.
      66             :  *
      67             :  * CP_IGNORE_TLIST specifies that the caller plans to replace the targetlist,
      68             :  * and therefore it doesn't matter a bit what target list gets generated.
      69             :  */
      70             : #define CP_EXACT_TLIST      0x0001  /* Plan must return specified tlist */
      71             : #define CP_SMALL_TLIST      0x0002  /* Prefer narrower tlists */
      72             : #define CP_LABEL_TLIST      0x0004  /* tlist must contain sortgrouprefs */
      73             : #define CP_IGNORE_TLIST     0x0008  /* caller will replace tlist */
      74             : 
      75             : 
      76             : static Plan *create_plan_recurse(PlannerInfo *root, Path *best_path,
      77             :                                  int flags);
      78             : static Plan *create_scan_plan(PlannerInfo *root, Path *best_path,
      79             :                               int flags);
      80             : static List *build_path_tlist(PlannerInfo *root, Path *path);
      81             : static bool use_physical_tlist(PlannerInfo *root, Path *path, int flags);
      82             : static List *get_gating_quals(PlannerInfo *root, List *quals);
      83             : static Plan *create_gating_plan(PlannerInfo *root, Path *path, Plan *plan,
      84             :                                 List *gating_quals);
      85             : static Plan *create_join_plan(PlannerInfo *root, JoinPath *best_path);
      86             : static bool mark_async_capable_plan(Plan *plan, Path *path);
      87             : static Plan *create_append_plan(PlannerInfo *root, AppendPath *best_path,
      88             :                                 int flags);
      89             : static Plan *create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path,
      90             :                                       int flags);
      91             : static Result *create_group_result_plan(PlannerInfo *root,
      92             :                                         GroupResultPath *best_path);
      93             : static ProjectSet *create_project_set_plan(PlannerInfo *root, ProjectSetPath *best_path);
      94             : static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path,
      95             :                                       int flags);
      96             : static Memoize *create_memoize_plan(PlannerInfo *root, MemoizePath *best_path,
      97             :                                     int flags);
      98             : static Plan *create_unique_plan(PlannerInfo *root, UniquePath *best_path,
      99             :                                 int flags);
     100             : static Gather *create_gather_plan(PlannerInfo *root, GatherPath *best_path);
     101             : static Plan *create_projection_plan(PlannerInfo *root,
     102             :                                     ProjectionPath *best_path,
     103             :                                     int flags);
     104             : static Plan *inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe);
     105             : static Sort *create_sort_plan(PlannerInfo *root, SortPath *best_path, int flags);
     106             : static IncrementalSort *create_incrementalsort_plan(PlannerInfo *root,
     107             :                                                     IncrementalSortPath *best_path, int flags);
     108             : static Group *create_group_plan(PlannerInfo *root, GroupPath *best_path);
     109             : static Unique *create_upper_unique_plan(PlannerInfo *root, UpperUniquePath *best_path,
     110             :                                         int flags);
     111             : static Agg *create_agg_plan(PlannerInfo *root, AggPath *best_path);
     112             : static Plan *create_groupingsets_plan(PlannerInfo *root, GroupingSetsPath *best_path);
     113             : static Result *create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path);
     114             : static WindowAgg *create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path);
     115             : static SetOp *create_setop_plan(PlannerInfo *root, SetOpPath *best_path,
     116             :                                 int flags);
     117             : static RecursiveUnion *create_recursiveunion_plan(PlannerInfo *root, RecursiveUnionPath *best_path);
     118             : static LockRows *create_lockrows_plan(PlannerInfo *root, LockRowsPath *best_path,
     119             :                                       int flags);
     120             : static ModifyTable *create_modifytable_plan(PlannerInfo *root, ModifyTablePath *best_path);
     121             : static Limit *create_limit_plan(PlannerInfo *root, LimitPath *best_path,
     122             :                                 int flags);
     123             : static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path,
     124             :                                     List *tlist, List *scan_clauses);
     125             : static SampleScan *create_samplescan_plan(PlannerInfo *root, Path *best_path,
     126             :                                           List *tlist, List *scan_clauses);
     127             : static Scan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path,
     128             :                                    List *tlist, List *scan_clauses, bool indexonly);
     129             : static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
     130             :                                                BitmapHeapPath *best_path,
     131             :                                                List *tlist, List *scan_clauses);
     132             : static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
     133             :                                    List **qual, List **indexqual, List **indexECs);
     134             : static void bitmap_subplan_mark_shared(Plan *plan);
     135             : static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
     136             :                                     List *tlist, List *scan_clauses);
     137             : static TidRangeScan *create_tidrangescan_plan(PlannerInfo *root,
     138             :                                               TidRangePath *best_path,
     139             :                                               List *tlist,
     140             :                                               List *scan_clauses);
     141             : static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root,
     142             :                                               SubqueryScanPath *best_path,
     143             :                                               List *tlist, List *scan_clauses);
     144             : static FunctionScan *create_functionscan_plan(PlannerInfo *root, Path *best_path,
     145             :                                               List *tlist, List *scan_clauses);
     146             : static ValuesScan *create_valuesscan_plan(PlannerInfo *root, Path *best_path,
     147             :                                           List *tlist, List *scan_clauses);
     148             : static TableFuncScan *create_tablefuncscan_plan(PlannerInfo *root, Path *best_path,
     149             :                                                 List *tlist, List *scan_clauses);
     150             : static CteScan *create_ctescan_plan(PlannerInfo *root, Path *best_path,
     151             :                                     List *tlist, List *scan_clauses);
     152             : static NamedTuplestoreScan *create_namedtuplestorescan_plan(PlannerInfo *root,
     153             :                                                             Path *best_path, List *tlist, List *scan_clauses);
     154             : static Result *create_resultscan_plan(PlannerInfo *root, Path *best_path,
     155             :                                       List *tlist, List *scan_clauses);
     156             : static WorkTableScan *create_worktablescan_plan(PlannerInfo *root, Path *best_path,
     157             :                                                 List *tlist, List *scan_clauses);
     158             : static ForeignScan *create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
     159             :                                             List *tlist, List *scan_clauses);
     160             : static CustomScan *create_customscan_plan(PlannerInfo *root,
     161             :                                           CustomPath *best_path,
     162             :                                           List *tlist, List *scan_clauses);
     163             : static NestLoop *create_nestloop_plan(PlannerInfo *root, NestPath *best_path);
     164             : static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path);
     165             : static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path);
     166             : static Node *replace_nestloop_params(PlannerInfo *root, Node *expr);
     167             : static Node *replace_nestloop_params_mutator(Node *node, PlannerInfo *root);
     168             : static void fix_indexqual_references(PlannerInfo *root, IndexPath *index_path,
     169             :                                      List **stripped_indexquals_p,
     170             :                                      List **fixed_indexquals_p);
     171             : static List *fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path);
     172             : static Node *fix_indexqual_clause(PlannerInfo *root,
     173             :                                   IndexOptInfo *index, int indexcol,
     174             :                                   Node *clause, List *indexcolnos);
     175             : static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol);
     176             : static List *get_switched_clauses(List *clauses, Relids outerrelids);
     177             : static List *order_qual_clauses(PlannerInfo *root, List *clauses);
     178             : static void copy_generic_path_info(Plan *dest, Path *src);
     179             : static void copy_plan_costsize(Plan *dest, Plan *src);
     180             : static void label_sort_with_costsize(PlannerInfo *root, Sort *plan,
     181             :                                      double limit_tuples);
     182             : static void label_incrementalsort_with_costsize(PlannerInfo *root, IncrementalSort *plan,
     183             :                                                 List *pathkeys, double limit_tuples);
     184             : static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
     185             : static SampleScan *make_samplescan(List *qptlist, List *qpqual, Index scanrelid,
     186             :                                    TableSampleClause *tsc);
     187             : static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
     188             :                                  Oid indexid, List *indexqual, List *indexqualorig,
     189             :                                  List *indexorderby, List *indexorderbyorig,
     190             :                                  List *indexorderbyops,
     191             :                                  ScanDirection indexscandir);
     192             : static IndexOnlyScan *make_indexonlyscan(List *qptlist, List *qpqual,
     193             :                                          Index scanrelid, Oid indexid,
     194             :                                          List *indexqual, List *recheckqual,
     195             :                                          List *indexorderby,
     196             :                                          List *indextlist,
     197             :                                          ScanDirection indexscandir);
     198             : static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid,
     199             :                                               List *indexqual,
     200             :                                               List *indexqualorig);
     201             : static BitmapHeapScan *make_bitmap_heapscan(List *qptlist,
     202             :                                             List *qpqual,
     203             :                                             Plan *lefttree,
     204             :                                             List *bitmapqualorig,
     205             :                                             Index scanrelid);
     206             : static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
     207             :                              List *tidquals);
     208             : static TidRangeScan *make_tidrangescan(List *qptlist, List *qpqual,
     209             :                                        Index scanrelid, List *tidrangequals);
     210             : static SubqueryScan *make_subqueryscan(List *qptlist,
     211             :                                        List *qpqual,
     212             :                                        Index scanrelid,
     213             :                                        Plan *subplan);
     214             : static FunctionScan *make_functionscan(List *qptlist, List *qpqual,
     215             :                                        Index scanrelid, List *functions, bool funcordinality);
     216             : static ValuesScan *make_valuesscan(List *qptlist, List *qpqual,
     217             :                                    Index scanrelid, List *values_lists);
     218             : static TableFuncScan *make_tablefuncscan(List *qptlist, List *qpqual,
     219             :                                          Index scanrelid, TableFunc *tablefunc);
     220             : static CteScan *make_ctescan(List *qptlist, List *qpqual,
     221             :                              Index scanrelid, int ctePlanId, int cteParam);
     222             : static NamedTuplestoreScan *make_namedtuplestorescan(List *qptlist, List *qpqual,
     223             :                                                      Index scanrelid, char *enrname);
     224             : static WorkTableScan *make_worktablescan(List *qptlist, List *qpqual,
     225             :                                          Index scanrelid, int wtParam);
     226             : static RecursiveUnion *make_recursive_union(List *tlist,
     227             :                                             Plan *lefttree,
     228             :                                             Plan *righttree,
     229             :                                             int wtParam,
     230             :                                             List *distinctList,
     231             :                                             long numGroups);
     232             : static BitmapAnd *make_bitmap_and(List *bitmapplans);
     233             : static BitmapOr *make_bitmap_or(List *bitmapplans);
     234             : static NestLoop *make_nestloop(List *tlist,
     235             :                                List *joinclauses, List *otherclauses, List *nestParams,
     236             :                                Plan *lefttree, Plan *righttree,
     237             :                                JoinType jointype, bool inner_unique);
     238             : static HashJoin *make_hashjoin(List *tlist,
     239             :                                List *joinclauses, List *otherclauses,
     240             :                                List *hashclauses,
     241             :                                List *hashoperators, List *hashcollations,
     242             :                                List *hashkeys,
     243             :                                Plan *lefttree, Plan *righttree,
     244             :                                JoinType jointype, bool inner_unique);
     245             : static Hash *make_hash(Plan *lefttree,
     246             :                        List *hashkeys,
     247             :                        Oid skewTable,
     248             :                        AttrNumber skewColumn,
     249             :                        bool skewInherit);
     250             : static MergeJoin *make_mergejoin(List *tlist,
     251             :                                  List *joinclauses, List *otherclauses,
     252             :                                  List *mergeclauses,
     253             :                                  Oid *mergefamilies,
     254             :                                  Oid *mergecollations,
     255             :                                  bool *mergereversals,
     256             :                                  bool *mergenullsfirst,
     257             :                                  Plan *lefttree, Plan *righttree,
     258             :                                  JoinType jointype, bool inner_unique,
     259             :                                  bool skip_mark_restore);
     260             : static Sort *make_sort(Plan *lefttree, int numCols,
     261             :                        AttrNumber *sortColIdx, Oid *sortOperators,
     262             :                        Oid *collations, bool *nullsFirst);
     263             : static IncrementalSort *make_incrementalsort(Plan *lefttree,
     264             :                                              int numCols, int nPresortedCols,
     265             :                                              AttrNumber *sortColIdx, Oid *sortOperators,
     266             :                                              Oid *collations, bool *nullsFirst);
     267             : static Plan *prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
     268             :                                         Relids relids,
     269             :                                         const AttrNumber *reqColIdx,
     270             :                                         bool adjust_tlist_in_place,
     271             :                                         int *p_numsortkeys,
     272             :                                         AttrNumber **p_sortColIdx,
     273             :                                         Oid **p_sortOperators,
     274             :                                         Oid **p_collations,
     275             :                                         bool **p_nullsFirst);
     276             : static Sort *make_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
     277             :                                      Relids relids);
     278             : static IncrementalSort *make_incrementalsort_from_pathkeys(Plan *lefttree,
     279             :                                                            List *pathkeys, Relids relids, int nPresortedCols);
     280             : static Sort *make_sort_from_groupcols(List *groupcls,
     281             :                                       AttrNumber *grpColIdx,
     282             :                                       Plan *lefttree);
     283             : static Material *make_material(Plan *lefttree);
     284             : static Memoize *make_memoize(Plan *lefttree, Oid *hashoperators,
     285             :                              Oid *collations, List *param_exprs,
     286             :                              bool singlerow, bool binary_mode,
     287             :                              uint32 est_entries, Bitmapset *keyparamids);
     288             : static WindowAgg *make_windowagg(List *tlist, WindowClause *wc,
     289             :                                  int partNumCols, AttrNumber *partColIdx, Oid *partOperators, Oid *partCollations,
     290             :                                  int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators, Oid *ordCollations,
     291             :                                  List *runCondition, List *qual, bool topWindow,
     292             :                                  Plan *lefttree);
     293             : static Group *make_group(List *tlist, List *qual, int numGroupCols,
     294             :                          AttrNumber *grpColIdx, Oid *grpOperators, Oid *grpCollations,
     295             :                          Plan *lefttree);
     296             : static Unique *make_unique_from_sortclauses(Plan *lefttree, List *distinctList);
     297             : static Unique *make_unique_from_pathkeys(Plan *lefttree,
     298             :                                          List *pathkeys, int numCols);
     299             : static Gather *make_gather(List *qptlist, List *qpqual,
     300             :                            int nworkers, int rescan_param, bool single_copy, Plan *subplan);
     301             : static SetOp *make_setop(SetOpCmd cmd, SetOpStrategy strategy,
     302             :                          List *tlist, Plan *lefttree, Plan *righttree,
     303             :                          List *groupList, long numGroups);
     304             : static LockRows *make_lockrows(Plan *lefttree, List *rowMarks, int epqParam);
     305             : static Result *make_result(List *tlist, Node *resconstantqual, Plan *subplan);
     306             : static ProjectSet *make_project_set(List *tlist, Plan *subplan);
     307             : static ModifyTable *make_modifytable(PlannerInfo *root, Plan *subplan,
     308             :                                      CmdType operation, bool canSetTag,
     309             :                                      Index nominalRelation, Index rootRelation,
     310             :                                      bool partColsUpdated,
     311             :                                      List *resultRelations,
     312             :                                      List *updateColnosLists,
     313             :                                      List *withCheckOptionLists, List *returningLists,
     314             :                                      List *rowMarks, OnConflictExpr *onconflict,
     315             :                                      List *mergeActionLists, List *mergeJoinConditions,
     316             :                                      int epqParam);
     317             : static GatherMerge *create_gather_merge_plan(PlannerInfo *root,
     318             :                                              GatherMergePath *best_path);
     319             : 
     320             : 
     321             : /*
     322             :  * create_plan
     323             :  *    Creates the access plan for a query by recursively processing the
     324             :  *    desired tree of pathnodes, starting at the node 'best_path'.  For
     325             :  *    every pathnode found, we create a corresponding plan node containing
     326             :  *    appropriate id, target list, and qualification information.
     327             :  *
     328             :  *    The tlists and quals in the plan tree are still in planner format,
     329             :  *    ie, Vars still correspond to the parser's numbering.  This will be
     330             :  *    fixed later by setrefs.c.
     331             :  *
     332             :  *    best_path is the best access path
     333             :  *
     334             :  *    Returns a Plan tree.
     335             :  */
     336             : Plan *
     337      524758 : create_plan(PlannerInfo *root, Path *best_path)
     338             : {
     339             :     Plan       *plan;
     340             : 
     341             :     /* plan_params should not be in use in current query level */
     342             :     Assert(root->plan_params == NIL);
     343             : 
     344             :     /* Initialize this module's workspace in PlannerInfo */
     345      524758 :     root->curOuterRels = NULL;
     346      524758 :     root->curOuterParams = NIL;
     347             : 
     348             :     /* Recursively process the path tree, demanding the correct tlist result */
     349      524758 :     plan = create_plan_recurse(root, best_path, CP_EXACT_TLIST);
     350             : 
     351             :     /*
     352             :      * Make sure the topmost plan node's targetlist exposes the original
     353             :      * column names and other decorative info.  Targetlists generated within
     354             :      * the planner don't bother with that stuff, but we must have it on the
     355             :      * top-level tlist seen at execution time.  However, ModifyTable plan
     356             :      * nodes don't have a tlist matching the querytree targetlist.
     357             :      */
     358      524362 :     if (!IsA(plan, ModifyTable))
     359      435730 :         apply_tlist_labeling(plan->targetlist, root->processed_tlist);
     360             : 
     361             :     /*
     362             :      * Attach any initPlans created in this query level to the topmost plan
     363             :      * node.  (In principle the initplans could go in any plan node at or
     364             :      * above where they're referenced, but there seems no reason to put them
     365             :      * any lower than the topmost node for the query level.  Also, see
     366             :      * comments for SS_finalize_plan before you try to change this.)
     367             :      */
     368      524362 :     SS_attach_initplans(root, plan);
     369             : 
     370             :     /* Check we successfully assigned all NestLoopParams to plan nodes */
     371      524362 :     if (root->curOuterParams != NIL)
     372           0 :         elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
     373             : 
     374             :     /*
     375             :      * Reset plan_params to ensure param IDs used for nestloop params are not
     376             :      * re-used later
     377             :      */
     378      524362 :     root->plan_params = NIL;
     379             : 
     380      524362 :     return plan;
     381             : }
     382             : 
     383             : /*
     384             :  * create_plan_recurse
     385             :  *    Recursive guts of create_plan().
     386             :  */
     387             : static Plan *
     388     1435240 : create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
     389             : {
     390             :     Plan       *plan;
     391             : 
     392             :     /* Guard against stack overflow due to overly complex plans */
     393     1435240 :     check_stack_depth();
     394             : 
     395     1435240 :     switch (best_path->pathtype)
     396             :     {
     397      495254 :         case T_SeqScan:
     398             :         case T_SampleScan:
     399             :         case T_IndexScan:
     400             :         case T_IndexOnlyScan:
     401             :         case T_BitmapHeapScan:
     402             :         case T_TidScan:
     403             :         case T_TidRangeScan:
     404             :         case T_SubqueryScan:
     405             :         case T_FunctionScan:
     406             :         case T_TableFuncScan:
     407             :         case T_ValuesScan:
     408             :         case T_CteScan:
     409             :         case T_WorkTableScan:
     410             :         case T_NamedTuplestoreScan:
     411             :         case T_ForeignScan:
     412             :         case T_CustomScan:
     413      495254 :             plan = create_scan_plan(root, best_path, flags);
     414      495254 :             break;
     415      135770 :         case T_HashJoin:
     416             :         case T_MergeJoin:
     417             :         case T_NestLoop:
     418      135770 :             plan = create_join_plan(root,
     419             :                                     (JoinPath *) best_path);
     420      135770 :             break;
     421       24296 :         case T_Append:
     422       24296 :             plan = create_append_plan(root,
     423             :                                       (AppendPath *) best_path,
     424             :                                       flags);
     425       24296 :             break;
     426         530 :         case T_MergeAppend:
     427         530 :             plan = create_merge_append_plan(root,
     428             :                                             (MergeAppendPath *) best_path,
     429             :                                             flags);
     430         530 :             break;
     431      535560 :         case T_Result:
     432      535560 :             if (IsA(best_path, ProjectionPath))
     433             :             {
     434      338220 :                 plan = create_projection_plan(root,
     435             :                                               (ProjectionPath *) best_path,
     436             :                                               flags);
     437             :             }
     438      197340 :             else if (IsA(best_path, MinMaxAggPath))
     439             :             {
     440         364 :                 plan = (Plan *) create_minmaxagg_plan(root,
     441             :                                                       (MinMaxAggPath *) best_path);
     442             :             }
     443      196976 :             else if (IsA(best_path, GroupResultPath))
     444             :             {
     445      192890 :                 plan = (Plan *) create_group_result_plan(root,
     446             :                                                          (GroupResultPath *) best_path);
     447             :             }
     448             :             else
     449             :             {
     450             :                 /* Simple RTE_RESULT base relation */
     451             :                 Assert(IsA(best_path, Path));
     452        4086 :                 plan = create_scan_plan(root, best_path, flags);
     453             :             }
     454      535560 :             break;
     455       12050 :         case T_ProjectSet:
     456       12050 :             plan = (Plan *) create_project_set_plan(root,
     457             :                                                     (ProjectSetPath *) best_path);
     458       12050 :             break;
     459        4650 :         case T_Material:
     460        4650 :             plan = (Plan *) create_material_plan(root,
     461             :                                                  (MaterialPath *) best_path,
     462             :                                                  flags);
     463        4650 :             break;
     464        1914 :         case T_Memoize:
     465        1914 :             plan = (Plan *) create_memoize_plan(root,
     466             :                                                 (MemoizePath *) best_path,
     467             :                                                 flags);
     468        1914 :             break;
     469        6166 :         case T_Unique:
     470        6166 :             if (IsA(best_path, UpperUniquePath))
     471             :             {
     472        5538 :                 plan = (Plan *) create_upper_unique_plan(root,
     473             :                                                          (UpperUniquePath *) best_path,
     474             :                                                          flags);
     475             :             }
     476             :             else
     477             :             {
     478             :                 Assert(IsA(best_path, UniquePath));
     479         628 :                 plan = create_unique_plan(root,
     480             :                                           (UniquePath *) best_path,
     481             :                                           flags);
     482             :             }
     483        6166 :             break;
     484         950 :         case T_Gather:
     485         950 :             plan = (Plan *) create_gather_plan(root,
     486             :                                                (GatherPath *) best_path);
     487         950 :             break;
     488       70230 :         case T_Sort:
     489       70230 :             plan = (Plan *) create_sort_plan(root,
     490             :                                              (SortPath *) best_path,
     491             :                                              flags);
     492       70230 :             break;
     493         968 :         case T_IncrementalSort:
     494         968 :             plan = (Plan *) create_incrementalsort_plan(root,
     495             :                                                         (IncrementalSortPath *) best_path,
     496             :                                                         flags);
     497         968 :             break;
     498         246 :         case T_Group:
     499         246 :             plan = (Plan *) create_group_plan(root,
     500             :                                               (GroupPath *) best_path);
     501         246 :             break;
     502       40940 :         case T_Agg:
     503       40940 :             if (IsA(best_path, GroupingSetsPath))
     504         860 :                 plan = create_groupingsets_plan(root,
     505             :                                                 (GroupingSetsPath *) best_path);
     506             :             else
     507             :             {
     508             :                 Assert(IsA(best_path, AggPath));
     509       40080 :                 plan = (Plan *) create_agg_plan(root,
     510             :                                                 (AggPath *) best_path);
     511             :             }
     512       40940 :             break;
     513        2546 :         case T_WindowAgg:
     514        2546 :             plan = (Plan *) create_windowagg_plan(root,
     515             :                                                   (WindowAggPath *) best_path);
     516        2546 :             break;
     517         662 :         case T_SetOp:
     518         662 :             plan = (Plan *) create_setop_plan(root,
     519             :                                               (SetOpPath *) best_path,
     520             :                                               flags);
     521         662 :             break;
     522        1004 :         case T_RecursiveUnion:
     523        1004 :             plan = (Plan *) create_recursiveunion_plan(root,
     524             :                                                        (RecursiveUnionPath *) best_path);
     525        1004 :             break;
     526        7744 :         case T_LockRows:
     527        7744 :             plan = (Plan *) create_lockrows_plan(root,
     528             :                                                  (LockRowsPath *) best_path,
     529             :                                                  flags);
     530        7744 :             break;
     531       89028 :         case T_ModifyTable:
     532       89028 :             plan = (Plan *) create_modifytable_plan(root,
     533             :                                                     (ModifyTablePath *) best_path);
     534       88632 :             break;
     535        4402 :         case T_Limit:
     536        4402 :             plan = (Plan *) create_limit_plan(root,
     537             :                                               (LimitPath *) best_path,
     538             :                                               flags);
     539        4402 :             break;
     540         330 :         case T_GatherMerge:
     541         330 :             plan = (Plan *) create_gather_merge_plan(root,
     542             :                                                      (GatherMergePath *) best_path);
     543         330 :             break;
     544           0 :         default:
     545           0 :             elog(ERROR, "unrecognized node type: %d",
     546             :                  (int) best_path->pathtype);
     547             :             plan = NULL;        /* keep compiler quiet */
     548             :             break;
     549             :     }
     550             : 
     551     1434844 :     return plan;
     552             : }
     553             : 
     554             : /*
     555             :  * create_scan_plan
     556             :  *   Create a scan plan for the parent relation of 'best_path'.
     557             :  */
     558             : static Plan *
     559      499340 : create_scan_plan(PlannerInfo *root, Path *best_path, int flags)
     560             : {
     561      499340 :     RelOptInfo *rel = best_path->parent;
     562             :     List       *scan_clauses;
     563             :     List       *gating_clauses;
     564             :     List       *tlist;
     565             :     Plan       *plan;
     566             : 
     567             :     /*
     568             :      * Extract the relevant restriction clauses from the parent relation. The
     569             :      * executor must apply all these restrictions during the scan, except for
     570             :      * pseudoconstants which we'll take care of below.
     571             :      *
     572             :      * If this is a plain indexscan or index-only scan, we need not consider
     573             :      * restriction clauses that are implied by the index's predicate, so use
     574             :      * indrestrictinfo not baserestrictinfo.  Note that we can't do that for
     575             :      * bitmap indexscans, since there's not necessarily a single index
     576             :      * involved; but it doesn't matter since create_bitmap_scan_plan() will be
     577             :      * able to get rid of such clauses anyway via predicate proof.
     578             :      */
     579      499340 :     switch (best_path->pathtype)
     580             :     {
     581      159488 :         case T_IndexScan:
     582             :         case T_IndexOnlyScan:
     583      159488 :             scan_clauses = castNode(IndexPath, best_path)->indexinfo->indrestrictinfo;
     584      159488 :             break;
     585      339852 :         default:
     586      339852 :             scan_clauses = rel->baserestrictinfo;
     587      339852 :             break;
     588             :     }
     589             : 
     590             :     /*
     591             :      * If this is a parameterized scan, we also need to enforce all the join
     592             :      * clauses available from the outer relation(s).
     593             :      *
     594             :      * For paranoia's sake, don't modify the stored baserestrictinfo list.
     595             :      */
     596      499340 :     if (best_path->param_info)
     597       47936 :         scan_clauses = list_concat_copy(scan_clauses,
     598       47936 :                                         best_path->param_info->ppi_clauses);
     599             : 
     600             :     /*
     601             :      * Detect whether we have any pseudoconstant quals to deal with.  Then, if
     602             :      * we'll need a gating Result node, it will be able to project, so there
     603             :      * are no requirements on the child's tlist.
     604             :      *
     605             :      * If this replaces a join, it must be a foreign scan or a custom scan,
     606             :      * and the FDW or the custom scan provider would have stored in the best
     607             :      * path the list of RestrictInfo nodes to apply to the join; check against
     608             :      * that list in that case.
     609             :      */
     610      499340 :     if (IS_JOIN_REL(rel))
     611         310 :     {
     612             :         List       *join_clauses;
     613             : 
     614             :         Assert(best_path->pathtype == T_ForeignScan ||
     615             :                best_path->pathtype == T_CustomScan);
     616         310 :         if (best_path->pathtype == T_ForeignScan)
     617         310 :             join_clauses = ((ForeignPath *) best_path)->fdw_restrictinfo;
     618             :         else
     619           0 :             join_clauses = ((CustomPath *) best_path)->custom_restrictinfo;
     620             : 
     621         310 :         gating_clauses = get_gating_quals(root, join_clauses);
     622             :     }
     623             :     else
     624      499030 :         gating_clauses = get_gating_quals(root, scan_clauses);
     625      499340 :     if (gating_clauses)
     626        6700 :         flags = 0;
     627             : 
     628             :     /*
     629             :      * For table scans, rather than using the relation targetlist (which is
     630             :      * only those Vars actually needed by the query), we prefer to generate a
     631             :      * tlist containing all Vars in order.  This will allow the executor to
     632             :      * optimize away projection of the table tuples, if possible.
     633             :      *
     634             :      * But if the caller is going to ignore our tlist anyway, then don't
     635             :      * bother generating one at all.  We use an exact equality test here, so
     636             :      * that this only applies when CP_IGNORE_TLIST is the only flag set.
     637             :      */
     638      499340 :     if (flags == CP_IGNORE_TLIST)
     639             :     {
     640       79082 :         tlist = NULL;
     641             :     }
     642      420258 :     else if (use_physical_tlist(root, best_path, flags))
     643             :     {
     644      193644 :         if (best_path->pathtype == T_IndexOnlyScan)
     645             :         {
     646             :             /* For index-only scan, the preferred tlist is the index's */
     647        8466 :             tlist = copyObject(((IndexPath *) best_path)->indexinfo->indextlist);
     648             : 
     649             :             /*
     650             :              * Transfer sortgroupref data to the replacement tlist, if
     651             :              * requested (use_physical_tlist checked that this will work).
     652             :              */
     653        8466 :             if (flags & CP_LABEL_TLIST)
     654        1920 :                 apply_pathtarget_labeling_to_tlist(tlist, best_path->pathtarget);
     655             :         }
     656             :         else
     657             :         {
     658      185178 :             tlist = build_physical_tlist(root, rel);
     659      185178 :             if (tlist == NIL)
     660             :             {
     661             :                 /* Failed because of dropped cols, so use regular method */
     662         160 :                 tlist = build_path_tlist(root, best_path);
     663             :             }
     664             :             else
     665             :             {
     666             :                 /* As above, transfer sortgroupref data to replacement tlist */
     667      185018 :                 if (flags & CP_LABEL_TLIST)
     668       13554 :                     apply_pathtarget_labeling_to_tlist(tlist, best_path->pathtarget);
     669             :             }
     670             :         }
     671             :     }
     672             :     else
     673             :     {
     674      226614 :         tlist = build_path_tlist(root, best_path);
     675             :     }
     676             : 
     677      499340 :     switch (best_path->pathtype)
     678             :     {
     679      216142 :         case T_SeqScan:
     680      216142 :             plan = (Plan *) create_seqscan_plan(root,
     681             :                                                 best_path,
     682             :                                                 tlist,
     683             :                                                 scan_clauses);
     684      216142 :             break;
     685             : 
     686         306 :         case T_SampleScan:
     687         306 :             plan = (Plan *) create_samplescan_plan(root,
     688             :                                                    best_path,
     689             :                                                    tlist,
     690             :                                                    scan_clauses);
     691         306 :             break;
     692             : 
     693      143140 :         case T_IndexScan:
     694      143140 :             plan = (Plan *) create_indexscan_plan(root,
     695             :                                                   (IndexPath *) best_path,
     696             :                                                   tlist,
     697             :                                                   scan_clauses,
     698             :                                                   false);
     699      143140 :             break;
     700             : 
     701       16348 :         case T_IndexOnlyScan:
     702       16348 :             plan = (Plan *) create_indexscan_plan(root,
     703             :                                                   (IndexPath *) best_path,
     704             :                                                   tlist,
     705             :                                                   scan_clauses,
     706             :                                                   true);
     707       16348 :             break;
     708             : 
     709       20656 :         case T_BitmapHeapScan:
     710       20656 :             plan = (Plan *) create_bitmap_scan_plan(root,
     711             :                                                     (BitmapHeapPath *) best_path,
     712             :                                                     tlist,
     713             :                                                     scan_clauses);
     714       20656 :             break;
     715             : 
     716         732 :         case T_TidScan:
     717         732 :             plan = (Plan *) create_tidscan_plan(root,
     718             :                                                 (TidPath *) best_path,
     719             :                                                 tlist,
     720             :                                                 scan_clauses);
     721         732 :             break;
     722             : 
     723        1940 :         case T_TidRangeScan:
     724        1940 :             plan = (Plan *) create_tidrangescan_plan(root,
     725             :                                                      (TidRangePath *) best_path,
     726             :                                                      tlist,
     727             :                                                      scan_clauses);
     728        1940 :             break;
     729             : 
     730       27752 :         case T_SubqueryScan:
     731       27752 :             plan = (Plan *) create_subqueryscan_plan(root,
     732             :                                                      (SubqueryScanPath *) best_path,
     733             :                                                      tlist,
     734             :                                                      scan_clauses);
     735       27752 :             break;
     736             : 
     737       51770 :         case T_FunctionScan:
     738       51770 :             plan = (Plan *) create_functionscan_plan(root,
     739             :                                                      best_path,
     740             :                                                      tlist,
     741             :                                                      scan_clauses);
     742       51770 :             break;
     743             : 
     744         626 :         case T_TableFuncScan:
     745         626 :             plan = (Plan *) create_tablefuncscan_plan(root,
     746             :                                                       best_path,
     747             :                                                       tlist,
     748             :                                                       scan_clauses);
     749         626 :             break;
     750             : 
     751        8248 :         case T_ValuesScan:
     752        8248 :             plan = (Plan *) create_valuesscan_plan(root,
     753             :                                                    best_path,
     754             :                                                    tlist,
     755             :                                                    scan_clauses);
     756        8248 :             break;
     757             : 
     758        4082 :         case T_CteScan:
     759        4082 :             plan = (Plan *) create_ctescan_plan(root,
     760             :                                                 best_path,
     761             :                                                 tlist,
     762             :                                                 scan_clauses);
     763        4082 :             break;
     764             : 
     765         462 :         case T_NamedTuplestoreScan:
     766         462 :             plan = (Plan *) create_namedtuplestorescan_plan(root,
     767             :                                                             best_path,
     768             :                                                             tlist,
     769             :                                                             scan_clauses);
     770         462 :             break;
     771             : 
     772        4086 :         case T_Result:
     773        4086 :             plan = (Plan *) create_resultscan_plan(root,
     774             :                                                    best_path,
     775             :                                                    tlist,
     776             :                                                    scan_clauses);
     777        4086 :             break;
     778             : 
     779        1004 :         case T_WorkTableScan:
     780        1004 :             plan = (Plan *) create_worktablescan_plan(root,
     781             :                                                       best_path,
     782             :                                                       tlist,
     783             :                                                       scan_clauses);
     784        1004 :             break;
     785             : 
     786        2046 :         case T_ForeignScan:
     787        2046 :             plan = (Plan *) create_foreignscan_plan(root,
     788             :                                                     (ForeignPath *) best_path,
     789             :                                                     tlist,
     790             :                                                     scan_clauses);
     791        2046 :             break;
     792             : 
     793           0 :         case T_CustomScan:
     794           0 :             plan = (Plan *) create_customscan_plan(root,
     795             :                                                    (CustomPath *) best_path,
     796             :                                                    tlist,
     797             :                                                    scan_clauses);
     798           0 :             break;
     799             : 
     800           0 :         default:
     801           0 :             elog(ERROR, "unrecognized node type: %d",
     802             :                  (int) best_path->pathtype);
     803             :             plan = NULL;        /* keep compiler quiet */
     804             :             break;
     805             :     }
     806             : 
     807             :     /*
     808             :      * If there are any pseudoconstant clauses attached to this node, insert a
     809             :      * gating Result node that evaluates the pseudoconstants as one-time
     810             :      * quals.
     811             :      */
     812      499340 :     if (gating_clauses)
     813        6700 :         plan = create_gating_plan(root, best_path, plan, gating_clauses);
     814             : 
     815      499340 :     return plan;
     816             : }
     817             : 
     818             : /*
     819             :  * Build a target list (ie, a list of TargetEntry) for the Path's output.
     820             :  *
     821             :  * This is almost just make_tlist_from_pathtarget(), but we also have to
     822             :  * deal with replacing nestloop params.
     823             :  */
     824             : static List *
     825      987098 : build_path_tlist(PlannerInfo *root, Path *path)
     826             : {
     827      987098 :     List       *tlist = NIL;
     828      987098 :     Index      *sortgrouprefs = path->pathtarget->sortgrouprefs;
     829      987098 :     int         resno = 1;
     830             :     ListCell   *v;
     831             : 
     832     3400024 :     foreach(v, path->pathtarget->exprs)
     833             :     {
     834     2412926 :         Node       *node = (Node *) lfirst(v);
     835             :         TargetEntry *tle;
     836             : 
     837             :         /*
     838             :          * If it's a parameterized path, there might be lateral references in
     839             :          * the tlist, which need to be replaced with Params.  There's no need
     840             :          * to remake the TargetEntry nodes, so apply this to each list item
     841             :          * separately.
     842             :          */
     843     2412926 :         if (path->param_info)
     844       21728 :             node = replace_nestloop_params(root, node);
     845             : 
     846     2412926 :         tle = makeTargetEntry((Expr *) node,
     847             :                               resno,
     848             :                               NULL,
     849             :                               false);
     850     2412926 :         if (sortgrouprefs)
     851     1508638 :             tle->ressortgroupref = sortgrouprefs[resno - 1];
     852             : 
     853     2412926 :         tlist = lappend(tlist, tle);
     854     2412926 :         resno++;
     855             :     }
     856      987098 :     return tlist;
     857             : }
     858             : 
     859             : /*
     860             :  * use_physical_tlist
     861             :  *      Decide whether to use a tlist matching relation structure,
     862             :  *      rather than only those Vars actually referenced.
     863             :  */
     864             : static bool
     865      758478 : use_physical_tlist(PlannerInfo *root, Path *path, int flags)
     866             : {
     867      758478 :     RelOptInfo *rel = path->parent;
     868             :     int         i;
     869             :     ListCell   *lc;
     870             : 
     871             :     /*
     872             :      * Forget it if either exact tlist or small tlist is demanded.
     873             :      */
     874      758478 :     if (flags & (CP_EXACT_TLIST | CP_SMALL_TLIST))
     875      523984 :         return false;
     876             : 
     877             :     /*
     878             :      * We can do this for real relation scans, subquery scans, function scans,
     879             :      * tablefunc scans, values scans, and CTE scans (but not for, eg, joins).
     880             :      */
     881      234494 :     if (rel->rtekind != RTE_RELATION &&
     882       38982 :         rel->rtekind != RTE_SUBQUERY &&
     883       36612 :         rel->rtekind != RTE_FUNCTION &&
     884       14204 :         rel->rtekind != RTE_TABLEFUNC &&
     885       13970 :         rel->rtekind != RTE_VALUES &&
     886       12646 :         rel->rtekind != RTE_CTE)
     887       11590 :         return false;
     888             : 
     889             :     /*
     890             :      * Can't do it with inheritance cases either (mainly because Append
     891             :      * doesn't project; this test may be unnecessary now that
     892             :      * create_append_plan instructs its children to return an exact tlist).
     893             :      */
     894      222904 :     if (rel->reloptkind != RELOPT_BASEREL)
     895        4748 :         return false;
     896             : 
     897             :     /*
     898             :      * Also, don't do it to a CustomPath; the premise that we're extracting
     899             :      * columns from a simple physical tuple is unlikely to hold for those.
     900             :      * (When it does make sense, the custom path creator can set up the path's
     901             :      * pathtarget that way.)
     902             :      */
     903      218156 :     if (IsA(path, CustomPath))
     904           0 :         return false;
     905             : 
     906             :     /*
     907             :      * If a bitmap scan's tlist is empty, keep it as-is.  This may allow the
     908             :      * executor to skip heap page fetches, and in any case, the benefit of
     909             :      * using a physical tlist instead would be minimal.
     910             :      */
     911      218156 :     if (IsA(path, BitmapHeapPath) &&
     912       10442 :         path->pathtarget->exprs == NIL)
     913        3156 :         return false;
     914             : 
     915             :     /*
     916             :      * Can't do it if any system columns or whole-row Vars are requested.
     917             :      * (This could possibly be fixed but would take some fragile assumptions
     918             :      * in setrefs.c, I think.)
     919             :      */
     920     1494014 :     for (i = rel->min_attr; i <= 0; i++)
     921             :     {
     922     1297828 :         if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
     923       18814 :             return false;
     924             :     }
     925             : 
     926             :     /*
     927             :      * Can't do it if the rel is required to emit any placeholder expressions,
     928             :      * either.
     929             :      */
     930      197822 :     foreach(lc, root->placeholder_list)
     931             :     {
     932        1988 :         PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
     933             : 
     934        3916 :         if (bms_nonempty_difference(phinfo->ph_needed, rel->relids) &&
     935        1928 :             bms_is_subset(phinfo->ph_eval_at, rel->relids))
     936         352 :             return false;
     937             :     }
     938             : 
     939             :     /*
     940             :      * For an index-only scan, the "physical tlist" is the index's indextlist.
     941             :      * We can only return that without a projection if all the index's columns
     942             :      * are returnable.
     943             :      */
     944      195834 :     if (path->pathtype == T_IndexOnlyScan)
     945             :     {
     946        8482 :         IndexOptInfo *indexinfo = ((IndexPath *) path)->indexinfo;
     947             : 
     948       18598 :         for (i = 0; i < indexinfo->ncolumns; i++)
     949             :         {
     950       10132 :             if (!indexinfo->canreturn[i])
     951          16 :                 return false;
     952             :         }
     953             :     }
     954             : 
     955             :     /*
     956             :      * Also, can't do it if CP_LABEL_TLIST is specified and path is requested
     957             :      * to emit any sort/group columns that are not simple Vars.  (If they are
     958             :      * simple Vars, they should appear in the physical tlist, and
     959             :      * apply_pathtarget_labeling_to_tlist will take care of getting them
     960             :      * labeled again.)  We also have to check that no two sort/group columns
     961             :      * are the same Var, else that element of the physical tlist would need
     962             :      * conflicting ressortgroupref labels.
     963             :      */
     964      195818 :     if ((flags & CP_LABEL_TLIST) && path->pathtarget->sortgrouprefs)
     965             :     {
     966        2082 :         Bitmapset  *sortgroupatts = NULL;
     967             : 
     968        2082 :         i = 0;
     969        5168 :         foreach(lc, path->pathtarget->exprs)
     970             :         {
     971        3752 :             Expr       *expr = (Expr *) lfirst(lc);
     972             : 
     973        3752 :             if (path->pathtarget->sortgrouprefs[i])
     974             :             {
     975        3068 :                 if (expr && IsA(expr, Var))
     976        2402 :                 {
     977        2414 :                     int         attno = ((Var *) expr)->varattno;
     978             : 
     979        2414 :                     attno -= FirstLowInvalidHeapAttributeNumber;
     980        2414 :                     if (bms_is_member(attno, sortgroupatts))
     981         666 :                         return false;
     982        2402 :                     sortgroupatts = bms_add_member(sortgroupatts, attno);
     983             :                 }
     984             :                 else
     985         654 :                     return false;
     986             :             }
     987        3086 :             i++;
     988             :         }
     989             :     }
     990             : 
     991      195152 :     return true;
     992             : }
     993             : 
     994             : /*
     995             :  * get_gating_quals
     996             :  *    See if there are pseudoconstant quals in a node's quals list
     997             :  *
     998             :  * If the node's quals list includes any pseudoconstant quals,
     999             :  * return just those quals.
    1000             :  */
    1001             : static List *
    1002      635110 : get_gating_quals(PlannerInfo *root, List *quals)
    1003             : {
    1004             :     /* No need to look if we know there are no pseudoconstants */
    1005      635110 :     if (!root->hasPseudoConstantQuals)
    1006      612648 :         return NIL;
    1007             : 
    1008             :     /* Sort into desirable execution order while still in RestrictInfo form */
    1009       22462 :     quals = order_qual_clauses(root, quals);
    1010             : 
    1011             :     /* Pull out any pseudoconstant quals from the RestrictInfo list */
    1012       22462 :     return extract_actual_clauses(quals, true);
    1013             : }
    1014             : 
    1015             : /*
    1016             :  * create_gating_plan
    1017             :  *    Deal with pseudoconstant qual clauses
    1018             :  *
    1019             :  * Add a gating Result node atop the already-built plan.
    1020             :  */
    1021             : static Plan *
    1022        9804 : create_gating_plan(PlannerInfo *root, Path *path, Plan *plan,
    1023             :                    List *gating_quals)
    1024             : {
    1025             :     Plan       *gplan;
    1026             :     Plan       *splan;
    1027             : 
    1028             :     Assert(gating_quals);
    1029             : 
    1030             :     /*
    1031             :      * We might have a trivial Result plan already.  Stacking one Result atop
    1032             :      * another is silly, so if that applies, just discard the input plan.
    1033             :      * (We're assuming its targetlist is uninteresting; it should be either
    1034             :      * the same as the result of build_path_tlist, or a simplified version.)
    1035             :      */
    1036        9804 :     splan = plan;
    1037        9804 :     if (IsA(plan, Result))
    1038             :     {
    1039          24 :         Result     *rplan = (Result *) plan;
    1040             : 
    1041          24 :         if (rplan->plan.lefttree == NULL &&
    1042          24 :             rplan->resconstantqual == NULL)
    1043          24 :             splan = NULL;
    1044             :     }
    1045             : 
    1046             :     /*
    1047             :      * Since we need a Result node anyway, always return the path's requested
    1048             :      * tlist; that's never a wrong choice, even if the parent node didn't ask
    1049             :      * for CP_EXACT_TLIST.
    1050             :      */
    1051        9804 :     gplan = (Plan *) make_result(build_path_tlist(root, path),
    1052             :                                  (Node *) gating_quals,
    1053             :                                  splan);
    1054             : 
    1055             :     /*
    1056             :      * Notice that we don't change cost or size estimates when doing gating.
    1057             :      * The costs of qual eval were already included in the subplan's cost.
    1058             :      * Leaving the size alone amounts to assuming that the gating qual will
    1059             :      * succeed, which is the conservative estimate for planning upper queries.
    1060             :      * We certainly don't want to assume the output size is zero (unless the
    1061             :      * gating qual is actually constant FALSE, and that case is dealt with in
    1062             :      * clausesel.c).  Interpolating between the two cases is silly, because it
    1063             :      * doesn't reflect what will really happen at runtime, and besides which
    1064             :      * in most cases we have only a very bad idea of the probability of the
    1065             :      * gating qual being true.
    1066             :      */
    1067        9804 :     copy_plan_costsize(gplan, plan);
    1068             : 
    1069             :     /* Gating quals could be unsafe, so better use the Path's safety flag */
    1070        9804 :     gplan->parallel_safe = path->parallel_safe;
    1071             : 
    1072        9804 :     return gplan;
    1073             : }
    1074             : 
    1075             : /*
    1076             :  * create_join_plan
    1077             :  *    Create a join plan for 'best_path' and (recursively) plans for its
    1078             :  *    inner and outer paths.
    1079             :  */
    1080             : static Plan *
    1081      135770 : create_join_plan(PlannerInfo *root, JoinPath *best_path)
    1082             : {
    1083             :     Plan       *plan;
    1084             :     List       *gating_clauses;
    1085             : 
    1086      135770 :     switch (best_path->path.pathtype)
    1087             :     {
    1088        8070 :         case T_MergeJoin:
    1089        8070 :             plan = (Plan *) create_mergejoin_plan(root,
    1090             :                                                   (MergePath *) best_path);
    1091        8070 :             break;
    1092       33270 :         case T_HashJoin:
    1093       33270 :             plan = (Plan *) create_hashjoin_plan(root,
    1094             :                                                  (HashPath *) best_path);
    1095       33270 :             break;
    1096       94430 :         case T_NestLoop:
    1097       94430 :             plan = (Plan *) create_nestloop_plan(root,
    1098             :                                                  (NestPath *) best_path);
    1099       94430 :             break;
    1100           0 :         default:
    1101           0 :             elog(ERROR, "unrecognized node type: %d",
    1102             :                  (int) best_path->path.pathtype);
    1103             :             plan = NULL;        /* keep compiler quiet */
    1104             :             break;
    1105             :     }
    1106             : 
    1107             :     /*
    1108             :      * If there are any pseudoconstant clauses attached to this node, insert a
    1109             :      * gating Result node that evaluates the pseudoconstants as one-time
    1110             :      * quals.
    1111             :      */
    1112      135770 :     gating_clauses = get_gating_quals(root, best_path->joinrestrictinfo);
    1113      135770 :     if (gating_clauses)
    1114        3104 :         plan = create_gating_plan(root, (Path *) best_path, plan,
    1115             :                                   gating_clauses);
    1116             : 
    1117             : #ifdef NOT_USED
    1118             : 
    1119             :     /*
    1120             :      * * Expensive function pullups may have pulled local predicates * into
    1121             :      * this path node.  Put them in the qpqual of the plan node. * JMH,
    1122             :      * 6/15/92
    1123             :      */
    1124             :     if (get_loc_restrictinfo(best_path) != NIL)
    1125             :         set_qpqual((Plan) plan,
    1126             :                    list_concat(get_qpqual((Plan) plan),
    1127             :                                get_actual_clauses(get_loc_restrictinfo(best_path))));
    1128             : #endif
    1129             : 
    1130      135770 :     return plan;
    1131             : }
    1132             : 
    1133             : /*
    1134             :  * mark_async_capable_plan
    1135             :  *      Check whether the Plan node created from a Path node is async-capable,
    1136             :  *      and if so, mark the Plan node as such and return true, otherwise
    1137             :  *      return false.
    1138             :  */
    1139             : static bool
    1140       29934 : mark_async_capable_plan(Plan *plan, Path *path)
    1141             : {
    1142       29934 :     switch (nodeTag(path))
    1143             :     {
    1144       10984 :         case T_SubqueryScanPath:
    1145             :             {
    1146       10984 :                 SubqueryScan *scan_plan = (SubqueryScan *) plan;
    1147             : 
    1148             :                 /*
    1149             :                  * If the generated plan node includes a gating Result node,
    1150             :                  * we can't execute it asynchronously.
    1151             :                  */
    1152       10984 :                 if (IsA(plan, Result))
    1153           4 :                     return false;
    1154             : 
    1155             :                 /*
    1156             :                  * If a SubqueryScan node atop of an async-capable plan node
    1157             :                  * is deletable, consider it as async-capable.
    1158             :                  */
    1159       15330 :                 if (trivial_subqueryscan(scan_plan) &&
    1160        4350 :                     mark_async_capable_plan(scan_plan->subplan,
    1161             :                                             ((SubqueryScanPath *) path)->subpath))
    1162          16 :                     break;
    1163       10964 :                 return false;
    1164             :             }
    1165         480 :         case T_ForeignPath:
    1166             :             {
    1167         480 :                 FdwRoutine *fdwroutine = path->parent->fdwroutine;
    1168             : 
    1169             :                 /*
    1170             :                  * If the generated plan node includes a gating Result node,
    1171             :                  * we can't execute it asynchronously.
    1172             :                  */
    1173         480 :                 if (IsA(plan, Result))
    1174           8 :                     return false;
    1175             : 
    1176             :                 Assert(fdwroutine != NULL);
    1177         938 :                 if (fdwroutine->IsForeignPathAsyncCapable != NULL &&
    1178         466 :                     fdwroutine->IsForeignPathAsyncCapable((ForeignPath *) path))
    1179         194 :                     break;
    1180         278 :                 return false;
    1181             :             }
    1182        5256 :         case T_ProjectionPath:
    1183             : 
    1184             :             /*
    1185             :              * If the generated plan node includes a Result node for the
    1186             :              * projection, we can't execute it asynchronously.
    1187             :              */
    1188        5256 :             if (IsA(plan, Result))
    1189         184 :                 return false;
    1190             : 
    1191             :             /*
    1192             :              * create_projection_plan() would have pulled up the subplan, so
    1193             :              * check the capability using the subpath.
    1194             :              */
    1195        5072 :             if (mark_async_capable_plan(plan,
    1196             :                                         ((ProjectionPath *) path)->subpath))
    1197          32 :                 return true;
    1198        5040 :             return false;
    1199       13214 :         default:
    1200       13214 :             return false;
    1201             :     }
    1202             : 
    1203         210 :     plan->async_capable = true;
    1204             : 
    1205         210 :     return true;
    1206             : }
    1207             : 
    1208             : /*
    1209             :  * create_append_plan
    1210             :  *    Create an Append plan for 'best_path' and (recursively) plans
    1211             :  *    for its subpaths.
    1212             :  *
    1213             :  *    Returns a Plan node.
    1214             :  */
    1215             : static Plan *
    1216       24296 : create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
    1217             : {
    1218             :     Append     *plan;
    1219       24296 :     List       *tlist = build_path_tlist(root, &best_path->path);
    1220       24296 :     int         orig_tlist_length = list_length(tlist);
    1221       24296 :     bool        tlist_was_changed = false;
    1222       24296 :     List       *pathkeys = best_path->path.pathkeys;
    1223       24296 :     List       *subplans = NIL;
    1224             :     ListCell   *subpaths;
    1225       24296 :     int         nasyncplans = 0;
    1226       24296 :     RelOptInfo *rel = best_path->path.parent;
    1227       24296 :     int         nodenumsortkeys = 0;
    1228       24296 :     AttrNumber *nodeSortColIdx = NULL;
    1229       24296 :     Oid        *nodeSortOperators = NULL;
    1230       24296 :     Oid        *nodeCollations = NULL;
    1231       24296 :     bool       *nodeNullsFirst = NULL;
    1232       24296 :     bool        consider_async = false;
    1233             : 
    1234             :     /*
    1235             :      * The subpaths list could be empty, if every child was proven empty by
    1236             :      * constraint exclusion.  In that case generate a dummy plan that returns
    1237             :      * no rows.
    1238             :      *
    1239             :      * Note that an AppendPath with no members is also generated in certain
    1240             :      * cases where there was no appending construct at all, but we know the
    1241             :      * relation is empty (see set_dummy_rel_pathlist and mark_dummy_rel).
    1242             :      */
    1243       24296 :     if (best_path->subpaths == NIL)
    1244             :     {
    1245             :         /* Generate a Result plan with constant-FALSE gating qual */
    1246             :         Plan       *plan;
    1247             : 
    1248        1024 :         plan = (Plan *) make_result(tlist,
    1249        1024 :                                     (Node *) list_make1(makeBoolConst(false,
    1250             :                                                                       false)),
    1251             :                                     NULL);
    1252             : 
    1253        1024 :         copy_generic_path_info(plan, (Path *) best_path);
    1254             : 
    1255        1024 :         return plan;
    1256             :     }
    1257             : 
    1258             :     /*
    1259             :      * Otherwise build an Append plan.  Note that if there's just one child,
    1260             :      * the Append is pretty useless; but we wait till setrefs.c to get rid of
    1261             :      * it.  Doing so here doesn't work because the varno of the child scan
    1262             :      * plan won't match the parent-rel Vars it'll be asked to emit.
    1263             :      *
    1264             :      * We don't have the actual creation of the Append node split out into a
    1265             :      * separate make_xxx function.  This is because we want to run
    1266             :      * prepare_sort_from_pathkeys on it before we do so on the individual
    1267             :      * child plans, to make cross-checking the sort info easier.
    1268             :      */
    1269       23272 :     plan = makeNode(Append);
    1270       23272 :     plan->plan.targetlist = tlist;
    1271       23272 :     plan->plan.qual = NIL;
    1272       23272 :     plan->plan.lefttree = NULL;
    1273       23272 :     plan->plan.righttree = NULL;
    1274       23272 :     plan->apprelids = rel->relids;
    1275             : 
    1276       23272 :     if (pathkeys != NIL)
    1277             :     {
    1278             :         /*
    1279             :          * Compute sort column info, and adjust the Append's tlist as needed.
    1280             :          * Because we pass adjust_tlist_in_place = true, we may ignore the
    1281             :          * function result; it must be the same plan node.  However, we then
    1282             :          * need to detect whether any tlist entries were added.
    1283             :          */
    1284         308 :         (void) prepare_sort_from_pathkeys((Plan *) plan, pathkeys,
    1285         308 :                                           best_path->path.parent->relids,
    1286             :                                           NULL,
    1287             :                                           true,
    1288             :                                           &nodenumsortkeys,
    1289             :                                           &nodeSortColIdx,
    1290             :                                           &nodeSortOperators,
    1291             :                                           &nodeCollations,
    1292             :                                           &nodeNullsFirst);
    1293         308 :         tlist_was_changed = (orig_tlist_length != list_length(plan->plan.targetlist));
    1294             :     }
    1295             : 
    1296             :     /* If appropriate, consider async append */
    1297       23272 :     consider_async = (enable_async_append && pathkeys == NIL &&
    1298       56686 :                       !best_path->path.parallel_safe &&
    1299       10142 :                       list_length(best_path->subpaths) > 1);
    1300             : 
    1301             :     /* Build the plan for each child */
    1302       76966 :     foreach(subpaths, best_path->subpaths)
    1303             :     {
    1304       53694 :         Path       *subpath = (Path *) lfirst(subpaths);
    1305             :         Plan       *subplan;
    1306             : 
    1307             :         /* Must insist that all children return the same tlist */
    1308       53694 :         subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
    1309             : 
    1310             :         /*
    1311             :          * For ordered Appends, we must insert a Sort node if subplan isn't
    1312             :          * sufficiently ordered.
    1313             :          */
    1314       53694 :         if (pathkeys != NIL)
    1315             :         {
    1316             :             int         numsortkeys;
    1317             :             AttrNumber *sortColIdx;
    1318             :             Oid        *sortOperators;
    1319             :             Oid        *collations;
    1320             :             bool       *nullsFirst;
    1321             : 
    1322             :             /*
    1323             :              * Compute sort column info, and adjust subplan's tlist as needed.
    1324             :              * We must apply prepare_sort_from_pathkeys even to subplans that
    1325             :              * don't need an explicit sort, to make sure they are returning
    1326             :              * the same sort key columns the Append expects.
    1327             :              */
    1328         776 :             subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
    1329         776 :                                                  subpath->parent->relids,
    1330             :                                                  nodeSortColIdx,
    1331             :                                                  false,
    1332             :                                                  &numsortkeys,
    1333             :                                                  &sortColIdx,
    1334             :                                                  &sortOperators,
    1335             :                                                  &collations,
    1336             :                                                  &nullsFirst);
    1337             : 
    1338             :             /*
    1339             :              * Check that we got the same sort key information.  We just
    1340             :              * Assert that the sortops match, since those depend only on the
    1341             :              * pathkeys; but it seems like a good idea to check the sort
    1342             :              * column numbers explicitly, to ensure the tlists match up.
    1343             :              */
    1344             :             Assert(numsortkeys == nodenumsortkeys);
    1345         776 :             if (memcmp(sortColIdx, nodeSortColIdx,
    1346             :                        numsortkeys * sizeof(AttrNumber)) != 0)
    1347           0 :                 elog(ERROR, "Append child's targetlist doesn't match Append");
    1348             :             Assert(memcmp(sortOperators, nodeSortOperators,
    1349             :                           numsortkeys * sizeof(Oid)) == 0);
    1350             :             Assert(memcmp(collations, nodeCollations,
    1351             :                           numsortkeys * sizeof(Oid)) == 0);
    1352             :             Assert(memcmp(nullsFirst, nodeNullsFirst,
    1353             :                           numsortkeys * sizeof(bool)) == 0);
    1354             : 
    1355             :             /* Now, insert a Sort node if subplan isn't sufficiently ordered */
    1356         776 :             if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
    1357             :             {
    1358           6 :                 Sort       *sort = make_sort(subplan, numsortkeys,
    1359             :                                              sortColIdx, sortOperators,
    1360             :                                              collations, nullsFirst);
    1361             : 
    1362           6 :                 label_sort_with_costsize(root, sort, best_path->limit_tuples);
    1363           6 :                 subplan = (Plan *) sort;
    1364             :             }
    1365             :         }
    1366             : 
    1367             :         /* If needed, check to see if subplan can be executed asynchronously */
    1368       53694 :         if (consider_async && mark_async_capable_plan(subplan, subpath))
    1369             :         {
    1370             :             Assert(subplan->async_capable);
    1371         194 :             ++nasyncplans;
    1372             :         }
    1373             : 
    1374       53694 :         subplans = lappend(subplans, subplan);
    1375             :     }
    1376             : 
    1377             :     /* Set below if we find quals that we can use to run-time prune */
    1378       23272 :     plan->part_prune_index = -1;
    1379             : 
    1380             :     /*
    1381             :      * If any quals exist, they may be useful to perform further partition
    1382             :      * pruning during execution.  Gather information needed by the executor to
    1383             :      * do partition pruning.
    1384             :      */
    1385       23272 :     if (enable_partition_pruning)
    1386             :     {
    1387             :         List       *prunequal;
    1388             : 
    1389       23218 :         prunequal = extract_actual_clauses(rel->baserestrictinfo, false);
    1390             : 
    1391       23218 :         if (best_path->path.param_info)
    1392             :         {
    1393         350 :             List       *prmquals = best_path->path.param_info->ppi_clauses;
    1394             : 
    1395         350 :             prmquals = extract_actual_clauses(prmquals, false);
    1396         350 :             prmquals = (List *) replace_nestloop_params(root,
    1397             :                                                         (Node *) prmquals);
    1398             : 
    1399         350 :             prunequal = list_concat(prunequal, prmquals);
    1400             :         }
    1401             : 
    1402       23218 :         if (prunequal != NIL)
    1403        9002 :             plan->part_prune_index = make_partition_pruneinfo(root, rel,
    1404             :                                                               best_path->subpaths,
    1405             :                                                               prunequal);
    1406             :     }
    1407             : 
    1408       23272 :     plan->appendplans = subplans;
    1409       23272 :     plan->nasyncplans = nasyncplans;
    1410       23272 :     plan->first_partial_plan = best_path->first_partial_path;
    1411             : 
    1412       23272 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    1413             : 
    1414             :     /*
    1415             :      * If prepare_sort_from_pathkeys added sort columns, but we were told to
    1416             :      * produce either the exact tlist or a narrow tlist, we should get rid of
    1417             :      * the sort columns again.  We must inject a projection node to do so.
    1418             :      */
    1419       23272 :     if (tlist_was_changed && (flags & (CP_EXACT_TLIST | CP_SMALL_TLIST)))
    1420             :     {
    1421           0 :         tlist = list_copy_head(plan->plan.targetlist, orig_tlist_length);
    1422           0 :         return inject_projection_plan((Plan *) plan, tlist,
    1423           0 :                                       plan->plan.parallel_safe);
    1424             :     }
    1425             :     else
    1426       23272 :         return (Plan *) plan;
    1427             : }
    1428             : 
    1429             : /*
    1430             :  * create_merge_append_plan
    1431             :  *    Create a MergeAppend plan for 'best_path' and (recursively) plans
    1432             :  *    for its subpaths.
    1433             :  *
    1434             :  *    Returns a Plan node.
    1435             :  */
    1436             : static Plan *
    1437         530 : create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path,
    1438             :                          int flags)
    1439             : {
    1440         530 :     MergeAppend *node = makeNode(MergeAppend);
    1441         530 :     Plan       *plan = &node->plan;
    1442         530 :     List       *tlist = build_path_tlist(root, &best_path->path);
    1443         530 :     int         orig_tlist_length = list_length(tlist);
    1444             :     bool        tlist_was_changed;
    1445         530 :     List       *pathkeys = best_path->path.pathkeys;
    1446         530 :     List       *subplans = NIL;
    1447             :     ListCell   *subpaths;
    1448         530 :     RelOptInfo *rel = best_path->path.parent;
    1449             : 
    1450             :     /*
    1451             :      * We don't have the actual creation of the MergeAppend node split out
    1452             :      * into a separate make_xxx function.  This is because we want to run
    1453             :      * prepare_sort_from_pathkeys on it before we do so on the individual
    1454             :      * child plans, to make cross-checking the sort info easier.
    1455             :      */
    1456         530 :     copy_generic_path_info(plan, (Path *) best_path);
    1457         530 :     plan->targetlist = tlist;
    1458         530 :     plan->qual = NIL;
    1459         530 :     plan->lefttree = NULL;
    1460         530 :     plan->righttree = NULL;
    1461         530 :     node->apprelids = rel->relids;
    1462             : 
    1463             :     /*
    1464             :      * Compute sort column info, and adjust MergeAppend's tlist as needed.
    1465             :      * Because we pass adjust_tlist_in_place = true, we may ignore the
    1466             :      * function result; it must be the same plan node.  However, we then need
    1467             :      * to detect whether any tlist entries were added.
    1468             :      */
    1469         530 :     (void) prepare_sort_from_pathkeys(plan, pathkeys,
    1470         530 :                                       best_path->path.parent->relids,
    1471             :                                       NULL,
    1472             :                                       true,
    1473             :                                       &node->numCols,
    1474             :                                       &node->sortColIdx,
    1475             :                                       &node->sortOperators,
    1476             :                                       &node->collations,
    1477             :                                       &node->nullsFirst);
    1478         530 :     tlist_was_changed = (orig_tlist_length != list_length(plan->targetlist));
    1479             : 
    1480             :     /*
    1481             :      * Now prepare the child plans.  We must apply prepare_sort_from_pathkeys
    1482             :      * even to subplans that don't need an explicit sort, to make sure they
    1483             :      * are returning the same sort key columns the MergeAppend expects.
    1484             :      */
    1485        2014 :     foreach(subpaths, best_path->subpaths)
    1486             :     {
    1487        1484 :         Path       *subpath = (Path *) lfirst(subpaths);
    1488             :         Plan       *subplan;
    1489             :         int         numsortkeys;
    1490             :         AttrNumber *sortColIdx;
    1491             :         Oid        *sortOperators;
    1492             :         Oid        *collations;
    1493             :         bool       *nullsFirst;
    1494             : 
    1495             :         /* Build the child plan */
    1496             :         /* Must insist that all children return the same tlist */
    1497        1484 :         subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
    1498             : 
    1499             :         /* Compute sort column info, and adjust subplan's tlist as needed */
    1500        1484 :         subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
    1501        1484 :                                              subpath->parent->relids,
    1502        1484 :                                              node->sortColIdx,
    1503             :                                              false,
    1504             :                                              &numsortkeys,
    1505             :                                              &sortColIdx,
    1506             :                                              &sortOperators,
    1507             :                                              &collations,
    1508             :                                              &nullsFirst);
    1509             : 
    1510             :         /*
    1511             :          * Check that we got the same sort key information.  We just Assert
    1512             :          * that the sortops match, since those depend only on the pathkeys;
    1513             :          * but it seems like a good idea to check the sort column numbers
    1514             :          * explicitly, to ensure the tlists really do match up.
    1515             :          */
    1516             :         Assert(numsortkeys == node->numCols);
    1517        1484 :         if (memcmp(sortColIdx, node->sortColIdx,
    1518             :                    numsortkeys * sizeof(AttrNumber)) != 0)
    1519           0 :             elog(ERROR, "MergeAppend child's targetlist doesn't match MergeAppend");
    1520             :         Assert(memcmp(sortOperators, node->sortOperators,
    1521             :                       numsortkeys * sizeof(Oid)) == 0);
    1522             :         Assert(memcmp(collations, node->collations,
    1523             :                       numsortkeys * sizeof(Oid)) == 0);
    1524             :         Assert(memcmp(nullsFirst, node->nullsFirst,
    1525             :                       numsortkeys * sizeof(bool)) == 0);
    1526             : 
    1527             :         /* Now, insert a Sort node if subplan isn't sufficiently ordered */
    1528        1484 :         if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
    1529             :         {
    1530          78 :             Sort       *sort = make_sort(subplan, numsortkeys,
    1531             :                                          sortColIdx, sortOperators,
    1532             :                                          collations, nullsFirst);
    1533             : 
    1534          78 :             label_sort_with_costsize(root, sort, best_path->limit_tuples);
    1535          78 :             subplan = (Plan *) sort;
    1536             :         }
    1537             : 
    1538        1484 :         subplans = lappend(subplans, subplan);
    1539             :     }
    1540             : 
    1541             :     /* Set below if we find quals that we can use to run-time prune */
    1542         530 :     node->part_prune_index = -1;
    1543             : 
    1544             :     /*
    1545             :      * If any quals exist, they may be useful to perform further partition
    1546             :      * pruning during execution.  Gather information needed by the executor to
    1547             :      * do partition pruning.
    1548             :      */
    1549         530 :     if (enable_partition_pruning)
    1550             :     {
    1551             :         List       *prunequal;
    1552             : 
    1553         530 :         prunequal = extract_actual_clauses(rel->baserestrictinfo, false);
    1554             : 
    1555             :         /* We don't currently generate any parameterized MergeAppend paths */
    1556             :         Assert(best_path->path.param_info == NULL);
    1557             : 
    1558         530 :         if (prunequal != NIL)
    1559         168 :             node->part_prune_index = make_partition_pruneinfo(root, rel,
    1560             :                                                               best_path->subpaths,
    1561             :                                                               prunequal);
    1562             :     }
    1563             : 
    1564         530 :     node->mergeplans = subplans;
    1565             : 
    1566             :     /*
    1567             :      * If prepare_sort_from_pathkeys added sort columns, but we were told to
    1568             :      * produce either the exact tlist or a narrow tlist, we should get rid of
    1569             :      * the sort columns again.  We must inject a projection node to do so.
    1570             :      */
    1571         530 :     if (tlist_was_changed && (flags & (CP_EXACT_TLIST | CP_SMALL_TLIST)))
    1572             :     {
    1573           0 :         tlist = list_copy_head(plan->targetlist, orig_tlist_length);
    1574           0 :         return inject_projection_plan(plan, tlist, plan->parallel_safe);
    1575             :     }
    1576             :     else
    1577         530 :         return plan;
    1578             : }
    1579             : 
    1580             : /*
    1581             :  * create_group_result_plan
    1582             :  *    Create a Result plan for 'best_path'.
    1583             :  *    This is only used for degenerate grouping cases.
    1584             :  *
    1585             :  *    Returns a Plan node.
    1586             :  */
    1587             : static Result *
    1588      192890 : create_group_result_plan(PlannerInfo *root, GroupResultPath *best_path)
    1589             : {
    1590             :     Result     *plan;
    1591             :     List       *tlist;
    1592             :     List       *quals;
    1593             : 
    1594      192890 :     tlist = build_path_tlist(root, &best_path->path);
    1595             : 
    1596             :     /* best_path->quals is just bare clauses */
    1597      192890 :     quals = order_qual_clauses(root, best_path->quals);
    1598             : 
    1599      192890 :     plan = make_result(tlist, (Node *) quals, NULL);
    1600             : 
    1601      192890 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    1602             : 
    1603      192890 :     return plan;
    1604             : }
    1605             : 
    1606             : /*
    1607             :  * create_project_set_plan
    1608             :  *    Create a ProjectSet plan for 'best_path'.
    1609             :  *
    1610             :  *    Returns a Plan node.
    1611             :  */
    1612             : static ProjectSet *
    1613       12050 : create_project_set_plan(PlannerInfo *root, ProjectSetPath *best_path)
    1614             : {
    1615             :     ProjectSet *plan;
    1616             :     Plan       *subplan;
    1617             :     List       *tlist;
    1618             : 
    1619             :     /* Since we intend to project, we don't need to constrain child tlist */
    1620       12050 :     subplan = create_plan_recurse(root, best_path->subpath, 0);
    1621             : 
    1622       12050 :     tlist = build_path_tlist(root, &best_path->path);
    1623             : 
    1624       12050 :     plan = make_project_set(tlist, subplan);
    1625             : 
    1626       12050 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    1627             : 
    1628       12050 :     return plan;
    1629             : }
    1630             : 
    1631             : /*
    1632             :  * create_material_plan
    1633             :  *    Create a Material plan for 'best_path' and (recursively) plans
    1634             :  *    for its subpaths.
    1635             :  *
    1636             :  *    Returns a Plan node.
    1637             :  */
    1638             : static Material *
    1639        4650 : create_material_plan(PlannerInfo *root, MaterialPath *best_path, int flags)
    1640             : {
    1641             :     Material   *plan;
    1642             :     Plan       *subplan;
    1643             : 
    1644             :     /*
    1645             :      * We don't want any excess columns in the materialized tuples, so request
    1646             :      * a smaller tlist.  Otherwise, since Material doesn't project, tlist
    1647             :      * requirements pass through.
    1648             :      */
    1649        4650 :     subplan = create_plan_recurse(root, best_path->subpath,
    1650             :                                   flags | CP_SMALL_TLIST);
    1651             : 
    1652        4650 :     plan = make_material(subplan);
    1653             : 
    1654        4650 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    1655             : 
    1656        4650 :     return plan;
    1657             : }
    1658             : 
    1659             : /*
    1660             :  * create_memoize_plan
    1661             :  *    Create a Memoize plan for 'best_path' and (recursively) plans for its
    1662             :  *    subpaths.
    1663             :  *
    1664             :  *    Returns a Plan node.
    1665             :  */
    1666             : static Memoize *
    1667        1914 : create_memoize_plan(PlannerInfo *root, MemoizePath *best_path, int flags)
    1668             : {
    1669             :     Memoize    *plan;
    1670             :     Bitmapset  *keyparamids;
    1671             :     Plan       *subplan;
    1672             :     Oid        *operators;
    1673             :     Oid        *collations;
    1674        1914 :     List       *param_exprs = NIL;
    1675             :     ListCell   *lc;
    1676             :     ListCell   *lc2;
    1677             :     int         nkeys;
    1678             :     int         i;
    1679             : 
    1680        1914 :     subplan = create_plan_recurse(root, best_path->subpath,
    1681             :                                   flags | CP_SMALL_TLIST);
    1682             : 
    1683        1914 :     param_exprs = (List *) replace_nestloop_params(root, (Node *)
    1684        1914 :                                                    best_path->param_exprs);
    1685             : 
    1686        1914 :     nkeys = list_length(param_exprs);
    1687             :     Assert(nkeys > 0);
    1688        1914 :     operators = palloc(nkeys * sizeof(Oid));
    1689        1914 :     collations = palloc(nkeys * sizeof(Oid));
    1690             : 
    1691        1914 :     i = 0;
    1692        3890 :     forboth(lc, param_exprs, lc2, best_path->hash_operators)
    1693             :     {
    1694        1976 :         Expr       *param_expr = (Expr *) lfirst(lc);
    1695        1976 :         Oid         opno = lfirst_oid(lc2);
    1696             : 
    1697        1976 :         operators[i] = opno;
    1698        1976 :         collations[i] = exprCollation((Node *) param_expr);
    1699        1976 :         i++;
    1700             :     }
    1701             : 
    1702        1914 :     keyparamids = pull_paramids((Expr *) param_exprs);
    1703             : 
    1704        1914 :     plan = make_memoize(subplan, operators, collations, param_exprs,
    1705        1914 :                         best_path->singlerow, best_path->binary_mode,
    1706             :                         best_path->est_entries, keyparamids);
    1707             : 
    1708        1914 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    1709             : 
    1710        1914 :     return plan;
    1711             : }
    1712             : 
    1713             : /*
    1714             :  * create_unique_plan
    1715             :  *    Create a Unique plan for 'best_path' and (recursively) plans
    1716             :  *    for its subpaths.
    1717             :  *
    1718             :  *    Returns a Plan node.
    1719             :  */
    1720             : static Plan *
    1721         628 : create_unique_plan(PlannerInfo *root, UniquePath *best_path, int flags)
    1722             : {
    1723             :     Plan       *plan;
    1724             :     Plan       *subplan;
    1725             :     List       *in_operators;
    1726             :     List       *uniq_exprs;
    1727             :     List       *newtlist;
    1728             :     int         nextresno;
    1729             :     bool        newitems;
    1730             :     int         numGroupCols;
    1731             :     AttrNumber *groupColIdx;
    1732             :     Oid        *groupCollations;
    1733             :     int         groupColPos;
    1734             :     ListCell   *l;
    1735             : 
    1736             :     /* Unique doesn't project, so tlist requirements pass through */
    1737         628 :     subplan = create_plan_recurse(root, best_path->subpath, flags);
    1738             : 
    1739             :     /* Done if we don't need to do any actual unique-ifying */
    1740         628 :     if (best_path->umethod == UNIQUE_PATH_NOOP)
    1741           0 :         return subplan;
    1742             : 
    1743             :     /*
    1744             :      * As constructed, the subplan has a "flat" tlist containing just the Vars
    1745             :      * needed here and at upper levels.  The values we are supposed to
    1746             :      * unique-ify may be expressions in these variables.  We have to add any
    1747             :      * such expressions to the subplan's tlist.
    1748             :      *
    1749             :      * The subplan may have a "physical" tlist if it is a simple scan plan. If
    1750             :      * we're going to sort, this should be reduced to the regular tlist, so
    1751             :      * that we don't sort more data than we need to.  For hashing, the tlist
    1752             :      * should be left as-is if we don't need to add any expressions; but if we
    1753             :      * do have to add expressions, then a projection step will be needed at
    1754             :      * runtime anyway, so we may as well remove unneeded items. Therefore
    1755             :      * newtlist starts from build_path_tlist() not just a copy of the
    1756             :      * subplan's tlist; and we don't install it into the subplan unless we are
    1757             :      * sorting or stuff has to be added.
    1758             :      */
    1759         628 :     in_operators = best_path->in_operators;
    1760         628 :     uniq_exprs = best_path->uniq_exprs;
    1761             : 
    1762             :     /* initialize modified subplan tlist as just the "required" vars */
    1763         628 :     newtlist = build_path_tlist(root, &best_path->path);
    1764         628 :     nextresno = list_length(newtlist) + 1;
    1765         628 :     newitems = false;
    1766             : 
    1767        1316 :     foreach(l, uniq_exprs)
    1768             :     {
    1769         688 :         Expr       *uniqexpr = lfirst(l);
    1770             :         TargetEntry *tle;
    1771             : 
    1772         688 :         tle = tlist_member(uniqexpr, newtlist);
    1773         688 :         if (!tle)
    1774             :         {
    1775          98 :             tle = makeTargetEntry((Expr *) uniqexpr,
    1776             :                                   nextresno,
    1777             :                                   NULL,
    1778             :                                   false);
    1779          98 :             newtlist = lappend(newtlist, tle);
    1780          98 :             nextresno++;
    1781          98 :             newitems = true;
    1782             :         }
    1783             :     }
    1784             : 
    1785             :     /* Use change_plan_targetlist in case we need to insert a Result node */
    1786         628 :     if (newitems || best_path->umethod == UNIQUE_PATH_SORT)
    1787         118 :         subplan = change_plan_targetlist(subplan, newtlist,
    1788         118 :                                          best_path->path.parallel_safe);
    1789             : 
    1790             :     /*
    1791             :      * Build control information showing which subplan output columns are to
    1792             :      * be examined by the grouping step.  Unfortunately we can't merge this
    1793             :      * with the previous loop, since we didn't then know which version of the
    1794             :      * subplan tlist we'd end up using.
    1795             :      */
    1796         628 :     newtlist = subplan->targetlist;
    1797         628 :     numGroupCols = list_length(uniq_exprs);
    1798         628 :     groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber));
    1799         628 :     groupCollations = (Oid *) palloc(numGroupCols * sizeof(Oid));
    1800             : 
    1801         628 :     groupColPos = 0;
    1802        1316 :     foreach(l, uniq_exprs)
    1803             :     {
    1804         688 :         Expr       *uniqexpr = lfirst(l);
    1805             :         TargetEntry *tle;
    1806             : 
    1807         688 :         tle = tlist_member(uniqexpr, newtlist);
    1808         688 :         if (!tle)               /* shouldn't happen */
    1809           0 :             elog(ERROR, "failed to find unique expression in subplan tlist");
    1810         688 :         groupColIdx[groupColPos] = tle->resno;
    1811         688 :         groupCollations[groupColPos] = exprCollation((Node *) tle->expr);
    1812         688 :         groupColPos++;
    1813             :     }
    1814             : 
    1815         628 :     if (best_path->umethod == UNIQUE_PATH_HASH)
    1816             :     {
    1817             :         Oid        *groupOperators;
    1818             : 
    1819             :         /*
    1820             :          * Get the hashable equality operators for the Agg node to use.
    1821             :          * Normally these are the same as the IN clause operators, but if
    1822             :          * those are cross-type operators then the equality operators are the
    1823             :          * ones for the IN clause operators' RHS datatype.
    1824             :          */
    1825         602 :         groupOperators = (Oid *) palloc(numGroupCols * sizeof(Oid));
    1826         602 :         groupColPos = 0;
    1827        1264 :         foreach(l, in_operators)
    1828             :         {
    1829         662 :             Oid         in_oper = lfirst_oid(l);
    1830             :             Oid         eq_oper;
    1831             : 
    1832         662 :             if (!get_compatible_hash_operators(in_oper, NULL, &eq_oper))
    1833           0 :                 elog(ERROR, "could not find compatible hash operator for operator %u",
    1834             :                      in_oper);
    1835         662 :             groupOperators[groupColPos++] = eq_oper;
    1836             :         }
    1837             : 
    1838             :         /*
    1839             :          * Since the Agg node is going to project anyway, we can give it the
    1840             :          * minimum output tlist, without any stuff we might have added to the
    1841             :          * subplan tlist.
    1842             :          */
    1843         602 :         plan = (Plan *) make_agg(build_path_tlist(root, &best_path->path),
    1844             :                                  NIL,
    1845             :                                  AGG_HASHED,
    1846             :                                  AGGSPLIT_SIMPLE,
    1847             :                                  numGroupCols,
    1848             :                                  groupColIdx,
    1849             :                                  groupOperators,
    1850             :                                  groupCollations,
    1851             :                                  NIL,
    1852             :                                  NIL,
    1853             :                                  best_path->path.rows,
    1854             :                                  0,
    1855             :                                  subplan);
    1856             :     }
    1857             :     else
    1858             :     {
    1859          26 :         List       *sortList = NIL;
    1860             :         Sort       *sort;
    1861             : 
    1862             :         /* Create an ORDER BY list to sort the input compatibly */
    1863          26 :         groupColPos = 0;
    1864          52 :         foreach(l, in_operators)
    1865             :         {
    1866          26 :             Oid         in_oper = lfirst_oid(l);
    1867             :             Oid         sortop;
    1868             :             Oid         eqop;
    1869             :             TargetEntry *tle;
    1870             :             SortGroupClause *sortcl;
    1871             : 
    1872          26 :             sortop = get_ordering_op_for_equality_op(in_oper, false);
    1873          26 :             if (!OidIsValid(sortop))    /* shouldn't happen */
    1874           0 :                 elog(ERROR, "could not find ordering operator for equality operator %u",
    1875             :                      in_oper);
    1876             : 
    1877             :             /*
    1878             :              * The Unique node will need equality operators.  Normally these
    1879             :              * are the same as the IN clause operators, but if those are
    1880             :              * cross-type operators then the equality operators are the ones
    1881             :              * for the IN clause operators' RHS datatype.
    1882             :              */
    1883          26 :             eqop = get_equality_op_for_ordering_op(sortop, NULL);
    1884          26 :             if (!OidIsValid(eqop))  /* shouldn't happen */
    1885           0 :                 elog(ERROR, "could not find equality operator for ordering operator %u",
    1886             :                      sortop);
    1887             : 
    1888          26 :             tle = get_tle_by_resno(subplan->targetlist,
    1889          26 :                                    groupColIdx[groupColPos]);
    1890             :             Assert(tle != NULL);
    1891             : 
    1892          26 :             sortcl = makeNode(SortGroupClause);
    1893          26 :             sortcl->tleSortGroupRef = assignSortGroupRef(tle,
    1894             :                                                          subplan->targetlist);
    1895          26 :             sortcl->eqop = eqop;
    1896          26 :             sortcl->sortop = sortop;
    1897          26 :             sortcl->reverse_sort = false;
    1898          26 :             sortcl->nulls_first = false;
    1899          26 :             sortcl->hashable = false;    /* no need to make this accurate */
    1900          26 :             sortList = lappend(sortList, sortcl);
    1901          26 :             groupColPos++;
    1902             :         }
    1903          26 :         sort = make_sort_from_sortclauses(sortList, subplan);
    1904          26 :         label_sort_with_costsize(root, sort, -1.0);
    1905          26 :         plan = (Plan *) make_unique_from_sortclauses((Plan *) sort, sortList);
    1906             :     }
    1907             : 
    1908             :     /* Copy cost data from Path to Plan */
    1909         628 :     copy_generic_path_info(plan, &best_path->path);
    1910             : 
    1911         628 :     return plan;
    1912             : }
    1913             : 
    1914             : /*
    1915             :  * create_gather_plan
    1916             :  *
    1917             :  *    Create a Gather plan for 'best_path' and (recursively) plans
    1918             :  *    for its subpaths.
    1919             :  */
    1920             : static Gather *
    1921         950 : create_gather_plan(PlannerInfo *root, GatherPath *best_path)
    1922             : {
    1923             :     Gather     *gather_plan;
    1924             :     Plan       *subplan;
    1925             :     List       *tlist;
    1926             : 
    1927             :     /*
    1928             :      * Push projection down to the child node.  That way, the projection work
    1929             :      * is parallelized, and there can be no system columns in the result (they
    1930             :      * can't travel through a tuple queue because it uses MinimalTuple
    1931             :      * representation).
    1932             :      */
    1933         950 :     subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
    1934             : 
    1935         950 :     tlist = build_path_tlist(root, &best_path->path);
    1936             : 
    1937         950 :     gather_plan = make_gather(tlist,
    1938             :                               NIL,
    1939             :                               best_path->num_workers,
    1940             :                               assign_special_exec_param(root),
    1941         950 :                               best_path->single_copy,
    1942             :                               subplan);
    1943             : 
    1944         950 :     copy_generic_path_info(&gather_plan->plan, &best_path->path);
    1945             : 
    1946             :     /* use parallel mode for parallel plans. */
    1947         950 :     root->glob->parallelModeNeeded = true;
    1948             : 
    1949         950 :     return gather_plan;
    1950             : }
    1951             : 
    1952             : /*
    1953             :  * create_gather_merge_plan
    1954             :  *
    1955             :  *    Create a Gather Merge plan for 'best_path' and (recursively)
    1956             :  *    plans for its subpaths.
    1957             :  */
    1958             : static GatherMerge *
    1959         330 : create_gather_merge_plan(PlannerInfo *root, GatherMergePath *best_path)
    1960             : {
    1961             :     GatherMerge *gm_plan;
    1962             :     Plan       *subplan;
    1963         330 :     List       *pathkeys = best_path->path.pathkeys;
    1964         330 :     List       *tlist = build_path_tlist(root, &best_path->path);
    1965             : 
    1966             :     /* As with Gather, project away columns in the workers. */
    1967         330 :     subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
    1968             : 
    1969             :     /* Create a shell for a GatherMerge plan. */
    1970         330 :     gm_plan = makeNode(GatherMerge);
    1971         330 :     gm_plan->plan.targetlist = tlist;
    1972         330 :     gm_plan->num_workers = best_path->num_workers;
    1973         330 :     copy_generic_path_info(&gm_plan->plan, &best_path->path);
    1974             : 
    1975             :     /* Assign the rescan Param. */
    1976         330 :     gm_plan->rescan_param = assign_special_exec_param(root);
    1977             : 
    1978             :     /* Gather Merge is pointless with no pathkeys; use Gather instead. */
    1979             :     Assert(pathkeys != NIL);
    1980             : 
    1981             :     /* Compute sort column info, and adjust subplan's tlist as needed */
    1982         330 :     subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
    1983         330 :                                          best_path->subpath->parent->relids,
    1984         330 :                                          gm_plan->sortColIdx,
    1985             :                                          false,
    1986             :                                          &gm_plan->numCols,
    1987             :                                          &gm_plan->sortColIdx,
    1988             :                                          &gm_plan->sortOperators,
    1989             :                                          &gm_plan->collations,
    1990             :                                          &gm_plan->nullsFirst);
    1991             : 
    1992             :     /*
    1993             :      * All gather merge paths should have already guaranteed the necessary
    1994             :      * sort order.  See create_gather_merge_path.
    1995             :      */
    1996             :     Assert(pathkeys_contained_in(pathkeys, best_path->subpath->pathkeys));
    1997             : 
    1998             :     /* Now insert the subplan under GatherMerge. */
    1999         330 :     gm_plan->plan.lefttree = subplan;
    2000             : 
    2001             :     /* use parallel mode for parallel plans. */
    2002         330 :     root->glob->parallelModeNeeded = true;
    2003             : 
    2004         330 :     return gm_plan;
    2005             : }
    2006             : 
    2007             : /*
    2008             :  * create_projection_plan
    2009             :  *
    2010             :  *    Create a plan tree to do a projection step and (recursively) plans
    2011             :  *    for its subpaths.  We may need a Result node for the projection,
    2012             :  *    but sometimes we can just let the subplan do the work.
    2013             :  */
    2014             : static Plan *
    2015      338220 : create_projection_plan(PlannerInfo *root, ProjectionPath *best_path, int flags)
    2016             : {
    2017             :     Plan       *plan;
    2018             :     Plan       *subplan;
    2019             :     List       *tlist;
    2020      338220 :     bool        needs_result_node = false;
    2021             : 
    2022             :     /*
    2023             :      * Convert our subpath to a Plan and determine whether we need a Result
    2024             :      * node.
    2025             :      *
    2026             :      * In most cases where we don't need to project, create_projection_path
    2027             :      * will have set dummypp, but not always.  First, some createplan.c
    2028             :      * routines change the tlists of their nodes.  (An example is that
    2029             :      * create_merge_append_plan might add resjunk sort columns to a
    2030             :      * MergeAppend.)  Second, create_projection_path has no way of knowing
    2031             :      * what path node will be placed on top of the projection path and
    2032             :      * therefore can't predict whether it will require an exact tlist. For
    2033             :      * both of these reasons, we have to recheck here.
    2034             :      */
    2035      338220 :     if (use_physical_tlist(root, &best_path->path, flags))
    2036             :     {
    2037             :         /*
    2038             :          * Our caller doesn't really care what tlist we return, so we don't
    2039             :          * actually need to project.  However, we may still need to ensure
    2040             :          * proper sortgroupref labels, if the caller cares about those.
    2041             :          */
    2042        1508 :         subplan = create_plan_recurse(root, best_path->subpath, 0);
    2043        1508 :         tlist = subplan->targetlist;
    2044        1508 :         if (flags & CP_LABEL_TLIST)
    2045         570 :             apply_pathtarget_labeling_to_tlist(tlist,
    2046             :                                                best_path->path.pathtarget);
    2047             :     }
    2048      336712 :     else if (is_projection_capable_path(best_path->subpath))
    2049             :     {
    2050             :         /*
    2051             :          * Our caller requires that we return the exact tlist, but no separate
    2052             :          * result node is needed because the subpath is projection-capable.
    2053             :          * Tell create_plan_recurse that we're going to ignore the tlist it
    2054             :          * produces.
    2055             :          */
    2056      334848 :         subplan = create_plan_recurse(root, best_path->subpath,
    2057             :                                       CP_IGNORE_TLIST);
    2058             :         Assert(is_projection_capable_plan(subplan));
    2059      334848 :         tlist = build_path_tlist(root, &best_path->path);
    2060             :     }
    2061             :     else
    2062             :     {
    2063             :         /*
    2064             :          * It looks like we need a result node, unless by good fortune the
    2065             :          * requested tlist is exactly the one the child wants to produce.
    2066             :          */
    2067        1864 :         subplan = create_plan_recurse(root, best_path->subpath, 0);
    2068        1864 :         tlist = build_path_tlist(root, &best_path->path);
    2069        1864 :         needs_result_node = !tlist_same_exprs(tlist, subplan->targetlist);
    2070             :     }
    2071             : 
    2072             :     /*
    2073             :      * If we make a different decision about whether to include a Result node
    2074             :      * than create_projection_path did, we'll have made slightly wrong cost
    2075             :      * estimates; but label the plan with the cost estimates we actually used,
    2076             :      * not "corrected" ones.  (XXX this could be cleaned up if we moved more
    2077             :      * of the sortcolumn setup logic into Path creation, but that would add
    2078             :      * expense to creating Paths we might end up not using.)
    2079             :      */
    2080      338220 :     if (!needs_result_node)
    2081             :     {
    2082             :         /* Don't need a separate Result, just assign tlist to subplan */
    2083      336494 :         plan = subplan;
    2084      336494 :         plan->targetlist = tlist;
    2085             : 
    2086             :         /* Label plan with the estimated costs we actually used */
    2087      336494 :         plan->startup_cost = best_path->path.startup_cost;
    2088      336494 :         plan->total_cost = best_path->path.total_cost;
    2089      336494 :         plan->plan_rows = best_path->path.rows;
    2090      336494 :         plan->plan_width = best_path->path.pathtarget->width;
    2091      336494 :         plan->parallel_safe = best_path->path.parallel_safe;
    2092             :         /* ... but don't change subplan's parallel_aware flag */
    2093             :     }
    2094             :     else
    2095             :     {
    2096             :         /* We need a Result node */
    2097        1726 :         plan = (Plan *) make_result(tlist, NULL, subplan);
    2098             : 
    2099        1726 :         copy_generic_path_info(plan, (Path *) best_path);
    2100             :     }
    2101             : 
    2102      338220 :     return plan;
    2103             : }
    2104             : 
    2105             : /*
    2106             :  * inject_projection_plan
    2107             :  *    Insert a Result node to do a projection step.
    2108             :  *
    2109             :  * This is used in a few places where we decide on-the-fly that we need a
    2110             :  * projection step as part of the tree generated for some Path node.
    2111             :  * We should try to get rid of this in favor of doing it more honestly.
    2112             :  *
    2113             :  * One reason it's ugly is we have to be told the right parallel_safe marking
    2114             :  * to apply (since the tlist might be unsafe even if the child plan is safe).
    2115             :  */
    2116             : static Plan *
    2117          42 : inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe)
    2118             : {
    2119             :     Plan       *plan;
    2120             : 
    2121          42 :     plan = (Plan *) make_result(tlist, NULL, subplan);
    2122             : 
    2123             :     /*
    2124             :      * In principle, we should charge tlist eval cost plus cpu_per_tuple per
    2125             :      * row for the Result node.  But the former has probably been factored in
    2126             :      * already and the latter was not accounted for during Path construction,
    2127             :      * so being formally correct might just make the EXPLAIN output look less
    2128             :      * consistent not more so.  Hence, just copy the subplan's cost.
    2129             :      */
    2130          42 :     copy_plan_costsize(plan, subplan);
    2131          42 :     plan->parallel_safe = parallel_safe;
    2132             : 
    2133          42 :     return plan;
    2134             : }
    2135             : 
    2136             : /*
    2137             :  * change_plan_targetlist
    2138             :  *    Externally available wrapper for inject_projection_plan.
    2139             :  *
    2140             :  * This is meant for use by FDW plan-generation functions, which might
    2141             :  * want to adjust the tlist computed by some subplan tree.  In general,
    2142             :  * a Result node is needed to compute the new tlist, but we can optimize
    2143             :  * some cases.
    2144             :  *
    2145             :  * In most cases, tlist_parallel_safe can just be passed as the parallel_safe
    2146             :  * flag of the FDW's own Path node.
    2147             :  */
    2148             : Plan *
    2149         196 : change_plan_targetlist(Plan *subplan, List *tlist, bool tlist_parallel_safe)
    2150             : {
    2151             :     /*
    2152             :      * If the top plan node can't do projections and its existing target list
    2153             :      * isn't already what we need, we need to add a Result node to help it
    2154             :      * along.
    2155             :      */
    2156         196 :     if (!is_projection_capable_plan(subplan) &&
    2157          24 :         !tlist_same_exprs(tlist, subplan->targetlist))
    2158          16 :         subplan = inject_projection_plan(subplan, tlist,
    2159          16 :                                          subplan->parallel_safe &&
    2160             :                                          tlist_parallel_safe);
    2161             :     else
    2162             :     {
    2163             :         /* Else we can just replace the plan node's tlist */
    2164         180 :         subplan->targetlist = tlist;
    2165         180 :         subplan->parallel_safe &= tlist_parallel_safe;
    2166             :     }
    2167         196 :     return subplan;
    2168             : }
    2169             : 
    2170             : /*
    2171             :  * create_sort_plan
    2172             :  *
    2173             :  *    Create a Sort plan for 'best_path' and (recursively) plans
    2174             :  *    for its subpaths.
    2175             :  */
    2176             : static Sort *
    2177       70230 : create_sort_plan(PlannerInfo *root, SortPath *best_path, int flags)
    2178             : {
    2179             :     Sort       *plan;
    2180             :     Plan       *subplan;
    2181             : 
    2182             :     /*
    2183             :      * We don't want any excess columns in the sorted tuples, so request a
    2184             :      * smaller tlist.  Otherwise, since Sort doesn't project, tlist
    2185             :      * requirements pass through.
    2186             :      */
    2187       70230 :     subplan = create_plan_recurse(root, best_path->subpath,
    2188             :                                   flags | CP_SMALL_TLIST);
    2189             : 
    2190             :     /*
    2191             :      * make_sort_from_pathkeys indirectly calls find_ec_member_matching_expr,
    2192             :      * which will ignore any child EC members that don't belong to the given
    2193             :      * relids. Thus, if this sort path is based on a child relation, we must
    2194             :      * pass its relids.
    2195             :      */
    2196       70230 :     plan = make_sort_from_pathkeys(subplan, best_path->path.pathkeys,
    2197       70230 :                                    IS_OTHER_REL(best_path->subpath->parent) ?
    2198         348 :                                    best_path->path.parent->relids : NULL);
    2199             : 
    2200       70230 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2201             : 
    2202       70230 :     return plan;
    2203             : }
    2204             : 
    2205             : /*
    2206             :  * create_incrementalsort_plan
    2207             :  *
    2208             :  *    Do the same as create_sort_plan, but create IncrementalSort plan.
    2209             :  */
    2210             : static IncrementalSort *
    2211         968 : create_incrementalsort_plan(PlannerInfo *root, IncrementalSortPath *best_path,
    2212             :                             int flags)
    2213             : {
    2214             :     IncrementalSort *plan;
    2215             :     Plan       *subplan;
    2216             : 
    2217             :     /* See comments in create_sort_plan() above */
    2218         968 :     subplan = create_plan_recurse(root, best_path->spath.subpath,
    2219             :                                   flags | CP_SMALL_TLIST);
    2220         968 :     plan = make_incrementalsort_from_pathkeys(subplan,
    2221             :                                               best_path->spath.path.pathkeys,
    2222         968 :                                               IS_OTHER_REL(best_path->spath.subpath->parent) ?
    2223           0 :                                               best_path->spath.path.parent->relids : NULL,
    2224             :                                               best_path->nPresortedCols);
    2225             : 
    2226         968 :     copy_generic_path_info(&plan->sort.plan, (Path *) best_path);
    2227             : 
    2228         968 :     return plan;
    2229             : }
    2230             : 
    2231             : /*
    2232             :  * create_group_plan
    2233             :  *
    2234             :  *    Create a Group plan for 'best_path' and (recursively) plans
    2235             :  *    for its subpaths.
    2236             :  */
    2237             : static Group *
    2238         246 : create_group_plan(PlannerInfo *root, GroupPath *best_path)
    2239             : {
    2240             :     Group      *plan;
    2241             :     Plan       *subplan;
    2242             :     List       *tlist;
    2243             :     List       *quals;
    2244             : 
    2245             :     /*
    2246             :      * Group can project, so no need to be terribly picky about child tlist,
    2247             :      * but we do need grouping columns to be available
    2248             :      */
    2249         246 :     subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
    2250             : 
    2251         246 :     tlist = build_path_tlist(root, &best_path->path);
    2252             : 
    2253         246 :     quals = order_qual_clauses(root, best_path->qual);
    2254             : 
    2255         492 :     plan = make_group(tlist,
    2256             :                       quals,
    2257         246 :                       list_length(best_path->groupClause),
    2258             :                       extract_grouping_cols(best_path->groupClause,
    2259             :                                             subplan->targetlist),
    2260             :                       extract_grouping_ops(best_path->groupClause),
    2261             :                       extract_grouping_collations(best_path->groupClause,
    2262             :                                                   subplan->targetlist),
    2263             :                       subplan);
    2264             : 
    2265         246 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2266             : 
    2267         246 :     return plan;
    2268             : }
    2269             : 
    2270             : /*
    2271             :  * create_upper_unique_plan
    2272             :  *
    2273             :  *    Create a Unique plan for 'best_path' and (recursively) plans
    2274             :  *    for its subpaths.
    2275             :  */
    2276             : static Unique *
    2277        5538 : create_upper_unique_plan(PlannerInfo *root, UpperUniquePath *best_path, int flags)
    2278             : {
    2279             :     Unique     *plan;
    2280             :     Plan       *subplan;
    2281             : 
    2282             :     /*
    2283             :      * Unique doesn't project, so tlist requirements pass through; moreover we
    2284             :      * need grouping columns to be labeled.
    2285             :      */
    2286        5538 :     subplan = create_plan_recurse(root, best_path->subpath,
    2287             :                                   flags | CP_LABEL_TLIST);
    2288             : 
    2289        5538 :     plan = make_unique_from_pathkeys(subplan,
    2290             :                                      best_path->path.pathkeys,
    2291             :                                      best_path->numkeys);
    2292             : 
    2293        5538 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2294             : 
    2295        5538 :     return plan;
    2296             : }
    2297             : 
    2298             : /*
    2299             :  * create_agg_plan
    2300             :  *
    2301             :  *    Create an Agg plan for 'best_path' and (recursively) plans
    2302             :  *    for its subpaths.
    2303             :  */
    2304             : static Agg *
    2305       40080 : create_agg_plan(PlannerInfo *root, AggPath *best_path)
    2306             : {
    2307             :     Agg        *plan;
    2308             :     Plan       *subplan;
    2309             :     List       *tlist;
    2310             :     List       *quals;
    2311             : 
    2312             :     /*
    2313             :      * Agg can project, so no need to be terribly picky about child tlist, but
    2314             :      * we do need grouping columns to be available
    2315             :      */
    2316       40080 :     subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
    2317             : 
    2318       40080 :     tlist = build_path_tlist(root, &best_path->path);
    2319             : 
    2320       40080 :     quals = order_qual_clauses(root, best_path->qual);
    2321             : 
    2322       80160 :     plan = make_agg(tlist, quals,
    2323             :                     best_path->aggstrategy,
    2324             :                     best_path->aggsplit,
    2325       40080 :                     list_length(best_path->groupClause),
    2326             :                     extract_grouping_cols(best_path->groupClause,
    2327             :                                           subplan->targetlist),
    2328             :                     extract_grouping_ops(best_path->groupClause),
    2329             :                     extract_grouping_collations(best_path->groupClause,
    2330             :                                                 subplan->targetlist),
    2331             :                     NIL,
    2332             :                     NIL,
    2333             :                     best_path->numGroups,
    2334             :                     best_path->transitionSpace,
    2335             :                     subplan);
    2336             : 
    2337       40080 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2338             : 
    2339       40080 :     return plan;
    2340             : }
    2341             : 
    2342             : /*
    2343             :  * Given a groupclause for a collection of grouping sets, produce the
    2344             :  * corresponding groupColIdx.
    2345             :  *
    2346             :  * root->grouping_map maps the tleSortGroupRef to the actual column position in
    2347             :  * the input tuple. So we get the ref from the entries in the groupclause and
    2348             :  * look them up there.
    2349             :  */
    2350             : static AttrNumber *
    2351        1846 : remap_groupColIdx(PlannerInfo *root, List *groupClause)
    2352             : {
    2353        1846 :     AttrNumber *grouping_map = root->grouping_map;
    2354             :     AttrNumber *new_grpColIdx;
    2355             :     ListCell   *lc;
    2356             :     int         i;
    2357             : 
    2358             :     Assert(grouping_map);
    2359             : 
    2360        1846 :     new_grpColIdx = palloc0(sizeof(AttrNumber) * list_length(groupClause));
    2361             : 
    2362        1846 :     i = 0;
    2363        4304 :     foreach(lc, groupClause)
    2364             :     {
    2365        2458 :         SortGroupClause *clause = lfirst(lc);
    2366             : 
    2367        2458 :         new_grpColIdx[i++] = grouping_map[clause->tleSortGroupRef];
    2368             :     }
    2369             : 
    2370        1846 :     return new_grpColIdx;
    2371             : }
    2372             : 
    2373             : /*
    2374             :  * create_groupingsets_plan
    2375             :  *    Create a plan for 'best_path' and (recursively) plans
    2376             :  *    for its subpaths.
    2377             :  *
    2378             :  *    What we emit is an Agg plan with some vestigial Agg and Sort nodes
    2379             :  *    hanging off the side.  The top Agg implements the last grouping set
    2380             :  *    specified in the GroupingSetsPath, and any additional grouping sets
    2381             :  *    each give rise to a subsidiary Agg and Sort node in the top Agg's
    2382             :  *    "chain" list.  These nodes don't participate in the plan directly,
    2383             :  *    but they are a convenient way to represent the required data for
    2384             :  *    the extra steps.
    2385             :  *
    2386             :  *    Returns a Plan node.
    2387             :  */
    2388             : static Plan *
    2389         860 : create_groupingsets_plan(PlannerInfo *root, GroupingSetsPath *best_path)
    2390             : {
    2391             :     Agg        *plan;
    2392             :     Plan       *subplan;
    2393         860 :     List       *rollups = best_path->rollups;
    2394             :     AttrNumber *grouping_map;
    2395             :     int         maxref;
    2396             :     List       *chain;
    2397             :     ListCell   *lc;
    2398             : 
    2399             :     /* Shouldn't get here without grouping sets */
    2400             :     Assert(root->parse->groupingSets);
    2401             :     Assert(rollups != NIL);
    2402             : 
    2403             :     /*
    2404             :      * Agg can project, so no need to be terribly picky about child tlist, but
    2405             :      * we do need grouping columns to be available
    2406             :      */
    2407         860 :     subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
    2408             : 
    2409             :     /*
    2410             :      * Compute the mapping from tleSortGroupRef to column index in the child's
    2411             :      * tlist.  First, identify max SortGroupRef in groupClause, for array
    2412             :      * sizing.
    2413             :      */
    2414         860 :     maxref = 0;
    2415        2684 :     foreach(lc, root->processed_groupClause)
    2416             :     {
    2417        1824 :         SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
    2418             : 
    2419        1824 :         if (gc->tleSortGroupRef > maxref)
    2420        1788 :             maxref = gc->tleSortGroupRef;
    2421             :     }
    2422             : 
    2423         860 :     grouping_map = (AttrNumber *) palloc0((maxref + 1) * sizeof(AttrNumber));
    2424             : 
    2425             :     /* Now look up the column numbers in the child's tlist */
    2426        2684 :     foreach(lc, root->processed_groupClause)
    2427             :     {
    2428        1824 :         SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
    2429        1824 :         TargetEntry *tle = get_sortgroupclause_tle(gc, subplan->targetlist);
    2430             : 
    2431        1824 :         grouping_map[gc->tleSortGroupRef] = tle->resno;
    2432             :     }
    2433             : 
    2434             :     /*
    2435             :      * During setrefs.c, we'll need the grouping_map to fix up the cols lists
    2436             :      * in GroupingFunc nodes.  Save it for setrefs.c to use.
    2437             :      */
    2438             :     Assert(root->grouping_map == NULL);
    2439         860 :     root->grouping_map = grouping_map;
    2440             : 
    2441             :     /*
    2442             :      * Generate the side nodes that describe the other sort and group
    2443             :      * operations besides the top one.  Note that we don't worry about putting
    2444             :      * accurate cost estimates in the side nodes; only the topmost Agg node's
    2445             :      * costs will be shown by EXPLAIN.
    2446             :      */
    2447         860 :     chain = NIL;
    2448         860 :     if (list_length(rollups) > 1)
    2449             :     {
    2450         584 :         bool        is_first_sort = ((RollupData *) linitial(rollups))->is_hashed;
    2451             : 
    2452        1570 :         for_each_from(lc, rollups, 1)
    2453             :         {
    2454         986 :             RollupData *rollup = lfirst(lc);
    2455             :             AttrNumber *new_grpColIdx;
    2456         986 :             Plan       *sort_plan = NULL;
    2457             :             Plan       *agg_plan;
    2458             :             AggStrategy strat;
    2459             : 
    2460         986 :             new_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
    2461             : 
    2462         986 :             if (!rollup->is_hashed && !is_first_sort)
    2463             :             {
    2464             :                 sort_plan = (Plan *)
    2465         240 :                     make_sort_from_groupcols(rollup->groupClause,
    2466             :                                              new_grpColIdx,
    2467             :                                              subplan);
    2468             :             }
    2469             : 
    2470         986 :             if (!rollup->is_hashed)
    2471         472 :                 is_first_sort = false;
    2472             : 
    2473         986 :             if (rollup->is_hashed)
    2474         514 :                 strat = AGG_HASHED;
    2475         472 :             else if (linitial(rollup->gsets) == NIL)
    2476         170 :                 strat = AGG_PLAIN;
    2477             :             else
    2478         302 :                 strat = AGG_SORTED;
    2479             : 
    2480        1972 :             agg_plan = (Plan *) make_agg(NIL,
    2481             :                                          NIL,
    2482             :                                          strat,
    2483             :                                          AGGSPLIT_SIMPLE,
    2484         986 :                                          list_length((List *) linitial(rollup->gsets)),
    2485             :                                          new_grpColIdx,
    2486             :                                          extract_grouping_ops(rollup->groupClause),
    2487             :                                          extract_grouping_collations(rollup->groupClause, subplan->targetlist),
    2488             :                                          rollup->gsets,
    2489             :                                          NIL,
    2490             :                                          rollup->numGroups,
    2491             :                                          best_path->transitionSpace,
    2492             :                                          sort_plan);
    2493             : 
    2494             :             /*
    2495             :              * Remove stuff we don't need to avoid bloating debug output.
    2496             :              */
    2497         986 :             if (sort_plan)
    2498             :             {
    2499         240 :                 sort_plan->targetlist = NIL;
    2500         240 :                 sort_plan->lefttree = NULL;
    2501             :             }
    2502             : 
    2503         986 :             chain = lappend(chain, agg_plan);
    2504             :         }
    2505             :     }
    2506             : 
    2507             :     /*
    2508             :      * Now make the real Agg node
    2509             :      */
    2510             :     {
    2511         860 :         RollupData *rollup = linitial(rollups);
    2512             :         AttrNumber *top_grpColIdx;
    2513             :         int         numGroupCols;
    2514             : 
    2515         860 :         top_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
    2516             : 
    2517         860 :         numGroupCols = list_length((List *) linitial(rollup->gsets));
    2518             : 
    2519         860 :         plan = make_agg(build_path_tlist(root, &best_path->path),
    2520             :                         best_path->qual,
    2521             :                         best_path->aggstrategy,
    2522             :                         AGGSPLIT_SIMPLE,
    2523             :                         numGroupCols,
    2524             :                         top_grpColIdx,
    2525             :                         extract_grouping_ops(rollup->groupClause),
    2526             :                         extract_grouping_collations(rollup->groupClause, subplan->targetlist),
    2527             :                         rollup->gsets,
    2528             :                         chain,
    2529             :                         rollup->numGroups,
    2530             :                         best_path->transitionSpace,
    2531             :                         subplan);
    2532             : 
    2533             :         /* Copy cost data from Path to Plan */
    2534         860 :         copy_generic_path_info(&plan->plan, &best_path->path);
    2535             :     }
    2536             : 
    2537         860 :     return (Plan *) plan;
    2538             : }
    2539             : 
    2540             : /*
    2541             :  * create_minmaxagg_plan
    2542             :  *
    2543             :  *    Create a Result plan for 'best_path' and (recursively) plans
    2544             :  *    for its subpaths.
    2545             :  */
    2546             : static Result *
    2547         364 : create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
    2548             : {
    2549             :     Result     *plan;
    2550             :     List       *tlist;
    2551             :     ListCell   *lc;
    2552             : 
    2553             :     /* Prepare an InitPlan for each aggregate's subquery. */
    2554         764 :     foreach(lc, best_path->mmaggregates)
    2555             :     {
    2556         400 :         MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
    2557         400 :         PlannerInfo *subroot = mminfo->subroot;
    2558         400 :         Query      *subparse = subroot->parse;
    2559             :         Plan       *plan;
    2560             : 
    2561             :         /*
    2562             :          * Generate the plan for the subquery. We already have a Path, but we
    2563             :          * have to convert it to a Plan and attach a LIMIT node above it.
    2564             :          * Since we are entering a different planner context (subroot),
    2565             :          * recurse to create_plan not create_plan_recurse.
    2566             :          */
    2567         400 :         plan = create_plan(subroot, mminfo->path);
    2568             : 
    2569         400 :         plan = (Plan *) make_limit(plan,
    2570             :                                    subparse->limitOffset,
    2571             :                                    subparse->limitCount,
    2572             :                                    subparse->limitOption,
    2573             :                                    0, NULL, NULL, NULL);
    2574             : 
    2575             :         /* Must apply correct cost/width data to Limit node */
    2576         400 :         plan->disabled_nodes = mminfo->path->disabled_nodes;
    2577         400 :         plan->startup_cost = mminfo->path->startup_cost;
    2578         400 :         plan->total_cost = mminfo->pathcost;
    2579         400 :         plan->plan_rows = 1;
    2580         400 :         plan->plan_width = mminfo->path->pathtarget->width;
    2581         400 :         plan->parallel_aware = false;
    2582         400 :         plan->parallel_safe = mminfo->path->parallel_safe;
    2583             : 
    2584             :         /* Convert the plan into an InitPlan in the outer query. */
    2585         400 :         SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
    2586             :     }
    2587             : 
    2588             :     /* Generate the output plan --- basically just a Result */
    2589         364 :     tlist = build_path_tlist(root, &best_path->path);
    2590             : 
    2591         364 :     plan = make_result(tlist, (Node *) best_path->quals, NULL);
    2592             : 
    2593         364 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2594             : 
    2595             :     /*
    2596             :      * During setrefs.c, we'll need to replace references to the Agg nodes
    2597             :      * with InitPlan output params.  (We can't just do that locally in the
    2598             :      * MinMaxAgg node, because path nodes above here may have Agg references
    2599             :      * as well.)  Save the mmaggregates list to tell setrefs.c to do that.
    2600             :      */
    2601             :     Assert(root->minmax_aggs == NIL);
    2602         364 :     root->minmax_aggs = best_path->mmaggregates;
    2603             : 
    2604         364 :     return plan;
    2605             : }
    2606             : 
    2607             : /*
    2608             :  * create_windowagg_plan
    2609             :  *
    2610             :  *    Create a WindowAgg plan for 'best_path' and (recursively) plans
    2611             :  *    for its subpaths.
    2612             :  */
    2613             : static WindowAgg *
    2614        2546 : create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path)
    2615             : {
    2616             :     WindowAgg  *plan;
    2617        2546 :     WindowClause *wc = best_path->winclause;
    2618        2546 :     int         numPart = list_length(wc->partitionClause);
    2619        2546 :     int         numOrder = list_length(wc->orderClause);
    2620             :     Plan       *subplan;
    2621             :     List       *tlist;
    2622             :     int         partNumCols;
    2623             :     AttrNumber *partColIdx;
    2624             :     Oid        *partOperators;
    2625             :     Oid        *partCollations;
    2626             :     int         ordNumCols;
    2627             :     AttrNumber *ordColIdx;
    2628             :     Oid        *ordOperators;
    2629             :     Oid        *ordCollations;
    2630             :     ListCell   *lc;
    2631             : 
    2632             :     /*
    2633             :      * Choice of tlist here is motivated by the fact that WindowAgg will be
    2634             :      * storing the input rows of window frames in a tuplestore; it therefore
    2635             :      * behooves us to request a small tlist to avoid wasting space. We do of
    2636             :      * course need grouping columns to be available.
    2637             :      */
    2638        2546 :     subplan = create_plan_recurse(root, best_path->subpath,
    2639             :                                   CP_LABEL_TLIST | CP_SMALL_TLIST);
    2640             : 
    2641        2546 :     tlist = build_path_tlist(root, &best_path->path);
    2642             : 
    2643             :     /*
    2644             :      * Convert SortGroupClause lists into arrays of attr indexes and equality
    2645             :      * operators, as wanted by executor.
    2646             :      */
    2647        2546 :     partColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numPart);
    2648        2546 :     partOperators = (Oid *) palloc(sizeof(Oid) * numPart);
    2649        2546 :     partCollations = (Oid *) palloc(sizeof(Oid) * numPart);
    2650             : 
    2651        2546 :     partNumCols = 0;
    2652        3278 :     foreach(lc, wc->partitionClause)
    2653             :     {
    2654         732 :         SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
    2655         732 :         TargetEntry *tle = get_sortgroupclause_tle(sgc, subplan->targetlist);
    2656             : 
    2657             :         Assert(OidIsValid(sgc->eqop));
    2658         732 :         partColIdx[partNumCols] = tle->resno;
    2659         732 :         partOperators[partNumCols] = sgc->eqop;
    2660         732 :         partCollations[partNumCols] = exprCollation((Node *) tle->expr);
    2661         732 :         partNumCols++;
    2662             :     }
    2663             : 
    2664        2546 :     ordColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numOrder);
    2665        2546 :     ordOperators = (Oid *) palloc(sizeof(Oid) * numOrder);
    2666        2546 :     ordCollations = (Oid *) palloc(sizeof(Oid) * numOrder);
    2667             : 
    2668        2546 :     ordNumCols = 0;
    2669        4722 :     foreach(lc, wc->orderClause)
    2670             :     {
    2671        2176 :         SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
    2672        2176 :         TargetEntry *tle = get_sortgroupclause_tle(sgc, subplan->targetlist);
    2673             : 
    2674             :         Assert(OidIsValid(sgc->eqop));
    2675        2176 :         ordColIdx[ordNumCols] = tle->resno;
    2676        2176 :         ordOperators[ordNumCols] = sgc->eqop;
    2677        2176 :         ordCollations[ordNumCols] = exprCollation((Node *) tle->expr);
    2678        2176 :         ordNumCols++;
    2679             :     }
    2680             : 
    2681             :     /* And finally we can make the WindowAgg node */
    2682        2546 :     plan = make_windowagg(tlist,
    2683             :                           wc,
    2684             :                           partNumCols,
    2685             :                           partColIdx,
    2686             :                           partOperators,
    2687             :                           partCollations,
    2688             :                           ordNumCols,
    2689             :                           ordColIdx,
    2690             :                           ordOperators,
    2691             :                           ordCollations,
    2692             :                           best_path->runCondition,
    2693             :                           best_path->qual,
    2694        2546 :                           best_path->topwindow,
    2695             :                           subplan);
    2696             : 
    2697        2546 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2698             : 
    2699        2546 :     return plan;
    2700             : }
    2701             : 
    2702             : /*
    2703             :  * create_setop_plan
    2704             :  *
    2705             :  *    Create a SetOp plan for 'best_path' and (recursively) plans
    2706             :  *    for its subpaths.
    2707             :  */
    2708             : static SetOp *
    2709         662 : create_setop_plan(PlannerInfo *root, SetOpPath *best_path, int flags)
    2710             : {
    2711             :     SetOp      *plan;
    2712         662 :     List       *tlist = build_path_tlist(root, &best_path->path);
    2713             :     Plan       *leftplan;
    2714             :     Plan       *rightplan;
    2715             :     long        numGroups;
    2716             : 
    2717             :     /*
    2718             :      * SetOp doesn't project, so tlist requirements pass through; moreover we
    2719             :      * need grouping columns to be labeled.
    2720             :      */
    2721         662 :     leftplan = create_plan_recurse(root, best_path->leftpath,
    2722             :                                    flags | CP_LABEL_TLIST);
    2723         662 :     rightplan = create_plan_recurse(root, best_path->rightpath,
    2724             :                                     flags | CP_LABEL_TLIST);
    2725             : 
    2726             :     /* Convert numGroups to long int --- but 'ware overflow! */
    2727         662 :     numGroups = clamp_cardinality_to_long(best_path->numGroups);
    2728             : 
    2729         662 :     plan = make_setop(best_path->cmd,
    2730             :                       best_path->strategy,
    2731             :                       tlist,
    2732             :                       leftplan,
    2733             :                       rightplan,
    2734             :                       best_path->groupList,
    2735             :                       numGroups);
    2736             : 
    2737         662 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2738             : 
    2739         662 :     return plan;
    2740             : }
    2741             : 
    2742             : /*
    2743             :  * create_recursiveunion_plan
    2744             :  *
    2745             :  *    Create a RecursiveUnion plan for 'best_path' and (recursively) plans
    2746             :  *    for its subpaths.
    2747             :  */
    2748             : static RecursiveUnion *
    2749        1004 : create_recursiveunion_plan(PlannerInfo *root, RecursiveUnionPath *best_path)
    2750             : {
    2751             :     RecursiveUnion *plan;
    2752             :     Plan       *leftplan;
    2753             :     Plan       *rightplan;
    2754             :     List       *tlist;
    2755             :     long        numGroups;
    2756             : 
    2757             :     /* Need both children to produce same tlist, so force it */
    2758        1004 :     leftplan = create_plan_recurse(root, best_path->leftpath, CP_EXACT_TLIST);
    2759        1004 :     rightplan = create_plan_recurse(root, best_path->rightpath, CP_EXACT_TLIST);
    2760             : 
    2761        1004 :     tlist = build_path_tlist(root, &best_path->path);
    2762             : 
    2763             :     /* Convert numGroups to long int --- but 'ware overflow! */
    2764        1004 :     numGroups = clamp_cardinality_to_long(best_path->numGroups);
    2765             : 
    2766        1004 :     plan = make_recursive_union(tlist,
    2767             :                                 leftplan,
    2768             :                                 rightplan,
    2769             :                                 best_path->wtParam,
    2770             :                                 best_path->distinctList,
    2771             :                                 numGroups);
    2772             : 
    2773        1004 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2774             : 
    2775        1004 :     return plan;
    2776             : }
    2777             : 
    2778             : /*
    2779             :  * create_lockrows_plan
    2780             :  *
    2781             :  *    Create a LockRows plan for 'best_path' and (recursively) plans
    2782             :  *    for its subpaths.
    2783             :  */
    2784             : static LockRows *
    2785        7744 : create_lockrows_plan(PlannerInfo *root, LockRowsPath *best_path,
    2786             :                      int flags)
    2787             : {
    2788             :     LockRows   *plan;
    2789             :     Plan       *subplan;
    2790             : 
    2791             :     /* LockRows doesn't project, so tlist requirements pass through */
    2792        7744 :     subplan = create_plan_recurse(root, best_path->subpath, flags);
    2793             : 
    2794        7744 :     plan = make_lockrows(subplan, best_path->rowMarks, best_path->epqParam);
    2795             : 
    2796        7744 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2797             : 
    2798        7744 :     return plan;
    2799             : }
    2800             : 
    2801             : /*
    2802             :  * create_modifytable_plan
    2803             :  *    Create a ModifyTable plan for 'best_path'.
    2804             :  *
    2805             :  *    Returns a Plan node.
    2806             :  */
    2807             : static ModifyTable *
    2808       89028 : create_modifytable_plan(PlannerInfo *root, ModifyTablePath *best_path)
    2809             : {
    2810             :     ModifyTable *plan;
    2811       89028 :     Path       *subpath = best_path->subpath;
    2812             :     Plan       *subplan;
    2813             : 
    2814             :     /* Subplan must produce exactly the specified tlist */
    2815       89028 :     subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
    2816             : 
    2817             :     /* Transfer resname/resjunk labeling, too, to keep executor happy */
    2818       89028 :     apply_tlist_labeling(subplan->targetlist, root->processed_tlist);
    2819             : 
    2820       89028 :     plan = make_modifytable(root,
    2821             :                             subplan,
    2822             :                             best_path->operation,
    2823       89028 :                             best_path->canSetTag,
    2824             :                             best_path->nominalRelation,
    2825             :                             best_path->rootRelation,
    2826       89028 :                             best_path->partColsUpdated,
    2827             :                             best_path->resultRelations,
    2828             :                             best_path->updateColnosLists,
    2829             :                             best_path->withCheckOptionLists,
    2830             :                             best_path->returningLists,
    2831             :                             best_path->rowMarks,
    2832             :                             best_path->onconflict,
    2833             :                             best_path->mergeActionLists,
    2834             :                             best_path->mergeJoinConditions,
    2835             :                             best_path->epqParam);
    2836             : 
    2837       88632 :     copy_generic_path_info(&plan->plan, &best_path->path);
    2838             : 
    2839       88632 :     return plan;
    2840             : }
    2841             : 
    2842             : /*
    2843             :  * create_limit_plan
    2844             :  *
    2845             :  *    Create a Limit plan for 'best_path' and (recursively) plans
    2846             :  *    for its subpaths.
    2847             :  */
    2848             : static Limit *
    2849        4402 : create_limit_plan(PlannerInfo *root, LimitPath *best_path, int flags)
    2850             : {
    2851             :     Limit      *plan;
    2852             :     Plan       *subplan;
    2853        4402 :     int         numUniqkeys = 0;
    2854        4402 :     AttrNumber *uniqColIdx = NULL;
    2855        4402 :     Oid        *uniqOperators = NULL;
    2856        4402 :     Oid        *uniqCollations = NULL;
    2857             : 
    2858             :     /* Limit doesn't project, so tlist requirements pass through */
    2859        4402 :     subplan = create_plan_recurse(root, best_path->subpath, flags);
    2860             : 
    2861             :     /* Extract information necessary for comparing rows for WITH TIES. */
    2862        4402 :     if (best_path->limitOption == LIMIT_OPTION_WITH_TIES)
    2863             :     {
    2864          30 :         Query      *parse = root->parse;
    2865             :         ListCell   *l;
    2866             : 
    2867          30 :         numUniqkeys = list_length(parse->sortClause);
    2868          30 :         uniqColIdx = (AttrNumber *) palloc(numUniqkeys * sizeof(AttrNumber));
    2869          30 :         uniqOperators = (Oid *) palloc(numUniqkeys * sizeof(Oid));
    2870          30 :         uniqCollations = (Oid *) palloc(numUniqkeys * sizeof(Oid));
    2871             : 
    2872          30 :         numUniqkeys = 0;
    2873          60 :         foreach(l, parse->sortClause)
    2874             :         {
    2875          30 :             SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
    2876          30 :             TargetEntry *tle = get_sortgroupclause_tle(sortcl, parse->targetList);
    2877             : 
    2878          30 :             uniqColIdx[numUniqkeys] = tle->resno;
    2879          30 :             uniqOperators[numUniqkeys] = sortcl->eqop;
    2880          30 :             uniqCollations[numUniqkeys] = exprCollation((Node *) tle->expr);
    2881          30 :             numUniqkeys++;
    2882             :         }
    2883             :     }
    2884             : 
    2885        4402 :     plan = make_limit(subplan,
    2886             :                       best_path->limitOffset,
    2887             :                       best_path->limitCount,
    2888             :                       best_path->limitOption,
    2889             :                       numUniqkeys, uniqColIdx, uniqOperators, uniqCollations);
    2890             : 
    2891        4402 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2892             : 
    2893        4402 :     return plan;
    2894             : }
    2895             : 
    2896             : 
    2897             : /*****************************************************************************
    2898             :  *
    2899             :  *  BASE-RELATION SCAN METHODS
    2900             :  *
    2901             :  *****************************************************************************/
    2902             : 
    2903             : 
    2904             : /*
    2905             :  * create_seqscan_plan
    2906             :  *   Returns a seqscan plan for the base relation scanned by 'best_path'
    2907             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    2908             :  */
    2909             : static SeqScan *
    2910      216142 : create_seqscan_plan(PlannerInfo *root, Path *best_path,
    2911             :                     List *tlist, List *scan_clauses)
    2912             : {
    2913             :     SeqScan    *scan_plan;
    2914      216142 :     Index       scan_relid = best_path->parent->relid;
    2915             : 
    2916             :     /* it should be a base rel... */
    2917             :     Assert(scan_relid > 0);
    2918             :     Assert(best_path->parent->rtekind == RTE_RELATION);
    2919             : 
    2920             :     /* Sort clauses into best execution order */
    2921      216142 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    2922             : 
    2923             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    2924      216142 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    2925             : 
    2926             :     /* Replace any outer-relation variables with nestloop params */
    2927      216142 :     if (best_path->param_info)
    2928             :     {
    2929             :         scan_clauses = (List *)
    2930         474 :             replace_nestloop_params(root, (Node *) scan_clauses);
    2931             :     }
    2932             : 
    2933      216142 :     scan_plan = make_seqscan(tlist,
    2934             :                              scan_clauses,
    2935             :                              scan_relid);
    2936             : 
    2937      216142 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    2938             : 
    2939      216142 :     return scan_plan;
    2940             : }
    2941             : 
    2942             : /*
    2943             :  * create_samplescan_plan
    2944             :  *   Returns a samplescan plan for the base relation scanned by 'best_path'
    2945             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    2946             :  */
    2947             : static SampleScan *
    2948         306 : create_samplescan_plan(PlannerInfo *root, Path *best_path,
    2949             :                        List *tlist, List *scan_clauses)
    2950             : {
    2951             :     SampleScan *scan_plan;
    2952         306 :     Index       scan_relid = best_path->parent->relid;
    2953             :     RangeTblEntry *rte;
    2954             :     TableSampleClause *tsc;
    2955             : 
    2956             :     /* it should be a base rel with a tablesample clause... */
    2957             :     Assert(scan_relid > 0);
    2958         306 :     rte = planner_rt_fetch(scan_relid, root);
    2959             :     Assert(rte->rtekind == RTE_RELATION);
    2960         306 :     tsc = rte->tablesample;
    2961             :     Assert(tsc != NULL);
    2962             : 
    2963             :     /* Sort clauses into best execution order */
    2964         306 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    2965             : 
    2966             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    2967         306 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    2968             : 
    2969             :     /* Replace any outer-relation variables with nestloop params */
    2970         306 :     if (best_path->param_info)
    2971             :     {
    2972             :         scan_clauses = (List *)
    2973          72 :             replace_nestloop_params(root, (Node *) scan_clauses);
    2974             :         tsc = (TableSampleClause *)
    2975          72 :             replace_nestloop_params(root, (Node *) tsc);
    2976             :     }
    2977             : 
    2978         306 :     scan_plan = make_samplescan(tlist,
    2979             :                                 scan_clauses,
    2980             :                                 scan_relid,
    2981             :                                 tsc);
    2982             : 
    2983         306 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    2984             : 
    2985         306 :     return scan_plan;
    2986             : }
    2987             : 
    2988             : /*
    2989             :  * create_indexscan_plan
    2990             :  *    Returns an indexscan plan for the base relation scanned by 'best_path'
    2991             :  *    with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    2992             :  *
    2993             :  * We use this for both plain IndexScans and IndexOnlyScans, because the
    2994             :  * qual preprocessing work is the same for both.  Note that the caller tells
    2995             :  * us which to build --- we don't look at best_path->path.pathtype, because
    2996             :  * create_bitmap_subplan needs to be able to override the prior decision.
    2997             :  */
    2998             : static Scan *
    2999      180764 : create_indexscan_plan(PlannerInfo *root,
    3000             :                       IndexPath *best_path,
    3001             :                       List *tlist,
    3002             :                       List *scan_clauses,
    3003             :                       bool indexonly)
    3004             : {
    3005             :     Scan       *scan_plan;
    3006      180764 :     List       *indexclauses = best_path->indexclauses;
    3007      180764 :     List       *indexorderbys = best_path->indexorderbys;
    3008      180764 :     Index       baserelid = best_path->path.parent->relid;
    3009      180764 :     IndexOptInfo *indexinfo = best_path->indexinfo;
    3010      180764 :     Oid         indexoid = indexinfo->indexoid;
    3011             :     List       *qpqual;
    3012             :     List       *stripped_indexquals;
    3013             :     List       *fixed_indexquals;
    3014             :     List       *fixed_indexorderbys;
    3015      180764 :     List       *indexorderbyops = NIL;
    3016             :     ListCell   *l;
    3017             : 
    3018             :     /* it should be a base rel... */
    3019             :     Assert(baserelid > 0);
    3020             :     Assert(best_path->path.parent->rtekind == RTE_RELATION);
    3021             :     /* check the scan direction is valid */
    3022             :     Assert(best_path->indexscandir == ForwardScanDirection ||
    3023             :            best_path->indexscandir == BackwardScanDirection);
    3024             : 
    3025             :     /*
    3026             :      * Extract the index qual expressions (stripped of RestrictInfos) from the
    3027             :      * IndexClauses list, and prepare a copy with index Vars substituted for
    3028             :      * table Vars.  (This step also does replace_nestloop_params on the
    3029             :      * fixed_indexquals.)
    3030             :      */
    3031      180764 :     fix_indexqual_references(root, best_path,
    3032             :                              &stripped_indexquals,
    3033             :                              &fixed_indexquals);
    3034             : 
    3035             :     /*
    3036             :      * Likewise fix up index attr references in the ORDER BY expressions.
    3037             :      */
    3038      180764 :     fixed_indexorderbys = fix_indexorderby_references(root, best_path);
    3039             : 
    3040             :     /*
    3041             :      * The qpqual list must contain all restrictions not automatically handled
    3042             :      * by the index, other than pseudoconstant clauses which will be handled
    3043             :      * by a separate gating plan node.  All the predicates in the indexquals
    3044             :      * will be checked (either by the index itself, or by nodeIndexscan.c),
    3045             :      * but if there are any "special" operators involved then they must be
    3046             :      * included in qpqual.  The upshot is that qpqual must contain
    3047             :      * scan_clauses minus whatever appears in indexquals.
    3048             :      *
    3049             :      * is_redundant_with_indexclauses() detects cases where a scan clause is
    3050             :      * present in the indexclauses list or is generated from the same
    3051             :      * EquivalenceClass as some indexclause, and is therefore redundant with
    3052             :      * it, though not equal.  (The latter happens when indxpath.c prefers a
    3053             :      * different derived equality than what generate_join_implied_equalities
    3054             :      * picked for a parameterized scan's ppi_clauses.)  Note that it will not
    3055             :      * match to lossy index clauses, which is critical because we have to
    3056             :      * include the original clause in qpqual in that case.
    3057             :      *
    3058             :      * In some situations (particularly with OR'd index conditions) we may
    3059             :      * have scan_clauses that are not equal to, but are logically implied by,
    3060             :      * the index quals; so we also try a predicate_implied_by() check to see
    3061             :      * if we can discard quals that way.  (predicate_implied_by assumes its
    3062             :      * first input contains only immutable functions, so we have to check
    3063             :      * that.)
    3064             :      *
    3065             :      * Note: if you change this bit of code you should also look at
    3066             :      * extract_nonindex_conditions() in costsize.c.
    3067             :      */
    3068      180764 :     qpqual = NIL;
    3069      434096 :     foreach(l, scan_clauses)
    3070             :     {
    3071      253332 :         RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
    3072             : 
    3073      253332 :         if (rinfo->pseudoconstant)
    3074        2130 :             continue;           /* we may drop pseudoconstants here */
    3075      251202 :         if (is_redundant_with_indexclauses(rinfo, indexclauses))
    3076      172928 :             continue;           /* dup or derived from same EquivalenceClass */
    3077      155156 :         if (!contain_mutable_functions((Node *) rinfo->clause) &&
    3078       76882 :             predicate_implied_by(list_make1(rinfo->clause), stripped_indexquals,
    3079             :                                  false))
    3080         186 :             continue;           /* provably implied by indexquals */
    3081       78088 :         qpqual = lappend(qpqual, rinfo);
    3082             :     }
    3083             : 
    3084             :     /* Sort clauses into best execution order */
    3085      180764 :     qpqual = order_qual_clauses(root, qpqual);
    3086             : 
    3087             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3088      180764 :     qpqual = extract_actual_clauses(qpqual, false);
    3089             : 
    3090             :     /*
    3091             :      * We have to replace any outer-relation variables with nestloop params in
    3092             :      * the indexqualorig, qpqual, and indexorderbyorig expressions.  A bit
    3093             :      * annoying to have to do this separately from the processing in
    3094             :      * fix_indexqual_references --- rethink this when generalizing the inner
    3095             :      * indexscan support.  But note we can't really do this earlier because
    3096             :      * it'd break the comparisons to predicates above ... (or would it?  Those
    3097             :      * wouldn't have outer refs)
    3098             :      */
    3099      180764 :     if (best_path->path.param_info)
    3100             :     {
    3101       38052 :         stripped_indexquals = (List *)
    3102       38052 :             replace_nestloop_params(root, (Node *) stripped_indexquals);
    3103             :         qpqual = (List *)
    3104       38052 :             replace_nestloop_params(root, (Node *) qpqual);
    3105             :         indexorderbys = (List *)
    3106       38052 :             replace_nestloop_params(root, (Node *) indexorderbys);
    3107             :     }
    3108             : 
    3109             :     /*
    3110             :      * If there are ORDER BY expressions, look up the sort operators for their
    3111             :      * result datatypes.
    3112             :      */
    3113      180764 :     if (indexorderbys)
    3114             :     {
    3115             :         ListCell   *pathkeyCell,
    3116             :                    *exprCell;
    3117             : 
    3118             :         /*
    3119             :          * PathKey contains OID of the btree opfamily we're sorting by, but
    3120             :          * that's not quite enough because we need the expression's datatype
    3121             :          * to look up the sort operator in the operator family.
    3122             :          */
    3123             :         Assert(list_length(best_path->path.pathkeys) == list_length(indexorderbys));
    3124         766 :         forboth(pathkeyCell, best_path->path.pathkeys, exprCell, indexorderbys)
    3125             :         {
    3126         386 :             PathKey    *pathkey = (PathKey *) lfirst(pathkeyCell);
    3127         386 :             Node       *expr = (Node *) lfirst(exprCell);
    3128         386 :             Oid         exprtype = exprType(expr);
    3129             :             Oid         sortop;
    3130             : 
    3131             :             /* Get sort operator from opfamily */
    3132         386 :             sortop = get_opfamily_member_for_cmptype(pathkey->pk_opfamily,
    3133             :                                                      exprtype,
    3134             :                                                      exprtype,
    3135             :                                                      pathkey->pk_cmptype);
    3136         386 :             if (!OidIsValid(sortop))
    3137           0 :                 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
    3138             :                      pathkey->pk_cmptype, exprtype, exprtype, pathkey->pk_opfamily);
    3139         386 :             indexorderbyops = lappend_oid(indexorderbyops, sortop);
    3140             :         }
    3141             :     }
    3142             : 
    3143             :     /*
    3144             :      * For an index-only scan, we must mark indextlist entries as resjunk if
    3145             :      * they are columns that the index AM can't return; this cues setrefs.c to
    3146             :      * not generate references to those columns.
    3147             :      */
    3148      180764 :     if (indexonly)
    3149             :     {
    3150       16348 :         int         i = 0;
    3151             : 
    3152       38840 :         foreach(l, indexinfo->indextlist)
    3153             :         {
    3154       22492 :             TargetEntry *indextle = (TargetEntry *) lfirst(l);
    3155             : 
    3156       22492 :             indextle->resjunk = !indexinfo->canreturn[i];
    3157       22492 :             i++;
    3158             :         }
    3159             :     }
    3160             : 
    3161             :     /* Finally ready to build the plan node */
    3162      180764 :     if (indexonly)
    3163       16348 :         scan_plan = (Scan *) make_indexonlyscan(tlist,
    3164             :                                                 qpqual,
    3165             :                                                 baserelid,
    3166             :                                                 indexoid,
    3167             :                                                 fixed_indexquals,
    3168             :                                                 stripped_indexquals,
    3169             :                                                 fixed_indexorderbys,
    3170             :                                                 indexinfo->indextlist,
    3171             :                                                 best_path->indexscandir);
    3172             :     else
    3173      164416 :         scan_plan = (Scan *) make_indexscan(tlist,
    3174             :                                             qpqual,
    3175             :                                             baserelid,
    3176             :                                             indexoid,
    3177             :                                             fixed_indexquals,
    3178             :                                             stripped_indexquals,
    3179             :                                             fixed_indexorderbys,
    3180             :                                             indexorderbys,
    3181             :                                             indexorderbyops,
    3182             :                                             best_path->indexscandir);
    3183             : 
    3184      180764 :     copy_generic_path_info(&scan_plan->plan, &best_path->path);
    3185             : 
    3186      180764 :     return scan_plan;
    3187             : }
    3188             : 
    3189             : /*
    3190             :  * create_bitmap_scan_plan
    3191             :  *    Returns a bitmap scan plan for the base relation scanned by 'best_path'
    3192             :  *    with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3193             :  */
    3194             : static BitmapHeapScan *
    3195       20656 : create_bitmap_scan_plan(PlannerInfo *root,
    3196             :                         BitmapHeapPath *best_path,
    3197             :                         List *tlist,
    3198             :                         List *scan_clauses)
    3199             : {
    3200       20656 :     Index       baserelid = best_path->path.parent->relid;
    3201             :     Plan       *bitmapqualplan;
    3202             :     List       *bitmapqualorig;
    3203             :     List       *indexquals;
    3204             :     List       *indexECs;
    3205             :     List       *qpqual;
    3206             :     ListCell   *l;
    3207             :     BitmapHeapScan *scan_plan;
    3208             : 
    3209             :     /* it should be a base rel... */
    3210             :     Assert(baserelid > 0);
    3211             :     Assert(best_path->path.parent->rtekind == RTE_RELATION);
    3212             : 
    3213             :     /* Process the bitmapqual tree into a Plan tree and qual lists */
    3214       20656 :     bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
    3215             :                                            &bitmapqualorig, &indexquals,
    3216             :                                            &indexECs);
    3217             : 
    3218       20656 :     if (best_path->path.parallel_aware)
    3219          30 :         bitmap_subplan_mark_shared(bitmapqualplan);
    3220             : 
    3221             :     /*
    3222             :      * The qpqual list must contain all restrictions not automatically handled
    3223             :      * by the index, other than pseudoconstant clauses which will be handled
    3224             :      * by a separate gating plan node.  All the predicates in the indexquals
    3225             :      * will be checked (either by the index itself, or by
    3226             :      * nodeBitmapHeapscan.c), but if there are any "special" operators
    3227             :      * involved then they must be added to qpqual.  The upshot is that qpqual
    3228             :      * must contain scan_clauses minus whatever appears in indexquals.
    3229             :      *
    3230             :      * This loop is similar to the comparable code in create_indexscan_plan(),
    3231             :      * but with some differences because it has to compare the scan clauses to
    3232             :      * stripped (no RestrictInfos) indexquals.  See comments there for more
    3233             :      * info.
    3234             :      *
    3235             :      * In normal cases simple equal() checks will be enough to spot duplicate
    3236             :      * clauses, so we try that first.  We next see if the scan clause is
    3237             :      * redundant with any top-level indexqual by virtue of being generated
    3238             :      * from the same EC.  After that, try predicate_implied_by().
    3239             :      *
    3240             :      * Unlike create_indexscan_plan(), the predicate_implied_by() test here is
    3241             :      * useful for getting rid of qpquals that are implied by index predicates,
    3242             :      * because the predicate conditions are included in the "indexquals"
    3243             :      * returned by create_bitmap_subplan().  Bitmap scans have to do it that
    3244             :      * way because predicate conditions need to be rechecked if the scan
    3245             :      * becomes lossy, so they have to be included in bitmapqualorig.
    3246             :      */
    3247       20656 :     qpqual = NIL;
    3248       48004 :     foreach(l, scan_clauses)
    3249             :     {
    3250       27348 :         RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
    3251       27348 :         Node       *clause = (Node *) rinfo->clause;
    3252             : 
    3253       27348 :         if (rinfo->pseudoconstant)
    3254          24 :             continue;           /* we may drop pseudoconstants here */
    3255       27324 :         if (list_member(indexquals, clause))
    3256       21162 :             continue;           /* simple duplicate */
    3257        6162 :         if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
    3258          16 :             continue;           /* derived from same EquivalenceClass */
    3259       12086 :         if (!contain_mutable_functions(clause) &&
    3260        5940 :             predicate_implied_by(list_make1(clause), indexquals, false))
    3261         662 :             continue;           /* provably implied by indexquals */
    3262        5484 :         qpqual = lappend(qpqual, rinfo);
    3263             :     }
    3264             : 
    3265             :     /* Sort clauses into best execution order */
    3266       20656 :     qpqual = order_qual_clauses(root, qpqual);
    3267             : 
    3268             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3269       20656 :     qpqual = extract_actual_clauses(qpqual, false);
    3270             : 
    3271             :     /*
    3272             :      * When dealing with special operators, we will at this point have
    3273             :      * duplicate clauses in qpqual and bitmapqualorig.  We may as well drop
    3274             :      * 'em from bitmapqualorig, since there's no point in making the tests
    3275             :      * twice.
    3276             :      */
    3277       20656 :     bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
    3278             : 
    3279             :     /*
    3280             :      * We have to replace any outer-relation variables with nestloop params in
    3281             :      * the qpqual and bitmapqualorig expressions.  (This was already done for
    3282             :      * expressions attached to plan nodes in the bitmapqualplan tree.)
    3283             :      */
    3284       20656 :     if (best_path->path.param_info)
    3285             :     {
    3286             :         qpqual = (List *)
    3287         630 :             replace_nestloop_params(root, (Node *) qpqual);
    3288         630 :         bitmapqualorig = (List *)
    3289         630 :             replace_nestloop_params(root, (Node *) bitmapqualorig);
    3290             :     }
    3291             : 
    3292             :     /* Finally ready to build the plan node */
    3293       20656 :     scan_plan = make_bitmap_heapscan(tlist,
    3294             :                                      qpqual,
    3295             :                                      bitmapqualplan,
    3296             :                                      bitmapqualorig,
    3297             :                                      baserelid);
    3298             : 
    3299       20656 :     copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
    3300             : 
    3301       20656 :     return scan_plan;
    3302             : }
    3303             : 
    3304             : /*
    3305             :  * Given a bitmapqual tree, generate the Plan tree that implements it
    3306             :  *
    3307             :  * As byproducts, we also return in *qual and *indexqual the qual lists
    3308             :  * (in implicit-AND form, without RestrictInfos) describing the original index
    3309             :  * conditions and the generated indexqual conditions.  (These are the same in
    3310             :  * simple cases, but when special index operators are involved, the former
    3311             :  * list includes the special conditions while the latter includes the actual
    3312             :  * indexable conditions derived from them.)  Both lists include partial-index
    3313             :  * predicates, because we have to recheck predicates as well as index
    3314             :  * conditions if the bitmap scan becomes lossy.
    3315             :  *
    3316             :  * In addition, we return a list of EquivalenceClass pointers for all the
    3317             :  * top-level indexquals that were possibly-redundantly derived from ECs.
    3318             :  * This allows removal of scan_clauses that are redundant with such quals.
    3319             :  * (We do not attempt to detect such redundancies for quals that are within
    3320             :  * OR subtrees.  This could be done in a less hacky way if we returned the
    3321             :  * indexquals in RestrictInfo form, but that would be slower and still pretty
    3322             :  * messy, since we'd have to build new RestrictInfos in many cases.)
    3323             :  */
    3324             : static Plan *
    3325       21890 : create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
    3326             :                       List **qual, List **indexqual, List **indexECs)
    3327             : {
    3328             :     Plan       *plan;
    3329             : 
    3330       21890 :     if (IsA(bitmapqual, BitmapAndPath))
    3331             :     {
    3332         222 :         BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
    3333         222 :         List       *subplans = NIL;
    3334         222 :         List       *subquals = NIL;
    3335         222 :         List       *subindexquals = NIL;
    3336         222 :         List       *subindexECs = NIL;
    3337             :         ListCell   *l;
    3338             : 
    3339             :         /*
    3340             :          * There may well be redundant quals among the subplans, since a
    3341             :          * top-level WHERE qual might have gotten used to form several
    3342             :          * different index quals.  We don't try exceedingly hard to eliminate
    3343             :          * redundancies, but we do eliminate obvious duplicates by using
    3344             :          * list_concat_unique.
    3345             :          */
    3346         666 :         foreach(l, apath->bitmapquals)
    3347             :         {
    3348             :             Plan       *subplan;
    3349             :             List       *subqual;
    3350             :             List       *subindexqual;
    3351             :             List       *subindexEC;
    3352             : 
    3353         444 :             subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
    3354             :                                             &subqual, &subindexqual,
    3355             :                                             &subindexEC);
    3356         444 :             subplans = lappend(subplans, subplan);
    3357         444 :             subquals = list_concat_unique(subquals, subqual);
    3358         444 :             subindexquals = list_concat_unique(subindexquals, subindexqual);
    3359             :             /* Duplicates in indexECs aren't worth getting rid of */
    3360         444 :             subindexECs = list_concat(subindexECs, subindexEC);
    3361             :         }
    3362         222 :         plan = (Plan *) make_bitmap_and(subplans);
    3363         222 :         plan->startup_cost = apath->path.startup_cost;
    3364         222 :         plan->total_cost = apath->path.total_cost;
    3365         222 :         plan->plan_rows =
    3366         222 :             clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
    3367         222 :         plan->plan_width = 0;    /* meaningless */
    3368         222 :         plan->parallel_aware = false;
    3369         222 :         plan->parallel_safe = apath->path.parallel_safe;
    3370         222 :         *qual = subquals;
    3371         222 :         *indexqual = subindexquals;
    3372         222 :         *indexECs = subindexECs;
    3373             :     }
    3374       21668 :     else if (IsA(bitmapqual, BitmapOrPath))
    3375             :     {
    3376         392 :         BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
    3377         392 :         List       *subplans = NIL;
    3378         392 :         List       *subquals = NIL;
    3379         392 :         List       *subindexquals = NIL;
    3380         392 :         bool        const_true_subqual = false;
    3381         392 :         bool        const_true_subindexqual = false;
    3382             :         ListCell   *l;
    3383             : 
    3384             :         /*
    3385             :          * Here, we only detect qual-free subplans.  A qual-free subplan would
    3386             :          * cause us to generate "... OR true ..."  which we may as well reduce
    3387             :          * to just "true".  We do not try to eliminate redundant subclauses
    3388             :          * because (a) it's not as likely as in the AND case, and (b) we might
    3389             :          * well be working with hundreds or even thousands of OR conditions,
    3390             :          * perhaps from a long IN list.  The performance of list_append_unique
    3391             :          * would be unacceptable.
    3392             :          */
    3393        1182 :         foreach(l, opath->bitmapquals)
    3394             :         {
    3395             :             Plan       *subplan;
    3396             :             List       *subqual;
    3397             :             List       *subindexqual;
    3398             :             List       *subindexEC;
    3399             : 
    3400         790 :             subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
    3401             :                                             &subqual, &subindexqual,
    3402             :                                             &subindexEC);
    3403         790 :             subplans = lappend(subplans, subplan);
    3404         790 :             if (subqual == NIL)
    3405           0 :                 const_true_subqual = true;
    3406         790 :             else if (!const_true_subqual)
    3407         790 :                 subquals = lappend(subquals,
    3408         790 :                                    make_ands_explicit(subqual));
    3409         790 :             if (subindexqual == NIL)
    3410           0 :                 const_true_subindexqual = true;
    3411         790 :             else if (!const_true_subindexqual)
    3412         790 :                 subindexquals = lappend(subindexquals,
    3413         790 :                                         make_ands_explicit(subindexqual));
    3414             :         }
    3415             : 
    3416             :         /*
    3417             :          * In the presence of ScalarArrayOpExpr quals, we might have built
    3418             :          * BitmapOrPaths with just one subpath; don't add an OR step.
    3419             :          */
    3420         392 :         if (list_length(subplans) == 1)
    3421             :         {
    3422           0 :             plan = (Plan *) linitial(subplans);
    3423             :         }
    3424             :         else
    3425             :         {
    3426         392 :             plan = (Plan *) make_bitmap_or(subplans);
    3427         392 :             plan->startup_cost = opath->path.startup_cost;
    3428         392 :             plan->total_cost = opath->path.total_cost;
    3429         392 :             plan->plan_rows =
    3430         392 :                 clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
    3431         392 :             plan->plan_width = 0;    /* meaningless */
    3432         392 :             plan->parallel_aware = false;
    3433         392 :             plan->parallel_safe = opath->path.parallel_safe;
    3434             :         }
    3435             : 
    3436             :         /*
    3437             :          * If there were constant-TRUE subquals, the OR reduces to constant
    3438             :          * TRUE.  Also, avoid generating one-element ORs, which could happen
    3439             :          * due to redundancy elimination or ScalarArrayOpExpr quals.
    3440             :          */
    3441         392 :         if (const_true_subqual)
    3442           0 :             *qual = NIL;
    3443         392 :         else if (list_length(subquals) <= 1)
    3444           0 :             *qual = subquals;
    3445             :         else
    3446         392 :             *qual = list_make1(make_orclause(subquals));
    3447         392 :         if (const_true_subindexqual)
    3448           0 :             *indexqual = NIL;
    3449         392 :         else if (list_length(subindexquals) <= 1)
    3450           0 :             *indexqual = subindexquals;
    3451             :         else
    3452         392 :             *indexqual = list_make1(make_orclause(subindexquals));
    3453         392 :         *indexECs = NIL;
    3454             :     }
    3455       21276 :     else if (IsA(bitmapqual, IndexPath))
    3456             :     {
    3457       21276 :         IndexPath  *ipath = (IndexPath *) bitmapqual;
    3458             :         IndexScan  *iscan;
    3459             :         List       *subquals;
    3460             :         List       *subindexquals;
    3461             :         List       *subindexECs;
    3462             :         ListCell   *l;
    3463             : 
    3464             :         /* Use the regular indexscan plan build machinery... */
    3465       21276 :         iscan = castNode(IndexScan,
    3466             :                          create_indexscan_plan(root, ipath,
    3467             :                                                NIL, NIL, false));
    3468             :         /* then convert to a bitmap indexscan */
    3469       21276 :         plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
    3470             :                                               iscan->indexid,
    3471             :                                               iscan->indexqual,
    3472             :                                               iscan->indexqualorig);
    3473             :         /* and set its cost/width fields appropriately */
    3474       21276 :         plan->startup_cost = 0.0;
    3475       21276 :         plan->total_cost = ipath->indextotalcost;
    3476       21276 :         plan->plan_rows =
    3477       21276 :             clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
    3478       21276 :         plan->plan_width = 0;    /* meaningless */
    3479       21276 :         plan->parallel_aware = false;
    3480       21276 :         plan->parallel_safe = ipath->path.parallel_safe;
    3481             :         /* Extract original index clauses, actual index quals, relevant ECs */
    3482       21276 :         subquals = NIL;
    3483       21276 :         subindexquals = NIL;
    3484       21276 :         subindexECs = NIL;
    3485       43722 :         foreach(l, ipath->indexclauses)
    3486             :         {
    3487       22446 :             IndexClause *iclause = (IndexClause *) lfirst(l);
    3488       22446 :             RestrictInfo *rinfo = iclause->rinfo;
    3489             : 
    3490             :             Assert(!rinfo->pseudoconstant);
    3491       22446 :             subquals = lappend(subquals, rinfo->clause);
    3492       22446 :             subindexquals = list_concat(subindexquals,
    3493       22446 :                                         get_actual_clauses(iclause->indexquals));
    3494       22446 :             if (rinfo->parent_ec)
    3495         480 :                 subindexECs = lappend(subindexECs, rinfo->parent_ec);
    3496             :         }
    3497             :         /* We can add any index predicate conditions, too */
    3498       21446 :         foreach(l, ipath->indexinfo->indpred)
    3499             :         {
    3500         170 :             Expr       *pred = (Expr *) lfirst(l);
    3501             : 
    3502             :             /*
    3503             :              * We know that the index predicate must have been implied by the
    3504             :              * query condition as a whole, but it may or may not be implied by
    3505             :              * the conditions that got pushed into the bitmapqual.  Avoid
    3506             :              * generating redundant conditions.
    3507             :              */
    3508         170 :             if (!predicate_implied_by(list_make1(pred), subquals, false))
    3509             :             {
    3510         140 :                 subquals = lappend(subquals, pred);
    3511         140 :                 subindexquals = lappend(subindexquals, pred);
    3512             :             }
    3513             :         }
    3514       21276 :         *qual = subquals;
    3515       21276 :         *indexqual = subindexquals;
    3516       21276 :         *indexECs = subindexECs;
    3517             :     }
    3518             :     else
    3519             :     {
    3520           0 :         elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
    3521             :         plan = NULL;            /* keep compiler quiet */
    3522             :     }
    3523             : 
    3524       21890 :     return plan;
    3525             : }
    3526             : 
    3527             : /*
    3528             :  * create_tidscan_plan
    3529             :  *   Returns a tidscan plan for the base relation scanned by 'best_path'
    3530             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3531             :  */
    3532             : static TidScan *
    3533         732 : create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
    3534             :                     List *tlist, List *scan_clauses)
    3535             : {
    3536             :     TidScan    *scan_plan;
    3537         732 :     Index       scan_relid = best_path->path.parent->relid;
    3538         732 :     List       *tidquals = best_path->tidquals;
    3539             : 
    3540             :     /* it should be a base rel... */
    3541             :     Assert(scan_relid > 0);
    3542             :     Assert(best_path->path.parent->rtekind == RTE_RELATION);
    3543             : 
    3544             :     /*
    3545             :      * The qpqual list must contain all restrictions not enforced by the
    3546             :      * tidquals list.  Since tidquals has OR semantics, we have to be careful
    3547             :      * about matching it up to scan_clauses.  It's convenient to handle the
    3548             :      * single-tidqual case separately from the multiple-tidqual case.  In the
    3549             :      * single-tidqual case, we look through the scan_clauses while they are
    3550             :      * still in RestrictInfo form, and drop any that are redundant with the
    3551             :      * tidqual.
    3552             :      *
    3553             :      * In normal cases simple pointer equality checks will be enough to spot
    3554             :      * duplicate RestrictInfos, so we try that first.
    3555             :      *
    3556             :      * Another common case is that a scan_clauses entry is generated from the
    3557             :      * same EquivalenceClass as some tidqual, and is therefore redundant with
    3558             :      * it, though not equal.
    3559             :      *
    3560             :      * Unlike indexpaths, we don't bother with predicate_implied_by(); the
    3561             :      * number of cases where it could win are pretty small.
    3562             :      */
    3563         732 :     if (list_length(tidquals) == 1)
    3564             :     {
    3565         708 :         List       *qpqual = NIL;
    3566             :         ListCell   *l;
    3567             : 
    3568        1500 :         foreach(l, scan_clauses)
    3569             :         {
    3570         792 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
    3571             : 
    3572         792 :             if (rinfo->pseudoconstant)
    3573           0 :                 continue;       /* we may drop pseudoconstants here */
    3574         792 :             if (list_member_ptr(tidquals, rinfo))
    3575         708 :                 continue;       /* simple duplicate */
    3576          84 :             if (is_redundant_derived_clause(rinfo, tidquals))
    3577           0 :                 continue;       /* derived from same EquivalenceClass */
    3578          84 :             qpqual = lappend(qpqual, rinfo);
    3579             :         }
    3580         708 :         scan_clauses = qpqual;
    3581             :     }
    3582             : 
    3583             :     /* Sort clauses into best execution order */
    3584         732 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3585             : 
    3586             :     /* Reduce RestrictInfo lists to bare expressions; ignore pseudoconstants */
    3587         732 :     tidquals = extract_actual_clauses(tidquals, false);
    3588         732 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3589             : 
    3590             :     /*
    3591             :      * If we have multiple tidquals, it's more convenient to remove duplicate
    3592             :      * scan_clauses after stripping the RestrictInfos.  In this situation,
    3593             :      * because the tidquals represent OR sub-clauses, they could not have come
    3594             :      * from EquivalenceClasses so we don't have to worry about matching up
    3595             :      * non-identical clauses.  On the other hand, because tidpath.c will have
    3596             :      * extracted those sub-clauses from some OR clause and built its own list,
    3597             :      * we will certainly not have pointer equality to any scan clause.  So
    3598             :      * convert the tidquals list to an explicit OR clause and see if we can
    3599             :      * match it via equal() to any scan clause.
    3600             :      */
    3601         732 :     if (list_length(tidquals) > 1)
    3602          24 :         scan_clauses = list_difference(scan_clauses,
    3603          24 :                                        list_make1(make_orclause(tidquals)));
    3604             : 
    3605             :     /* Replace any outer-relation variables with nestloop params */
    3606         732 :     if (best_path->path.param_info)
    3607             :     {
    3608             :         tidquals = (List *)
    3609          24 :             replace_nestloop_params(root, (Node *) tidquals);
    3610             :         scan_clauses = (List *)
    3611          24 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3612             :     }
    3613             : 
    3614         732 :     scan_plan = make_tidscan(tlist,
    3615             :                              scan_clauses,
    3616             :                              scan_relid,
    3617             :                              tidquals);
    3618             : 
    3619         732 :     copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
    3620             : 
    3621         732 :     return scan_plan;
    3622             : }
    3623             : 
    3624             : /*
    3625             :  * create_tidrangescan_plan
    3626             :  *   Returns a tidrangescan plan for the base relation scanned by 'best_path'
    3627             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3628             :  */
    3629             : static TidRangeScan *
    3630        1940 : create_tidrangescan_plan(PlannerInfo *root, TidRangePath *best_path,
    3631             :                          List *tlist, List *scan_clauses)
    3632             : {
    3633             :     TidRangeScan *scan_plan;
    3634        1940 :     Index       scan_relid = best_path->path.parent->relid;
    3635        1940 :     List       *tidrangequals = best_path->tidrangequals;
    3636             : 
    3637             :     /* it should be a base rel... */
    3638             :     Assert(scan_relid > 0);
    3639             :     Assert(best_path->path.parent->rtekind == RTE_RELATION);
    3640             : 
    3641             :     /*
    3642             :      * The qpqual list must contain all restrictions not enforced by the
    3643             :      * tidrangequals list.  tidrangequals has AND semantics, so we can simply
    3644             :      * remove any qual that appears in it.
    3645             :      */
    3646             :     {
    3647        1940 :         List       *qpqual = NIL;
    3648             :         ListCell   *l;
    3649             : 
    3650        3910 :         foreach(l, scan_clauses)
    3651             :         {
    3652        1970 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
    3653             : 
    3654        1970 :             if (rinfo->pseudoconstant)
    3655           0 :                 continue;       /* we may drop pseudoconstants here */
    3656        1970 :             if (list_member_ptr(tidrangequals, rinfo))
    3657        1970 :                 continue;       /* simple duplicate */
    3658           0 :             qpqual = lappend(qpqual, rinfo);
    3659             :         }
    3660        1940 :         scan_clauses = qpqual;
    3661             :     }
    3662             : 
    3663             :     /* Sort clauses into best execution order */
    3664        1940 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3665             : 
    3666             :     /* Reduce RestrictInfo lists to bare expressions; ignore pseudoconstants */
    3667        1940 :     tidrangequals = extract_actual_clauses(tidrangequals, false);
    3668        1940 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3669             : 
    3670             :     /* Replace any outer-relation variables with nestloop params */
    3671        1940 :     if (best_path->path.param_info)
    3672             :     {
    3673             :         tidrangequals = (List *)
    3674           0 :             replace_nestloop_params(root, (Node *) tidrangequals);
    3675             :         scan_clauses = (List *)
    3676           0 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3677             :     }
    3678             : 
    3679        1940 :     scan_plan = make_tidrangescan(tlist,
    3680             :                                   scan_clauses,
    3681             :                                   scan_relid,
    3682             :                                   tidrangequals);
    3683             : 
    3684        1940 :     copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
    3685             : 
    3686        1940 :     return scan_plan;
    3687             : }
    3688             : 
    3689             : /*
    3690             :  * create_subqueryscan_plan
    3691             :  *   Returns a subqueryscan plan for the base relation scanned by 'best_path'
    3692             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3693             :  */
    3694             : static SubqueryScan *
    3695       27752 : create_subqueryscan_plan(PlannerInfo *root, SubqueryScanPath *best_path,
    3696             :                          List *tlist, List *scan_clauses)
    3697             : {
    3698             :     SubqueryScan *scan_plan;
    3699       27752 :     RelOptInfo *rel = best_path->path.parent;
    3700       27752 :     Index       scan_relid = rel->relid;
    3701             :     Plan       *subplan;
    3702             : 
    3703             :     /* it should be a subquery base rel... */
    3704             :     Assert(scan_relid > 0);
    3705             :     Assert(rel->rtekind == RTE_SUBQUERY);
    3706             : 
    3707             :     /*
    3708             :      * Recursively create Plan from Path for subquery.  Since we are entering
    3709             :      * a different planner context (subroot), recurse to create_plan not
    3710             :      * create_plan_recurse.
    3711             :      */
    3712       27752 :     subplan = create_plan(rel->subroot, best_path->subpath);
    3713             : 
    3714             :     /* Sort clauses into best execution order */
    3715       27752 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3716             : 
    3717             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3718       27752 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3719             : 
    3720             :     /*
    3721             :      * Replace any outer-relation variables with nestloop params.
    3722             :      *
    3723             :      * We must provide nestloop params for both lateral references of the
    3724             :      * subquery and outer vars in the scan_clauses.  It's better to assign the
    3725             :      * former first, because that code path requires specific param IDs, while
    3726             :      * replace_nestloop_params can adapt to the IDs assigned by
    3727             :      * process_subquery_nestloop_params.  This avoids possibly duplicating
    3728             :      * nestloop params when the same Var is needed for both reasons.
    3729             :      */
    3730       27752 :     if (best_path->path.param_info)
    3731             :     {
    3732         550 :         process_subquery_nestloop_params(root,
    3733             :                                          rel->subplan_params);
    3734             :         scan_clauses = (List *)
    3735         550 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3736             :     }
    3737             : 
    3738       27752 :     scan_plan = make_subqueryscan(tlist,
    3739             :                                   scan_clauses,
    3740             :                                   scan_relid,
    3741             :                                   subplan);
    3742             : 
    3743       27752 :     copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
    3744             : 
    3745       27752 :     return scan_plan;
    3746             : }
    3747             : 
    3748             : /*
    3749             :  * create_functionscan_plan
    3750             :  *   Returns a functionscan plan for the base relation scanned by 'best_path'
    3751             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3752             :  */
    3753             : static FunctionScan *
    3754       51770 : create_functionscan_plan(PlannerInfo *root, Path *best_path,
    3755             :                          List *tlist, List *scan_clauses)
    3756             : {
    3757             :     FunctionScan *scan_plan;
    3758       51770 :     Index       scan_relid = best_path->parent->relid;
    3759             :     RangeTblEntry *rte;
    3760             :     List       *functions;
    3761             : 
    3762             :     /* it should be a function base rel... */
    3763             :     Assert(scan_relid > 0);
    3764       51770 :     rte = planner_rt_fetch(scan_relid, root);
    3765             :     Assert(rte->rtekind == RTE_FUNCTION);
    3766       51770 :     functions = rte->functions;
    3767             : 
    3768             :     /* Sort clauses into best execution order */
    3769       51770 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3770             : 
    3771             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3772       51770 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3773             : 
    3774             :     /* Replace any outer-relation variables with nestloop params */
    3775       51770 :     if (best_path->param_info)
    3776             :     {
    3777             :         scan_clauses = (List *)
    3778        8300 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3779             :         /* The function expressions could contain nestloop params, too */
    3780        8300 :         functions = (List *) replace_nestloop_params(root, (Node *) functions);
    3781             :     }
    3782             : 
    3783       51770 :     scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
    3784       51770 :                                   functions, rte->funcordinality);
    3785             : 
    3786       51770 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    3787             : 
    3788       51770 :     return scan_plan;
    3789             : }
    3790             : 
    3791             : /*
    3792             :  * create_tablefuncscan_plan
    3793             :  *   Returns a tablefuncscan plan for the base relation scanned by 'best_path'
    3794             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3795             :  */
    3796             : static TableFuncScan *
    3797         626 : create_tablefuncscan_plan(PlannerInfo *root, Path *best_path,
    3798             :                           List *tlist, List *scan_clauses)
    3799             : {
    3800             :     TableFuncScan *scan_plan;
    3801         626 :     Index       scan_relid = best_path->parent->relid;
    3802             :     RangeTblEntry *rte;
    3803             :     TableFunc  *tablefunc;
    3804             : 
    3805             :     /* it should be a function base rel... */
    3806             :     Assert(scan_relid > 0);
    3807         626 :     rte = planner_rt_fetch(scan_relid, root);
    3808             :     Assert(rte->rtekind == RTE_TABLEFUNC);
    3809         626 :     tablefunc = rte->tablefunc;
    3810             : 
    3811             :     /* Sort clauses into best execution order */
    3812         626 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3813             : 
    3814             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3815         626 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3816             : 
    3817             :     /* Replace any outer-relation variables with nestloop params */
    3818         626 :     if (best_path->param_info)
    3819             :     {
    3820             :         scan_clauses = (List *)
    3821         234 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3822             :         /* The function expressions could contain nestloop params, too */
    3823         234 :         tablefunc = (TableFunc *) replace_nestloop_params(root, (Node *) tablefunc);
    3824             :     }
    3825             : 
    3826         626 :     scan_plan = make_tablefuncscan(tlist, scan_clauses, scan_relid,
    3827             :                                    tablefunc);
    3828             : 
    3829         626 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    3830             : 
    3831         626 :     return scan_plan;
    3832             : }
    3833             : 
    3834             : /*
    3835             :  * create_valuesscan_plan
    3836             :  *   Returns a valuesscan plan for the base relation scanned by 'best_path'
    3837             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3838             :  */
    3839             : static ValuesScan *
    3840        8248 : create_valuesscan_plan(PlannerInfo *root, Path *best_path,
    3841             :                        List *tlist, List *scan_clauses)
    3842             : {
    3843             :     ValuesScan *scan_plan;
    3844        8248 :     Index       scan_relid = best_path->parent->relid;
    3845             :     RangeTblEntry *rte;
    3846             :     List       *values_lists;
    3847             : 
    3848             :     /* it should be a values base rel... */
    3849             :     Assert(scan_relid > 0);
    3850        8248 :     rte = planner_rt_fetch(scan_relid, root);
    3851             :     Assert(rte->rtekind == RTE_VALUES);
    3852        8248 :     values_lists = rte->values_lists;
    3853             : 
    3854             :     /* Sort clauses into best execution order */
    3855        8248 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3856             : 
    3857             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3858        8248 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3859             : 
    3860             :     /* Replace any outer-relation variables with nestloop params */
    3861        8248 :     if (best_path->param_info)
    3862             :     {
    3863             :         scan_clauses = (List *)
    3864          66 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3865             :         /* The values lists could contain nestloop params, too */
    3866             :         values_lists = (List *)
    3867          66 :             replace_nestloop_params(root, (Node *) values_lists);
    3868             :     }
    3869             : 
    3870        8248 :     scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid,
    3871             :                                 values_lists);
    3872             : 
    3873        8248 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    3874             : 
    3875        8248 :     return scan_plan;
    3876             : }
    3877             : 
    3878             : /*
    3879             :  * create_ctescan_plan
    3880             :  *   Returns a ctescan plan for the base relation scanned by 'best_path'
    3881             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3882             :  */
    3883             : static CteScan *
    3884        4082 : create_ctescan_plan(PlannerInfo *root, Path *best_path,
    3885             :                     List *tlist, List *scan_clauses)
    3886             : {
    3887             :     CteScan    *scan_plan;
    3888        4082 :     Index       scan_relid = best_path->parent->relid;
    3889             :     RangeTblEntry *rte;
    3890        4082 :     SubPlan    *ctesplan = NULL;
    3891             :     int         plan_id;
    3892             :     int         cte_param_id;
    3893             :     PlannerInfo *cteroot;
    3894             :     Index       levelsup;
    3895             :     int         ndx;
    3896             :     ListCell   *lc;
    3897             : 
    3898             :     Assert(scan_relid > 0);
    3899        4082 :     rte = planner_rt_fetch(scan_relid, root);
    3900             :     Assert(rte->rtekind == RTE_CTE);
    3901             :     Assert(!rte->self_reference);
    3902             : 
    3903             :     /*
    3904             :      * Find the referenced CTE, and locate the SubPlan previously made for it.
    3905             :      */
    3906        4082 :     levelsup = rte->ctelevelsup;
    3907        4082 :     cteroot = root;
    3908        7062 :     while (levelsup-- > 0)
    3909             :     {
    3910        2980 :         cteroot = cteroot->parent_root;
    3911        2980 :         if (!cteroot)           /* shouldn't happen */
    3912           0 :             elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
    3913             :     }
    3914             : 
    3915             :     /*
    3916             :      * Note: cte_plan_ids can be shorter than cteList, if we are still working
    3917             :      * on planning the CTEs (ie, this is a side-reference from another CTE).
    3918             :      * So we mustn't use forboth here.
    3919             :      */
    3920        4082 :     ndx = 0;
    3921        5666 :     foreach(lc, cteroot->parse->cteList)
    3922             :     {
    3923        5666 :         CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
    3924             : 
    3925        5666 :         if (strcmp(cte->ctename, rte->ctename) == 0)
    3926        4082 :             break;
    3927        1584 :         ndx++;
    3928             :     }
    3929        4082 :     if (lc == NULL)             /* shouldn't happen */
    3930           0 :         elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
    3931        4082 :     if (ndx >= list_length(cteroot->cte_plan_ids))
    3932           0 :         elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
    3933        4082 :     plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
    3934        4082 :     if (plan_id <= 0)
    3935           0 :         elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
    3936        4860 :     foreach(lc, cteroot->init_plans)
    3937             :     {
    3938        4860 :         ctesplan = (SubPlan *) lfirst(lc);
    3939        4860 :         if (ctesplan->plan_id == plan_id)
    3940        4082 :             break;
    3941             :     }
    3942        4082 :     if (lc == NULL)             /* shouldn't happen */
    3943           0 :         elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
    3944             : 
    3945             :     /*
    3946             :      * We need the CTE param ID, which is the sole member of the SubPlan's
    3947             :      * setParam list.
    3948             :      */
    3949        4082 :     cte_param_id = linitial_int(ctesplan->setParam);
    3950             : 
    3951             :     /* Sort clauses into best execution order */
    3952        4082 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3953             : 
    3954             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3955        4082 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3956             : 
    3957             :     /* Replace any outer-relation variables with nestloop params */
    3958        4082 :     if (best_path->param_info)
    3959             :     {
    3960             :         scan_clauses = (List *)
    3961           0 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3962             :     }
    3963             : 
    3964        4082 :     scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
    3965             :                              plan_id, cte_param_id);
    3966             : 
    3967        4082 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    3968             : 
    3969        4082 :     return scan_plan;
    3970             : }
    3971             : 
    3972             : /*
    3973             :  * create_namedtuplestorescan_plan
    3974             :  *   Returns a tuplestorescan plan for the base relation scanned by
    3975             :  *  'best_path' with restriction clauses 'scan_clauses' and targetlist
    3976             :  *  'tlist'.
    3977             :  */
    3978             : static NamedTuplestoreScan *
    3979         462 : create_namedtuplestorescan_plan(PlannerInfo *root, Path *best_path,
    3980             :                                 List *tlist, List *scan_clauses)
    3981             : {
    3982             :     NamedTuplestoreScan *scan_plan;
    3983         462 :     Index       scan_relid = best_path->parent->relid;
    3984             :     RangeTblEntry *rte;
    3985             : 
    3986             :     Assert(scan_relid > 0);
    3987         462 :     rte = planner_rt_fetch(scan_relid, root);
    3988             :     Assert(rte->rtekind == RTE_NAMEDTUPLESTORE);
    3989             : 
    3990             :     /* Sort clauses into best execution order */
    3991         462 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3992             : 
    3993             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3994         462 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3995             : 
    3996             :     /* Replace any outer-relation variables with nestloop params */
    3997         462 :     if (best_path->param_info)
    3998             :     {
    3999             :         scan_clauses = (List *)
    4000           0 :             replace_nestloop_params(root, (Node *) scan_clauses);
    4001             :     }
    4002             : 
    4003         462 :     scan_plan = make_namedtuplestorescan(tlist, scan_clauses, scan_relid,
    4004             :                                          rte->enrname);
    4005             : 
    4006         462 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    4007             : 
    4008         462 :     return scan_plan;
    4009             : }
    4010             : 
    4011             : /*
    4012             :  * create_resultscan_plan
    4013             :  *   Returns a Result plan for the RTE_RESULT base relation scanned by
    4014             :  *  'best_path' with restriction clauses 'scan_clauses' and targetlist
    4015             :  *  'tlist'.
    4016             :  */
    4017             : static Result *
    4018        4086 : create_resultscan_plan(PlannerInfo *root, Path *best_path,
    4019             :                        List *tlist, List *scan_clauses)
    4020             : {
    4021             :     Result     *scan_plan;
    4022        4086 :     Index       scan_relid = best_path->parent->relid;
    4023             :     RangeTblEntry *rte PG_USED_FOR_ASSERTS_ONLY;
    4024             : 
    4025             :     Assert(scan_relid > 0);
    4026        4086 :     rte = planner_rt_fetch(scan_relid, root);
    4027             :     Assert(rte->rtekind == RTE_RESULT);
    4028             : 
    4029             :     /* Sort clauses into best execution order */
    4030        4086 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    4031             : 
    4032             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    4033        4086 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    4034             : 
    4035             :     /* Replace any outer-relation variables with nestloop params */
    4036        4086 :     if (best_path->param_info)
    4037             :     {
    4038             :         scan_clauses = (List *)
    4039         138 :             replace_nestloop_params(root, (Node *) scan_clauses);
    4040             :     }
    4041             : 
    4042        4086 :     scan_plan = make_result(tlist, (Node *) scan_clauses, NULL);
    4043             : 
    4044        4086 :     copy_generic_path_info(&scan_plan->plan, best_path);
    4045             : 
    4046        4086 :     return scan_plan;
    4047             : }
    4048             : 
    4049             : /*
    4050             :  * create_worktablescan_plan
    4051             :  *   Returns a worktablescan plan for the base relation scanned by 'best_path'
    4052             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    4053             :  */
    4054             : static WorkTableScan *
    4055        1004 : create_worktablescan_plan(PlannerInfo *root, Path *best_path,
    4056             :                           List *tlist, List *scan_clauses)
    4057             : {
    4058             :     WorkTableScan *scan_plan;
    4059        1004 :     Index       scan_relid = best_path->parent->relid;
    4060             :     RangeTblEntry *rte;
    4061             :     Index       levelsup;
    4062             :     PlannerInfo *cteroot;
    4063             : 
    4064             :     Assert(scan_relid > 0);
    4065        1004 :     rte = planner_rt_fetch(scan_relid, root);
    4066             :     Assert(rte->rtekind == RTE_CTE);
    4067             :     Assert(rte->self_reference);
    4068             : 
    4069             :     /*
    4070             :      * We need to find the worktable param ID, which is in the plan level
    4071             :      * that's processing the recursive UNION, which is one level *below* where
    4072             :      * the CTE comes from.
    4073             :      */
    4074        1004 :     levelsup = rte->ctelevelsup;
    4075        1004 :     if (levelsup == 0)          /* shouldn't happen */
    4076           0 :         elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
    4077        1004 :     levelsup--;
    4078        1004 :     cteroot = root;
    4079        2364 :     while (levelsup-- > 0)
    4080             :     {
    4081        1360 :         cteroot = cteroot->parent_root;
    4082        1360 :         if (!cteroot)           /* shouldn't happen */
    4083           0 :             elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
    4084             :     }
    4085        1004 :     if (cteroot->wt_param_id < 0) /* shouldn't happen */
    4086           0 :         elog(ERROR, "could not find param ID for CTE \"%s\"", rte->ctename);
    4087             : 
    4088             :     /* Sort clauses into best execution order */
    4089        1004 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    4090             : 
    4091             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    4092        1004 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    4093             : 
    4094             :     /* Replace any outer-relation variables with nestloop params */
    4095        1004 :     if (best_path->param_info)
    4096             :     {
    4097             :         scan_clauses = (List *)
    4098           0 :             replace_nestloop_params(root, (Node *) scan_clauses);
    4099             :     }
    4100             : 
    4101        1004 :     scan_plan = make_worktablescan(tlist, scan_clauses, scan_relid,
    4102             :                                    cteroot->wt_param_id);
    4103             : 
    4104        1004 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    4105             : 
    4106        1004 :     return scan_plan;
    4107             : }
    4108             : 
    4109             : /*
    4110             :  * create_foreignscan_plan
    4111             :  *   Returns a foreignscan plan for the relation scanned by 'best_path'
    4112             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    4113             :  */
    4114             : static ForeignScan *
    4115        2046 : create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
    4116             :                         List *tlist, List *scan_clauses)
    4117             : {
    4118             :     ForeignScan *scan_plan;
    4119        2046 :     RelOptInfo *rel = best_path->path.parent;
    4120        2046 :     Index       scan_relid = rel->relid;
    4121        2046 :     Oid         rel_oid = InvalidOid;
    4122        2046 :     Plan       *outer_plan = NULL;
    4123             : 
    4124             :     Assert(rel->fdwroutine != NULL);
    4125             : 
    4126             :     /* transform the child path if any */
    4127        2046 :     if (best_path->fdw_outerpath)
    4128          48 :         outer_plan = create_plan_recurse(root, best_path->fdw_outerpath,
    4129             :                                          CP_EXACT_TLIST);
    4130             : 
    4131             :     /*
    4132             :      * If we're scanning a base relation, fetch its OID.  (Irrelevant if
    4133             :      * scanning a join relation.)
    4134             :      */
    4135        2046 :     if (scan_relid > 0)
    4136             :     {
    4137             :         RangeTblEntry *rte;
    4138             : 
    4139             :         Assert(rel->rtekind == RTE_RELATION);
    4140        1484 :         rte = planner_rt_fetch(scan_relid, root);
    4141             :         Assert(rte->rtekind == RTE_RELATION);
    4142        1484 :         rel_oid = rte->relid;
    4143             :     }
    4144             : 
    4145             :     /*
    4146             :      * Sort clauses into best execution order.  We do this first since the FDW
    4147             :      * might have more info than we do and wish to adjust the ordering.
    4148             :      */
    4149        2046 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    4150             : 
    4151             :     /*
    4152             :      * Let the FDW perform its processing on the restriction clauses and
    4153             :      * generate the plan node.  Note that the FDW might remove restriction
    4154             :      * clauses that it intends to execute remotely, or even add more (if it
    4155             :      * has selected some join clauses for remote use but also wants them
    4156             :      * rechecked locally).
    4157             :      */
    4158        2046 :     scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid,
    4159             :                                                 best_path,
    4160             :                                                 tlist, scan_clauses,
    4161             :                                                 outer_plan);
    4162             : 
    4163             :     /* Copy cost data from Path to Plan; no need to make FDW do this */
    4164        2046 :     copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
    4165             : 
    4166             :     /* Copy user OID to access as; likewise no need to make FDW do this */
    4167        2046 :     scan_plan->checkAsUser = rel->userid;
    4168             : 
    4169             :     /* Copy foreign server OID; likewise, no need to make FDW do this */
    4170        2046 :     scan_plan->fs_server = rel->serverid;
    4171             : 
    4172             :     /*
    4173             :      * Likewise, copy the relids that are represented by this foreign scan. An
    4174             :      * upper rel doesn't have relids set, but it covers all the relations
    4175             :      * participating in the underlying scan/join, so use root->all_query_rels.
    4176             :      */
    4177        2046 :     if (rel->reloptkind == RELOPT_UPPER_REL)
    4178         240 :         scan_plan->fs_relids = root->all_query_rels;
    4179             :     else
    4180        1806 :         scan_plan->fs_relids = best_path->path.parent->relids;
    4181             : 
    4182             :     /*
    4183             :      * Join relid sets include relevant outer joins, but FDWs may need to know
    4184             :      * which are the included base rels.  That's a bit tedious to get without
    4185             :      * access to the plan-time data structures, so compute it here.
    4186             :      */
    4187        4092 :     scan_plan->fs_base_relids = bms_difference(scan_plan->fs_relids,
    4188        2046 :                                                root->outer_join_rels);
    4189             : 
    4190             :     /*
    4191             :      * If this is a foreign join, and to make it valid to push down we had to
    4192             :      * assume that the current user is the same as some user explicitly named
    4193             :      * in the query, mark the finished plan as depending on the current user.
    4194             :      */
    4195        2046 :     if (rel->useridiscurrent)
    4196           4 :         root->glob->dependsOnRole = true;
    4197             : 
    4198             :     /*
    4199             :      * Replace any outer-relation variables with nestloop params in the qual,
    4200             :      * fdw_exprs and fdw_recheck_quals expressions.  We do this last so that
    4201             :      * the FDW doesn't have to be involved.  (Note that parts of fdw_exprs or
    4202             :      * fdw_recheck_quals could have come from join clauses, so doing this
    4203             :      * beforehand on the scan_clauses wouldn't work.)  We assume
    4204             :      * fdw_scan_tlist contains no such variables.
    4205             :      */
    4206        2046 :     if (best_path->path.param_info)
    4207             :     {
    4208          26 :         scan_plan->scan.plan.qual = (List *)
    4209          26 :             replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
    4210          26 :         scan_plan->fdw_exprs = (List *)
    4211          26 :             replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
    4212          26 :         scan_plan->fdw_recheck_quals = (List *)
    4213          26 :             replace_nestloop_params(root,
    4214          26 :                                     (Node *) scan_plan->fdw_recheck_quals);
    4215             :     }
    4216             : 
    4217             :     /*
    4218             :      * If rel is a base relation, detect whether any system columns are
    4219             :      * requested from the rel.  (If rel is a join relation, rel->relid will be
    4220             :      * 0, but there can be no Var with relid 0 in the rel's targetlist or the
    4221             :      * restriction clauses, so we skip this in that case.  Note that any such
    4222             :      * columns in base relations that were joined are assumed to be contained
    4223             :      * in fdw_scan_tlist.)  This is a bit of a kluge and might go away
    4224             :      * someday, so we intentionally leave it out of the API presented to FDWs.
    4225             :      */
    4226        2046 :     scan_plan->fsSystemCol = false;
    4227        2046 :     if (scan_relid > 0)
    4228             :     {
    4229        1484 :         Bitmapset  *attrs_used = NULL;
    4230             :         ListCell   *lc;
    4231             :         int         i;
    4232             : 
    4233             :         /*
    4234             :          * First, examine all the attributes needed for joins or final output.
    4235             :          * Note: we must look at rel's targetlist, not the attr_needed data,
    4236             :          * because attr_needed isn't computed for inheritance child rels.
    4237             :          */
    4238        1484 :         pull_varattnos((Node *) rel->reltarget->exprs, scan_relid, &attrs_used);
    4239             : 
    4240             :         /* Add all the attributes used by restriction clauses. */
    4241        2188 :         foreach(lc, rel->baserestrictinfo)
    4242             :         {
    4243         704 :             RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
    4244             : 
    4245         704 :             pull_varattnos((Node *) rinfo->clause, scan_relid, &attrs_used);
    4246             :         }
    4247             : 
    4248             :         /* Now, are any system columns requested from rel? */
    4249        8442 :         for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
    4250             :         {
    4251        7484 :             if (bms_is_member(i - FirstLowInvalidHeapAttributeNumber, attrs_used))
    4252             :             {
    4253         526 :                 scan_plan->fsSystemCol = true;
    4254         526 :                 break;
    4255             :             }
    4256             :         }
    4257             : 
    4258        1484 :         bms_free(attrs_used);
    4259             :     }
    4260             : 
    4261        2046 :     return scan_plan;
    4262             : }
    4263             : 
    4264             : /*
    4265             :  * create_customscan_plan
    4266             :  *
    4267             :  * Transform a CustomPath into a Plan.
    4268             :  */
    4269             : static CustomScan *
    4270           0 : create_customscan_plan(PlannerInfo *root, CustomPath *best_path,
    4271             :                        List *tlist, List *scan_clauses)
    4272             : {
    4273             :     CustomScan *cplan;
    4274           0 :     RelOptInfo *rel = best_path->path.parent;
    4275           0 :     List       *custom_plans = NIL;
    4276             :     ListCell   *lc;
    4277             : 
    4278             :     /* Recursively transform child paths. */
    4279           0 :     foreach(lc, best_path->custom_paths)
    4280             :     {
    4281           0 :         Plan       *plan = create_plan_recurse(root, (Path *) lfirst(lc),
    4282             :                                                CP_EXACT_TLIST);
    4283             : 
    4284           0 :         custom_plans = lappend(custom_plans, plan);
    4285             :     }
    4286             : 
    4287             :     /*
    4288             :      * Sort clauses into the best execution order, although custom-scan
    4289             :      * provider can reorder them again.
    4290             :      */
    4291           0 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    4292             : 
    4293             :     /*
    4294             :      * Invoke custom plan provider to create the Plan node represented by the
    4295             :      * CustomPath.
    4296             :      */
    4297           0 :     cplan = castNode(CustomScan,
    4298             :                      best_path->methods->PlanCustomPath(root,
    4299             :                                                         rel,
    4300             :                                                         best_path,
    4301             :                                                         tlist,
    4302             :                                                         scan_clauses,
    4303             :                                                         custom_plans));
    4304             : 
    4305             :     /*
    4306             :      * Copy cost data from Path to Plan; no need to make custom-plan providers
    4307             :      * do this
    4308             :      */
    4309           0 :     copy_generic_path_info(&cplan->scan.plan, &best_path->path);
    4310             : 
    4311             :     /* Likewise, copy the relids that are represented by this custom scan */
    4312           0 :     cplan->custom_relids = best_path->path.parent->relids;
    4313             : 
    4314             :     /*
    4315             :      * Replace any outer-relation variables with nestloop params in the qual
    4316             :      * and custom_exprs expressions.  We do this last so that the custom-plan
    4317             :      * provider doesn't have to be involved.  (Note that parts of custom_exprs
    4318             :      * could have come from join clauses, so doing this beforehand on the
    4319             :      * scan_clauses wouldn't work.)  We assume custom_scan_tlist contains no
    4320             :      * such variables.
    4321             :      */
    4322           0 :     if (best_path->path.param_info)
    4323             :     {
    4324           0 :         cplan->scan.plan.qual = (List *)
    4325           0 :             replace_nestloop_params(root, (Node *) cplan->scan.plan.qual);
    4326           0 :         cplan->custom_exprs = (List *)
    4327           0 :             replace_nestloop_params(root, (Node *) cplan->custom_exprs);
    4328             :     }
    4329             : 
    4330           0 :     return cplan;
    4331             : }
    4332             : 
    4333             : 
    4334             : /*****************************************************************************
    4335             :  *
    4336             :  *  JOIN METHODS
    4337             :  *
    4338             :  *****************************************************************************/
    4339             : 
    4340             : static NestLoop *
    4341       94430 : create_nestloop_plan(PlannerInfo *root,
    4342             :                      NestPath *best_path)
    4343             : {
    4344             :     NestLoop   *join_plan;
    4345             :     Plan       *outer_plan;
    4346             :     Plan       *inner_plan;
    4347             :     Relids      outerrelids;
    4348       94430 :     List       *tlist = build_path_tlist(root, &best_path->jpath.path);
    4349       94430 :     List       *joinrestrictclauses = best_path->jpath.joinrestrictinfo;
    4350             :     List       *joinclauses;
    4351             :     List       *otherclauses;
    4352             :     List       *nestParams;
    4353             :     List       *outer_tlist;
    4354             :     bool        outer_parallel_safe;
    4355       94430 :     Relids      saveOuterRels = root->curOuterRels;
    4356             :     ListCell   *lc;
    4357             : 
    4358             :     /*
    4359             :      * If the inner path is parameterized by the topmost parent of the outer
    4360             :      * rel rather than the outer rel itself, fix that.  (Nothing happens here
    4361             :      * if it is not so parameterized.)
    4362             :      */
    4363       94430 :     best_path->jpath.innerjoinpath =
    4364       94430 :         reparameterize_path_by_child(root,
    4365             :                                      best_path->jpath.innerjoinpath,
    4366       94430 :                                      best_path->jpath.outerjoinpath->parent);
    4367             : 
    4368             :     /*
    4369             :      * Failure here probably means that reparameterize_path_by_child() is not
    4370             :      * in sync with path_is_reparameterizable_by_child().
    4371             :      */
    4372             :     Assert(best_path->jpath.innerjoinpath != NULL);
    4373             : 
    4374             :     /* NestLoop can project, so no need to be picky about child tlists */
    4375       94430 :     outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath, 0);
    4376             : 
    4377             :     /* For a nestloop, include outer relids in curOuterRels for inner side */
    4378       94430 :     outerrelids = best_path->jpath.outerjoinpath->parent->relids;
    4379       94430 :     root->curOuterRels = bms_union(root->curOuterRels, outerrelids);
    4380             : 
    4381       94430 :     inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath, 0);
    4382             : 
    4383             :     /* Restore curOuterRels */
    4384       94430 :     bms_free(root->curOuterRels);
    4385       94430 :     root->curOuterRels = saveOuterRels;
    4386             : 
    4387             :     /* Sort join qual clauses into best execution order */
    4388       94430 :     joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
    4389             : 
    4390             :     /* Get the join qual clauses (in plain expression form) */
    4391             :     /* Any pseudoconstant clauses are ignored here */
    4392       94430 :     if (IS_OUTER_JOIN(best_path->jpath.jointype))
    4393             :     {
    4394       22872 :         extract_actual_join_clauses(joinrestrictclauses,
    4395       22872 :                                     best_path->jpath.path.parent->relids,
    4396             :                                     &joinclauses, &otherclauses);
    4397             :     }
    4398             :     else
    4399             :     {
    4400             :         /* We can treat all clauses alike for an inner join */
    4401       71558 :         joinclauses = extract_actual_clauses(joinrestrictclauses, false);
    4402       71558 :         otherclauses = NIL;
    4403             :     }
    4404             : 
    4405             :     /* Replace any outer-relation variables with nestloop params */
    4406       94430 :     if (best_path->jpath.path.param_info)
    4407             :     {
    4408         946 :         joinclauses = (List *)
    4409         946 :             replace_nestloop_params(root, (Node *) joinclauses);
    4410         946 :         otherclauses = (List *)
    4411         946 :             replace_nestloop_params(root, (Node *) otherclauses);
    4412             :     }
    4413             : 
    4414             :     /*
    4415             :      * Identify any nestloop parameters that should be supplied by this join
    4416             :      * node, and remove them from root->curOuterParams.
    4417             :      */
    4418       94430 :     nestParams = identify_current_nestloop_params(root,
    4419             :                                                   outerrelids,
    4420       94430 :                                                   PATH_REQ_OUTER((Path *) best_path));
    4421             : 
    4422             :     /*
    4423             :      * While nestloop parameters that are Vars had better be available from
    4424             :      * the outer_plan already, there are edge cases where nestloop parameters
    4425             :      * that are PHVs won't be.  In such cases we must add them to the
    4426             :      * outer_plan's tlist, since the executor's NestLoopParam machinery
    4427             :      * requires the params to be simple outer-Var references to that tlist.
    4428             :      * (This is cheating a little bit, because the outer path's required-outer
    4429             :      * relids might not be enough to allow evaluating such a PHV.  But in
    4430             :      * practice, if we could have evaluated the PHV at the nestloop node, we
    4431             :      * can do so in the outer plan too.)
    4432             :      */
    4433       94430 :     outer_tlist = outer_plan->targetlist;
    4434       94430 :     outer_parallel_safe = outer_plan->parallel_safe;
    4435      147018 :     foreach(lc, nestParams)
    4436             :     {
    4437       52588 :         NestLoopParam *nlp = (NestLoopParam *) lfirst(lc);
    4438             :         PlaceHolderVar *phv;
    4439             :         TargetEntry *tle;
    4440             : 
    4441       52588 :         if (IsA(nlp->paramval, Var))
    4442       52336 :             continue;           /* nothing to do for simple Vars */
    4443             :         /* Otherwise it must be a PHV */
    4444         252 :         phv = castNode(PlaceHolderVar, nlp->paramval);
    4445             : 
    4446         252 :         if (tlist_member((Expr *) phv, outer_tlist))
    4447         222 :             continue;           /* already available */
    4448             : 
    4449             :         /*
    4450             :          * It's possible that nestloop parameter PHVs selected to evaluate
    4451             :          * here contain references to surviving root->curOuterParams items
    4452             :          * (that is, they reference values that will be supplied by some
    4453             :          * higher-level nestloop).  Those need to be converted to Params now.
    4454             :          * Note: it's safe to do this after the tlist_member() check, because
    4455             :          * equal() won't pay attention to phv->phexpr.
    4456             :          */
    4457          60 :         phv->phexpr = (Expr *) replace_nestloop_params(root,
    4458          30 :                                                        (Node *) phv->phexpr);
    4459             : 
    4460             :         /* Make a shallow copy of outer_tlist, if we didn't already */
    4461          30 :         if (outer_tlist == outer_plan->targetlist)
    4462          30 :             outer_tlist = list_copy(outer_tlist);
    4463             :         /* ... and add the needed expression */
    4464          30 :         tle = makeTargetEntry((Expr *) copyObject(phv),
    4465          30 :                               list_length(outer_tlist) + 1,
    4466             :                               NULL,
    4467             :                               true);
    4468          30 :         outer_tlist = lappend(outer_tlist, tle);
    4469             :         /* ... and track whether tlist is (still) parallel-safe */
    4470          30 :         if (outer_parallel_safe)
    4471           6 :             outer_parallel_safe = is_parallel_safe(root, (Node *) phv);
    4472             :     }
    4473       94430 :     if (outer_tlist != outer_plan->targetlist)
    4474          30 :         outer_plan = change_plan_targetlist(outer_plan, outer_tlist,
    4475             :                                             outer_parallel_safe);
    4476             : 
    4477             :     /* And finally, we can build the join plan node */
    4478       94430 :     join_plan = make_nestloop(tlist,
    4479             :                               joinclauses,
    4480             :                               otherclauses,
    4481             :                               nestParams,
    4482             :                               outer_plan,
    4483             :                               inner_plan,
    4484             :                               best_path->jpath.jointype,
    4485       94430 :                               best_path->jpath.inner_unique);
    4486             : 
    4487       94430 :     copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
    4488             : 
    4489       94430 :     return join_plan;
    4490             : }
    4491             : 
    4492             : static MergeJoin *
    4493        8070 : create_mergejoin_plan(PlannerInfo *root,
    4494             :                       MergePath *best_path)
    4495             : {
    4496             :     MergeJoin  *join_plan;
    4497             :     Plan       *outer_plan;
    4498             :     Plan       *inner_plan;
    4499        8070 :     List       *tlist = build_path_tlist(root, &best_path->jpath.path);
    4500             :     List       *joinclauses;
    4501             :     List       *otherclauses;
    4502             :     List       *mergeclauses;
    4503             :     List       *outerpathkeys;
    4504             :     List       *innerpathkeys;
    4505             :     int         nClauses;
    4506             :     Oid        *mergefamilies;
    4507             :     Oid        *mergecollations;
    4508             :     bool       *mergereversals;
    4509             :     bool       *mergenullsfirst;
    4510             :     PathKey    *opathkey;
    4511             :     EquivalenceClass *opeclass;
    4512             :     int         i;
    4513             :     ListCell   *lc;
    4514             :     ListCell   *lop;
    4515             :     ListCell   *lip;
    4516        8070 :     Path       *outer_path = best_path->jpath.outerjoinpath;
    4517        8070 :     Path       *inner_path = best_path->jpath.innerjoinpath;
    4518             : 
    4519             :     /*
    4520             :      * MergeJoin can project, so we don't have to demand exact tlists from the
    4521             :      * inputs.  However, if we're intending to sort an input's result, it's
    4522             :      * best to request a small tlist so we aren't sorting more data than
    4523             :      * necessary.
    4524             :      */
    4525        8070 :     outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
    4526        8070 :                                      (best_path->outersortkeys != NIL) ? CP_SMALL_TLIST : 0);
    4527             : 
    4528        8070 :     inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
    4529        8070 :                                      (best_path->innersortkeys != NIL) ? CP_SMALL_TLIST : 0);
    4530             : 
    4531             :     /* Sort join qual clauses into best execution order */
    4532             :     /* NB: do NOT reorder the mergeclauses */
    4533        8070 :     joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
    4534             : 
    4535             :     /* Get the join qual clauses (in plain expression form) */
    4536             :     /* Any pseudoconstant clauses are ignored here */
    4537        8070 :     if (IS_OUTER_JOIN(best_path->jpath.jointype))
    4538             :     {
    4539        5614 :         extract_actual_join_clauses(joinclauses,
    4540        5614 :                                     best_path->jpath.path.parent->relids,
    4541             :                                     &joinclauses, &otherclauses);
    4542             :     }
    4543             :     else
    4544             :     {
    4545             :         /* We can treat all clauses alike for an inner join */
    4546        2456 :         joinclauses = extract_actual_clauses(joinclauses, false);
    4547        2456 :         otherclauses = NIL;
    4548             :     }
    4549             : 
    4550             :     /*
    4551             :      * Remove the mergeclauses from the list of join qual clauses, leaving the
    4552             :      * list of quals that must be checked as qpquals.
    4553             :      */
    4554        8070 :     mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
    4555        8070 :     joinclauses = list_difference(joinclauses, mergeclauses);
    4556             : 
    4557             :     /*
    4558             :      * Replace any outer-relation variables with nestloop params.  There
    4559             :      * should not be any in the mergeclauses.
    4560             :      */
    4561        8070 :     if (best_path->jpath.path.param_info)
    4562             :     {
    4563           6 :         joinclauses = (List *)
    4564           6 :             replace_nestloop_params(root, (Node *) joinclauses);
    4565           6 :         otherclauses = (List *)
    4566           6 :             replace_nestloop_params(root, (Node *) otherclauses);
    4567             :     }
    4568             : 
    4569             :     /*
    4570             :      * Rearrange mergeclauses, if needed, so that the outer variable is always
    4571             :      * on the left; mark the mergeclause restrictinfos with correct
    4572             :      * outer_is_left status.
    4573             :      */
    4574        8070 :     mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
    4575        8070 :                                         best_path->jpath.outerjoinpath->parent->relids);
    4576             : 
    4577             :     /*
    4578             :      * Create explicit sort nodes for the outer and inner paths if necessary.
    4579             :      */
    4580        8070 :     if (best_path->outersortkeys)
    4581             :     {
    4582        3204 :         Relids      outer_relids = outer_path->parent->relids;
    4583             :         Plan       *sort_plan;
    4584             : 
    4585             :         /*
    4586             :          * We can assert that the outer path is not already ordered
    4587             :          * appropriately for the mergejoin; otherwise, outersortkeys would
    4588             :          * have been set to NIL.
    4589             :          */
    4590             :         Assert(!pathkeys_contained_in(best_path->outersortkeys,
    4591             :                                       outer_path->pathkeys));
    4592             : 
    4593             :         /*
    4594             :          * We choose to use incremental sort if it is enabled and there are
    4595             :          * presorted keys; otherwise we use full sort.
    4596             :          */
    4597        3204 :         if (enable_incremental_sort && best_path->outer_presorted_keys > 0)
    4598             :         {
    4599             :             sort_plan = (Plan *)
    4600          12 :                 make_incrementalsort_from_pathkeys(outer_plan,
    4601             :                                                    best_path->outersortkeys,
    4602             :                                                    outer_relids,
    4603             :                                                    best_path->outer_presorted_keys);
    4604             : 
    4605          12 :             label_incrementalsort_with_costsize(root,
    4606             :                                                 (IncrementalSort *) sort_plan,
    4607             :                                                 best_path->outersortkeys,
    4608             :                                                 -1.0);
    4609             :         }
    4610             :         else
    4611             :         {
    4612             :             sort_plan = (Plan *)
    4613        3192 :                 make_sort_from_pathkeys(outer_plan,
    4614             :                                         best_path->outersortkeys,
    4615             :                                         outer_relids);
    4616             : 
    4617        3192 :             label_sort_with_costsize(root, (Sort *) sort_plan, -1.0);
    4618             :         }
    4619             : 
    4620        3204 :         outer_plan = sort_plan;
    4621        3204 :         outerpathkeys = best_path->outersortkeys;
    4622             :     }
    4623             :     else
    4624        4866 :         outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
    4625             : 
    4626        8070 :     if (best_path->innersortkeys)
    4627             :     {
    4628             :         /*
    4629             :          * We do not consider incremental sort for inner path, because
    4630             :          * incremental sort does not support mark/restore.
    4631             :          */
    4632             : 
    4633        7592 :         Relids      inner_relids = inner_path->parent->relids;
    4634             :         Sort       *sort;
    4635             : 
    4636             :         /*
    4637             :          * We can assert that the inner path is not already ordered
    4638             :          * appropriately for the mergejoin; otherwise, innersortkeys would
    4639             :          * have been set to NIL.
    4640             :          */
    4641             :         Assert(!pathkeys_contained_in(best_path->innersortkeys,
    4642             :                                       inner_path->pathkeys));
    4643             : 
    4644        7592 :         sort = make_sort_from_pathkeys(inner_plan,
    4645             :                                        best_path->innersortkeys,
    4646             :                                        inner_relids);
    4647             : 
    4648        7592 :         label_sort_with_costsize(root, sort, -1.0);
    4649        7592 :         inner_plan = (Plan *) sort;
    4650        7592 :         innerpathkeys = best_path->innersortkeys;
    4651             :     }
    4652             :     else
    4653         478 :         innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
    4654             : 
    4655             :     /*
    4656             :      * If specified, add a materialize node to shield the inner plan from the
    4657             :      * need to handle mark/restore.
    4658             :      */
    4659        8070 :     if (best_path->materialize_inner)
    4660             :     {
    4661         170 :         Plan       *matplan = (Plan *) make_material(inner_plan);
    4662             : 
    4663             :         /*
    4664             :          * We assume the materialize will not spill to disk, and therefore
    4665             :          * charge just cpu_operator_cost per tuple.  (Keep this estimate in
    4666             :          * sync with final_cost_mergejoin.)
    4667             :          */
    4668         170 :         copy_plan_costsize(matplan, inner_plan);
    4669         170 :         matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
    4670             : 
    4671         170 :         inner_plan = matplan;
    4672             :     }
    4673             : 
    4674             :     /*
    4675             :      * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
    4676             :      * executor.  The information is in the pathkeys for the two inputs, but
    4677             :      * we need to be careful about the possibility of mergeclauses sharing a
    4678             :      * pathkey, as well as the possibility that the inner pathkeys are not in
    4679             :      * an order matching the mergeclauses.
    4680             :      */
    4681        8070 :     nClauses = list_length(mergeclauses);
    4682             :     Assert(nClauses == list_length(best_path->path_mergeclauses));
    4683        8070 :     mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
    4684        8070 :     mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
    4685        8070 :     mergereversals = (bool *) palloc(nClauses * sizeof(bool));
    4686        8070 :     mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
    4687             : 
    4688        8070 :     opathkey = NULL;
    4689        8070 :     opeclass = NULL;
    4690        8070 :     lop = list_head(outerpathkeys);
    4691        8070 :     lip = list_head(innerpathkeys);
    4692        8070 :     i = 0;
    4693       17210 :     foreach(lc, best_path->path_mergeclauses)
    4694             :     {
    4695        9140 :         RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
    4696             :         EquivalenceClass *oeclass;
    4697             :         EquivalenceClass *ieclass;
    4698        9140 :         PathKey    *ipathkey = NULL;
    4699        9140 :         EquivalenceClass *ipeclass = NULL;
    4700        9140 :         bool        first_inner_match = false;
    4701             : 
    4702             :         /* fetch outer/inner eclass from mergeclause */
    4703        9140 :         if (rinfo->outer_is_left)
    4704             :         {
    4705        7362 :             oeclass = rinfo->left_ec;
    4706        7362 :             ieclass = rinfo->right_ec;
    4707             :         }
    4708             :         else
    4709             :         {
    4710        1778 :             oeclass = rinfo->right_ec;
    4711        1778 :             ieclass = rinfo->left_ec;
    4712             :         }
    4713             :         Assert(oeclass != NULL);
    4714             :         Assert(ieclass != NULL);
    4715             : 
    4716             :         /*
    4717             :          * We must identify the pathkey elements associated with this clause
    4718             :          * by matching the eclasses (which should give a unique match, since
    4719             :          * the pathkey lists should be canonical).  In typical cases the merge
    4720             :          * clauses are one-to-one with the pathkeys, but when dealing with
    4721             :          * partially redundant query conditions, things are more complicated.
    4722             :          *
    4723             :          * lop and lip reference the first as-yet-unmatched pathkey elements.
    4724             :          * If they're NULL then all pathkey elements have been matched.
    4725             :          *
    4726             :          * The ordering of the outer pathkeys should match the mergeclauses,
    4727             :          * by construction (see find_mergeclauses_for_outer_pathkeys()). There
    4728             :          * could be more than one mergeclause for the same outer pathkey, but
    4729             :          * no pathkey may be entirely skipped over.
    4730             :          */
    4731        9140 :         if (oeclass != opeclass)    /* multiple matches are not interesting */
    4732             :         {
    4733             :             /* doesn't match the current opathkey, so must match the next */
    4734        9128 :             if (lop == NULL)
    4735           0 :                 elog(ERROR, "outer pathkeys do not match mergeclauses");
    4736        9128 :             opathkey = (PathKey *) lfirst(lop);
    4737        9128 :             opeclass = opathkey->pk_eclass;
    4738        9128 :             lop = lnext(outerpathkeys, lop);
    4739        9128 :             if (oeclass != opeclass)
    4740           0 :                 elog(ERROR, "outer pathkeys do not match mergeclauses");
    4741             :         }
    4742             : 
    4743             :         /*
    4744             :          * The inner pathkeys likewise should not have skipped-over keys, but
    4745             :          * it's possible for a mergeclause to reference some earlier inner
    4746             :          * pathkey if we had redundant pathkeys.  For example we might have
    4747             :          * mergeclauses like "o.a = i.x AND o.b = i.y AND o.c = i.x".  The
    4748             :          * implied inner ordering is then "ORDER BY x, y, x", but the pathkey
    4749             :          * mechanism drops the second sort by x as redundant, and this code
    4750             :          * must cope.
    4751             :          *
    4752             :          * It's also possible for the implied inner-rel ordering to be like
    4753             :          * "ORDER BY x, y, x DESC".  We still drop the second instance of x as
    4754             :          * redundant; but this means that the sort ordering of a redundant
    4755             :          * inner pathkey should not be considered significant.  So we must
    4756             :          * detect whether this is the first clause matching an inner pathkey.
    4757             :          */
    4758        9140 :         if (lip)
    4759             :         {
    4760        9122 :             ipathkey = (PathKey *) lfirst(lip);
    4761        9122 :             ipeclass = ipathkey->pk_eclass;
    4762        9122 :             if (ieclass == ipeclass)
    4763             :             {
    4764             :                 /* successful first match to this inner pathkey */
    4765        9122 :                 lip = lnext(innerpathkeys, lip);
    4766        9122 :                 first_inner_match = true;
    4767             :             }
    4768             :         }
    4769        9140 :         if (!first_inner_match)
    4770             :         {
    4771             :             /* redundant clause ... must match something before lip */
    4772             :             ListCell   *l2;
    4773             : 
    4774          18 :             foreach(l2, innerpathkeys)
    4775             :             {
    4776          18 :                 if (l2 == lip)
    4777           0 :                     break;
    4778          18 :                 ipathkey = (PathKey *) lfirst(l2);
    4779          18 :                 ipeclass = ipathkey->pk_eclass;
    4780          18 :                 if (ieclass == ipeclass)
    4781          18 :                     break;
    4782             :             }
    4783          18 :             if (ieclass != ipeclass)
    4784           0 :                 elog(ERROR, "inner pathkeys do not match mergeclauses");
    4785             :         }
    4786             : 
    4787             :         /*
    4788             :          * The pathkeys should always match each other as to opfamily and
    4789             :          * collation (which affect equality), but if we're considering a
    4790             :          * redundant inner pathkey, its sort ordering might not match.  In
    4791             :          * such cases we may ignore the inner pathkey's sort ordering and use
    4792             :          * the outer's.  (In effect, we're lying to the executor about the
    4793             :          * sort direction of this inner column, but it does not matter since
    4794             :          * the run-time row comparisons would only reach this column when
    4795             :          * there's equality for the earlier column containing the same eclass.
    4796             :          * There could be only one value in this column for the range of inner
    4797             :          * rows having a given value in the earlier column, so it does not
    4798             :          * matter which way we imagine this column to be ordered.)  But a
    4799             :          * non-redundant inner pathkey had better match outer's ordering too.
    4800             :          */
    4801        9140 :         if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
    4802        9140 :             opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation)
    4803           0 :             elog(ERROR, "left and right pathkeys do not match in mergejoin");
    4804        9140 :         if (first_inner_match &&
    4805        9122 :             (opathkey->pk_cmptype != ipathkey->pk_cmptype ||
    4806        9122 :              opathkey->pk_nulls_first != ipathkey->pk_nulls_first))
    4807           0 :             elog(ERROR, "left and right pathkeys do not match in mergejoin");
    4808             : 
    4809             :         /* OK, save info for executor */
    4810        9140 :         mergefamilies[i] = opathkey->pk_opfamily;
    4811        9140 :         mergecollations[i] = opathkey->pk_eclass->ec_collation;
    4812        9140 :         mergereversals[i] = (opathkey->pk_cmptype == COMPARE_GT ? true : false);
    4813        9140 :         mergenullsfirst[i] = opathkey->pk_nulls_first;
    4814        9140 :         i++;
    4815             :     }
    4816             : 
    4817             :     /*
    4818             :      * Note: it is not an error if we have additional pathkey elements (i.e.,
    4819             :      * lop or lip isn't NULL here).  The input paths might be better-sorted
    4820             :      * than we need for the current mergejoin.
    4821             :      */
    4822             : 
    4823             :     /*
    4824             :      * Now we can build the mergejoin node.
    4825             :      */
    4826        8070 :     join_plan = make_mergejoin(tlist,
    4827             :                                joinclauses,
    4828             :                                otherclauses,
    4829             :                                mergeclauses,
    4830             :                                mergefamilies,
    4831             :                                mergecollations,
    4832             :                                mergereversals,
    4833             :                                mergenullsfirst,
    4834             :                                outer_plan,
    4835             :                                inner_plan,
    4836             :                                best_path->jpath.jointype,
    4837        8070 :                                best_path->jpath.inner_unique,
    4838        8070 :                                best_path->skip_mark_restore);
    4839             : 
    4840             :     /* Costs of sort and material steps are included in path cost already */
    4841        8070 :     copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
    4842             : 
    4843        8070 :     return join_plan;
    4844             : }
    4845             : 
    4846             : static HashJoin *
    4847       33270 : create_hashjoin_plan(PlannerInfo *root,
    4848             :                      HashPath *best_path)
    4849             : {
    4850             :     HashJoin   *join_plan;
    4851             :     Hash       *hash_plan;
    4852             :     Plan       *outer_plan;
    4853             :     Plan       *inner_plan;
    4854       33270 :     List       *tlist = build_path_tlist(root, &best_path->jpath.path);
    4855             :     List       *joinclauses;
    4856             :     List       *otherclauses;
    4857             :     List       *hashclauses;
    4858       33270 :     List       *hashoperators = NIL;
    4859       33270 :     List       *hashcollations = NIL;
    4860       33270 :     List       *inner_hashkeys = NIL;
    4861       33270 :     List       *outer_hashkeys = NIL;
    4862       33270 :     Oid         skewTable = InvalidOid;
    4863       33270 :     AttrNumber  skewColumn = InvalidAttrNumber;
    4864       33270 :     bool        skewInherit = false;
    4865             :     ListCell   *lc;
    4866             : 
    4867             :     /*
    4868             :      * HashJoin can project, so we don't have to demand exact tlists from the
    4869             :      * inputs.  However, it's best to request a small tlist from the inner
    4870             :      * side, so that we aren't storing more data than necessary.  Likewise, if
    4871             :      * we anticipate batching, request a small tlist from the outer side so
    4872             :      * that we don't put extra data in the outer batch files.
    4873             :      */
    4874       33270 :     outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
    4875       33270 :                                      (best_path->num_batches > 1) ? CP_SMALL_TLIST : 0);
    4876             : 
    4877       33270 :     inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
    4878             :                                      CP_SMALL_TLIST);
    4879             : 
    4880             :     /* Sort join qual clauses into best execution order */
    4881       33270 :     joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
    4882             :     /* There's no point in sorting the hash clauses ... */
    4883             : 
    4884             :     /* Get the join qual clauses (in plain expression form) */
    4885             :     /* Any pseudoconstant clauses are ignored here */
    4886       33270 :     if (IS_OUTER_JOIN(best_path->jpath.jointype))
    4887             :     {
    4888       11800 :         extract_actual_join_clauses(joinclauses,
    4889       11800 :                                     best_path->jpath.path.parent->relids,
    4890             :                                     &joinclauses, &otherclauses);
    4891             :     }
    4892             :     else
    4893             :     {
    4894             :         /* We can treat all clauses alike for an inner join */
    4895       21470 :         joinclauses = extract_actual_clauses(joinclauses, false);
    4896       21470 :         otherclauses = NIL;
    4897             :     }
    4898             : 
    4899             :     /*
    4900             :      * Remove the hashclauses from the list of join qual clauses, leaving the
    4901             :      * list of quals that must be checked as qpquals.
    4902             :      */
    4903       33270 :     hashclauses = get_actual_clauses(best_path->path_hashclauses);
    4904       33270 :     joinclauses = list_difference(joinclauses, hashclauses);
    4905             : 
    4906             :     /*
    4907             :      * Replace any outer-relation variables with nestloop params.  There
    4908             :      * should not be any in the hashclauses.
    4909             :      */
    4910       33270 :     if (best_path->jpath.path.param_info)
    4911             :     {
    4912         156 :         joinclauses = (List *)
    4913         156 :             replace_nestloop_params(root, (Node *) joinclauses);
    4914         156 :         otherclauses = (List *)
    4915         156 :             replace_nestloop_params(root, (Node *) otherclauses);
    4916             :     }
    4917             : 
    4918             :     /*
    4919             :      * Rearrange hashclauses, if needed, so that the outer variable is always
    4920             :      * on the left.
    4921             :      */
    4922       33270 :     hashclauses = get_switched_clauses(best_path->path_hashclauses,
    4923       33270 :                                        best_path->jpath.outerjoinpath->parent->relids);
    4924             : 
    4925             :     /*
    4926             :      * If there is a single join clause and we can identify the outer variable
    4927             :      * as a simple column reference, supply its identity for possible use in
    4928             :      * skew optimization.  (Note: in principle we could do skew optimization
    4929             :      * with multiple join clauses, but we'd have to be able to determine the
    4930             :      * most common combinations of outer values, which we don't currently have
    4931             :      * enough stats for.)
    4932             :      */
    4933       33270 :     if (list_length(hashclauses) == 1)
    4934             :     {
    4935       30780 :         OpExpr     *clause = (OpExpr *) linitial(hashclauses);
    4936             :         Node       *node;
    4937             : 
    4938             :         Assert(is_opclause(clause));
    4939       30780 :         node = (Node *) linitial(clause->args);
    4940       30780 :         if (IsA(node, RelabelType))
    4941         620 :             node = (Node *) ((RelabelType *) node)->arg;
    4942       30780 :         if (IsA(node, Var))
    4943             :         {
    4944       26674 :             Var        *var = (Var *) node;
    4945             :             RangeTblEntry *rte;
    4946             : 
    4947       26674 :             rte = root->simple_rte_array[var->varno];
    4948       26674 :             if (rte->rtekind == RTE_RELATION)
    4949             :             {
    4950       23416 :                 skewTable = rte->relid;
    4951       23416 :                 skewColumn = var->varattno;
    4952       23416 :                 skewInherit = rte->inh;
    4953             :             }
    4954             :         }
    4955             :     }
    4956             : 
    4957             :     /*
    4958             :      * Collect hash related information. The hashed expressions are
    4959             :      * deconstructed into outer/inner expressions, so they can be computed
    4960             :      * separately (inner expressions are used to build the hashtable via Hash,
    4961             :      * outer expressions to perform lookups of tuples from HashJoin's outer
    4962             :      * plan in the hashtable). Also collect operator information necessary to
    4963             :      * build the hashtable.
    4964             :      */
    4965       69132 :     foreach(lc, hashclauses)
    4966             :     {
    4967       35862 :         OpExpr     *hclause = lfirst_node(OpExpr, lc);
    4968             : 
    4969       35862 :         hashoperators = lappend_oid(hashoperators, hclause->opno);
    4970       35862 :         hashcollations = lappend_oid(hashcollations, hclause->inputcollid);
    4971       35862 :         outer_hashkeys = lappend(outer_hashkeys, linitial(hclause->args));
    4972       35862 :         inner_hashkeys = lappend(inner_hashkeys, lsecond(hclause->args));
    4973             :     }
    4974             : 
    4975             :     /*
    4976             :      * Build the hash node and hash join node.
    4977             :      */
    4978       33270 :     hash_plan = make_hash(inner_plan,
    4979             :                           inner_hashkeys,
    4980             :                           skewTable,
    4981             :                           skewColumn,
    4982             :                           skewInherit);
    4983             : 
    4984             :     /*
    4985             :      * Set Hash node's startup & total costs equal to total cost of input
    4986             :      * plan; this only affects EXPLAIN display not decisions.
    4987             :      */
    4988       33270 :     copy_plan_costsize(&hash_plan->plan, inner_plan);
    4989       33270 :     hash_plan->plan.startup_cost = hash_plan->plan.total_cost;
    4990             : 
    4991             :     /*
    4992             :      * If parallel-aware, the executor will also need an estimate of the total
    4993             :      * number of rows expected from all participants so that it can size the
    4994             :      * shared hash table.
    4995             :      */
    4996       33270 :     if (best_path->jpath.path.parallel_aware)
    4997             :     {
    4998         186 :         hash_plan->plan.parallel_aware = true;
    4999         186 :         hash_plan->rows_total = best_path->inner_rows_total;
    5000             :     }
    5001             : 
    5002       33270 :     join_plan = make_hashjoin(tlist,
    5003             :                               joinclauses,
    5004             :                               otherclauses,
    5005             :                               hashclauses,
    5006             :                               hashoperators,
    5007             :                               hashcollations,
    5008             :                               outer_hashkeys,
    5009             :                               outer_plan,
    5010             :                               (Plan *) hash_plan,
    5011             :                               best_path->jpath.jointype,
    5012       33270 :                               best_path->jpath.inner_unique);
    5013             : 
    5014       33270 :     copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
    5015             : 
    5016       33270 :     return join_plan;
    5017             : }
    5018             : 
    5019             : 
    5020             : /*****************************************************************************
    5021             :  *
    5022             :  *  SUPPORTING ROUTINES
    5023             :  *
    5024             :  *****************************************************************************/
    5025             : 
    5026             : /*
    5027             :  * replace_nestloop_params
    5028             :  *    Replace outer-relation Vars and PlaceHolderVars in the given expression
    5029             :  *    with nestloop Params
    5030             :  *
    5031             :  * All Vars and PlaceHolderVars belonging to the relation(s) identified by
    5032             :  * root->curOuterRels are replaced by Params, and entries are added to
    5033             :  * root->curOuterParams if not already present.
    5034             :  */
    5035             : static Node *
    5036      358286 : replace_nestloop_params(PlannerInfo *root, Node *expr)
    5037             : {
    5038             :     /* No setup needed for tree walk, so away we go */
    5039      358286 :     return replace_nestloop_params_mutator(expr, root);
    5040             : }
    5041             : 
    5042             : static Node *
    5043     1318406 : replace_nestloop_params_mutator(Node *node, PlannerInfo *root)
    5044             : {
    5045     1318406 :     if (node == NULL)
    5046       85460 :         return NULL;
    5047     1232946 :     if (IsA(node, Var))
    5048             :     {
    5049      376960 :         Var        *var = (Var *) node;
    5050             : 
    5051             :         /* Upper-level Vars should be long gone at this point */
    5052             :         Assert(var->varlevelsup == 0);
    5053             :         /* If not to be replaced, we can just return the Var unmodified */
    5054      376960 :         if (IS_SPECIAL_VARNO(var->varno) ||
    5055      376948 :             !bms_is_member(var->varno, root->curOuterRels))
    5056      281302 :             return node;
    5057             :         /* Replace the Var with a nestloop Param */
    5058       95658 :         return (Node *) replace_nestloop_param_var(root, var);
    5059             :     }
    5060      855986 :     if (IsA(node, PlaceHolderVar))
    5061             :     {
    5062         916 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
    5063             : 
    5064             :         /* Upper-level PlaceHolderVars should be long gone at this point */
    5065             :         Assert(phv->phlevelsup == 0);
    5066             : 
    5067             :         /* Check whether we need to replace the PHV */
    5068         916 :         if (!bms_is_subset(find_placeholder_info(root, phv)->ph_eval_at,
    5069         916 :                            root->curOuterRels))
    5070             :         {
    5071             :             /*
    5072             :              * We can't replace the whole PHV, but we might still need to
    5073             :              * replace Vars or PHVs within its expression, in case it ends up
    5074             :              * actually getting evaluated here.  (It might get evaluated in
    5075             :              * this plan node, or some child node; in the latter case we don't
    5076             :              * really need to process the expression here, but we haven't got
    5077             :              * enough info to tell if that's the case.)  Flat-copy the PHV
    5078             :              * node and then recurse on its expression.
    5079             :              *
    5080             :              * Note that after doing this, we might have different
    5081             :              * representations of the contents of the same PHV in different
    5082             :              * parts of the plan tree.  This is OK because equal() will just
    5083             :              * match on phid/phlevelsup, so setrefs.c will still recognize an
    5084             :              * upper-level reference to a lower-level copy of the same PHV.
    5085             :              */
    5086         592 :             PlaceHolderVar *newphv = makeNode(PlaceHolderVar);
    5087             : 
    5088         592 :             memcpy(newphv, phv, sizeof(PlaceHolderVar));
    5089         592 :             newphv->phexpr = (Expr *)
    5090         592 :                 replace_nestloop_params_mutator((Node *) phv->phexpr,
    5091             :                                                 root);
    5092         592 :             return (Node *) newphv;
    5093             :         }
    5094             :         /* Replace the PlaceHolderVar with a nestloop Param */
    5095         324 :         return (Node *) replace_nestloop_param_placeholdervar(root, phv);
    5096             :     }
    5097      855070 :     return expression_tree_mutator(node, replace_nestloop_params_mutator, root);
    5098             : }
    5099             : 
    5100             : /*
    5101             :  * fix_indexqual_references
    5102             :  *    Adjust indexqual clauses to the form the executor's indexqual
    5103             :  *    machinery needs.
    5104             :  *
    5105             :  * We have three tasks here:
    5106             :  *  * Select the actual qual clauses out of the input IndexClause list,
    5107             :  *    and remove RestrictInfo nodes from the qual clauses.
    5108             :  *  * Replace any outer-relation Var or PHV nodes with nestloop Params.
    5109             :  *    (XXX eventually, that responsibility should go elsewhere?)
    5110             :  *  * Index keys must be represented by Var nodes with varattno set to the
    5111             :  *    index's attribute number, not the attribute number in the original rel.
    5112             :  *
    5113             :  * *stripped_indexquals_p receives a list of the actual qual clauses.
    5114             :  *
    5115             :  * *fixed_indexquals_p receives a list of the adjusted quals.  This is a copy
    5116             :  * that shares no substructure with the original; this is needed in case there
    5117             :  * are subplans in it (we need two separate copies of the subplan tree, or
    5118             :  * things will go awry).
    5119             :  */
    5120             : static void
    5121      180764 : fix_indexqual_references(PlannerInfo *root, IndexPath *index_path,
    5122             :                          List **stripped_indexquals_p, List **fixed_indexquals_p)
    5123             : {
    5124      180764 :     IndexOptInfo *index = index_path->indexinfo;
    5125             :     List       *stripped_indexquals;
    5126             :     List       *fixed_indexquals;
    5127             :     ListCell   *lc;
    5128             : 
    5129      180764 :     stripped_indexquals = fixed_indexquals = NIL;
    5130             : 
    5131      377322 :     foreach(lc, index_path->indexclauses)
    5132             :     {
    5133      196558 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    5134      196558 :         int         indexcol = iclause->indexcol;
    5135             :         ListCell   *lc2;
    5136             : 
    5137      394172 :         foreach(lc2, iclause->indexquals)
    5138             :         {
    5139      197614 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
    5140      197614 :             Node       *clause = (Node *) rinfo->clause;
    5141             : 
    5142      197614 :             stripped_indexquals = lappend(stripped_indexquals, clause);
    5143      197614 :             clause = fix_indexqual_clause(root, index, indexcol,
    5144             :                                           clause, iclause->indexcols);
    5145      197614 :             fixed_indexquals = lappend(fixed_indexquals, clause);
    5146             :         }
    5147             :     }
    5148             : 
    5149      180764 :     *stripped_indexquals_p = stripped_indexquals;
    5150      180764 :     *fixed_indexquals_p = fixed_indexquals;
    5151      180764 : }
    5152             : 
    5153             : /*
    5154             :  * fix_indexorderby_references
    5155             :  *    Adjust indexorderby clauses to the form the executor's index
    5156             :  *    machinery needs.
    5157             :  *
    5158             :  * This is a simplified version of fix_indexqual_references.  The input is
    5159             :  * bare clauses and a separate indexcol list, instead of IndexClauses.
    5160             :  */
    5161             : static List *
    5162      180764 : fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path)
    5163             : {
    5164      180764 :     IndexOptInfo *index = index_path->indexinfo;
    5165             :     List       *fixed_indexorderbys;
    5166             :     ListCell   *lcc,
    5167             :                *lci;
    5168             : 
    5169      180764 :     fixed_indexorderbys = NIL;
    5170             : 
    5171      181150 :     forboth(lcc, index_path->indexorderbys, lci, index_path->indexorderbycols)
    5172             :     {
    5173         386 :         Node       *clause = (Node *) lfirst(lcc);
    5174         386 :         int         indexcol = lfirst_int(lci);
    5175             : 
    5176         386 :         clause = fix_indexqual_clause(root, index, indexcol, clause, NIL);
    5177         386 :         fixed_indexorderbys = lappend(fixed_indexorderbys, clause);
    5178             :     }
    5179             : 
    5180      180764 :     return fixed_indexorderbys;
    5181             : }
    5182             : 
    5183             : /*
    5184             :  * fix_indexqual_clause
    5185             :  *    Convert a single indexqual clause to the form needed by the executor.
    5186             :  *
    5187             :  * We replace nestloop params here, and replace the index key variables
    5188             :  * or expressions by index Var nodes.
    5189             :  */
    5190             : static Node *
    5191      198000 : fix_indexqual_clause(PlannerInfo *root, IndexOptInfo *index, int indexcol,
    5192             :                      Node *clause, List *indexcolnos)
    5193             : {
    5194             :     /*
    5195             :      * Replace any outer-relation variables with nestloop params.
    5196             :      *
    5197             :      * This also makes a copy of the clause, so it's safe to modify it
    5198             :      * in-place below.
    5199             :      */
    5200      198000 :     clause = replace_nestloop_params(root, clause);
    5201             : 
    5202      198000 :     if (IsA(clause, OpExpr))
    5203             :     {
    5204      194900 :         OpExpr     *op = (OpExpr *) clause;
    5205             : 
    5206             :         /* Replace the indexkey expression with an index Var. */
    5207      194900 :         linitial(op->args) = fix_indexqual_operand(linitial(op->args),
    5208             :                                                    index,
    5209             :                                                    indexcol);
    5210             :     }
    5211        3100 :     else if (IsA(clause, RowCompareExpr))
    5212             :     {
    5213         168 :         RowCompareExpr *rc = (RowCompareExpr *) clause;
    5214             :         ListCell   *lca,
    5215             :                    *lcai;
    5216             : 
    5217             :         /* Replace the indexkey expressions with index Vars. */
    5218             :         Assert(list_length(rc->largs) == list_length(indexcolnos));
    5219         504 :         forboth(lca, rc->largs, lcai, indexcolnos)
    5220             :         {
    5221         336 :             lfirst(lca) = fix_indexqual_operand(lfirst(lca),
    5222             :                                                 index,
    5223             :                                                 lfirst_int(lcai));
    5224             :         }
    5225             :     }
    5226        2932 :     else if (IsA(clause, ScalarArrayOpExpr))
    5227             :     {
    5228        2038 :         ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
    5229             : 
    5230             :         /* Replace the indexkey expression with an index Var. */
    5231        2038 :         linitial(saop->args) = fix_indexqual_operand(linitial(saop->args),
    5232             :                                                      index,
    5233             :                                                      indexcol);
    5234             :     }
    5235         894 :     else if (IsA(clause, NullTest))
    5236             :     {
    5237         894 :         NullTest   *nt = (NullTest *) clause;
    5238             : 
    5239             :         /* Replace the indexkey expression with an index Var. */
    5240         894 :         nt->arg = (Expr *) fix_indexqual_operand((Node *) nt->arg,
    5241             :                                                  index,
    5242             :                                                  indexcol);
    5243             :     }
    5244             :     else
    5245           0 :         elog(ERROR, "unsupported indexqual type: %d",
    5246             :              (int) nodeTag(clause));
    5247             : 
    5248      198000 :     return clause;
    5249             : }
    5250             : 
    5251             : /*
    5252             :  * fix_indexqual_operand
    5253             :  *    Convert an indexqual expression to a Var referencing the index column.
    5254             :  *
    5255             :  * We represent index keys by Var nodes having varno == INDEX_VAR and varattno
    5256             :  * equal to the index's attribute number (index column position).
    5257             :  *
    5258             :  * Most of the code here is just for sanity cross-checking that the given
    5259             :  * expression actually matches the index column it's claimed to.
    5260             :  */
    5261             : static Node *
    5262      198168 : fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol)
    5263             : {
    5264             :     Var        *result;
    5265             :     int         pos;
    5266             :     ListCell   *indexpr_item;
    5267             : 
    5268             :     /*
    5269             :      * Remove any binary-compatible relabeling of the indexkey
    5270             :      */
    5271      198168 :     if (IsA(node, RelabelType))
    5272         626 :         node = (Node *) ((RelabelType *) node)->arg;
    5273             : 
    5274             :     Assert(indexcol >= 0 && indexcol < index->ncolumns);
    5275             : 
    5276      198168 :     if (index->indexkeys[indexcol] != 0)
    5277             :     {
    5278             :         /* It's a simple index column */
    5279      197804 :         if (IsA(node, Var) &&
    5280      197804 :             ((Var *) node)->varno == index->rel->relid &&
    5281      197804 :             ((Var *) node)->varattno == index->indexkeys[indexcol])
    5282             :         {
    5283      197804 :             result = (Var *) copyObject(node);
    5284      197804 :             result->varno = INDEX_VAR;
    5285      197804 :             result->varattno = indexcol + 1;
    5286      197804 :             return (Node *) result;
    5287             :         }
    5288             :         else
    5289           0 :             elog(ERROR, "index key does not match expected index column");
    5290             :     }
    5291             : 
    5292             :     /* It's an index expression, so find and cross-check the expression */
    5293         364 :     indexpr_item = list_head(index->indexprs);
    5294         364 :     for (pos = 0; pos < index->ncolumns; pos++)
    5295             :     {
    5296         364 :         if (index->indexkeys[pos] == 0)
    5297             :         {
    5298         364 :             if (indexpr_item == NULL)
    5299           0 :                 elog(ERROR, "too few entries in indexprs list");
    5300         364 :             if (pos == indexcol)
    5301             :             {
    5302             :                 Node       *indexkey;
    5303             : 
    5304         364 :                 indexkey = (Node *) lfirst(indexpr_item);
    5305         364 :                 if (indexkey && IsA(indexkey, RelabelType))
    5306          10 :                     indexkey = (Node *) ((RelabelType *) indexkey)->arg;
    5307         364 :                 if (equal(node, indexkey))
    5308             :                 {
    5309         364 :                     result = makeVar(INDEX_VAR, indexcol + 1,
    5310         364 :                                      exprType(lfirst(indexpr_item)), -1,
    5311         364 :                                      exprCollation(lfirst(indexpr_item)),
    5312             :                                      0);
    5313         364 :                     return (Node *) result;
    5314             :                 }
    5315             :                 else
    5316           0 :                     elog(ERROR, "index key does not match expected index column");
    5317             :             }
    5318           0 :             indexpr_item = lnext(index->indexprs, indexpr_item);
    5319             :         }
    5320             :     }
    5321             : 
    5322             :     /* Oops... */
    5323           0 :     elog(ERROR, "index key does not match expected index column");
    5324             :     return NULL;                /* keep compiler quiet */
    5325             : }
    5326             : 
    5327             : /*
    5328             :  * get_switched_clauses
    5329             :  *    Given a list of merge or hash joinclauses (as RestrictInfo nodes),
    5330             :  *    extract the bare clauses, and rearrange the elements within the
    5331             :  *    clauses, if needed, so the outer join variable is on the left and
    5332             :  *    the inner is on the right.  The original clause data structure is not
    5333             :  *    touched; a modified list is returned.  We do, however, set the transient
    5334             :  *    outer_is_left field in each RestrictInfo to show which side was which.
    5335             :  */
    5336             : static List *
    5337       41340 : get_switched_clauses(List *clauses, Relids outerrelids)
    5338             : {
    5339       41340 :     List       *t_list = NIL;
    5340             :     ListCell   *l;
    5341             : 
    5342       86342 :     foreach(l, clauses)
    5343             :     {
    5344       45002 :         RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
    5345       45002 :         OpExpr     *clause = (OpExpr *) restrictinfo->clause;
    5346             : 
    5347             :         Assert(is_opclause(clause));
    5348       45002 :         if (bms_is_subset(restrictinfo->right_relids, outerrelids))
    5349             :         {
    5350             :             /*
    5351             :              * Duplicate just enough of the structure to allow commuting the
    5352             :              * clause without changing the original list.  Could use
    5353             :              * copyObject, but a complete deep copy is overkill.
    5354             :              */
    5355       18746 :             OpExpr     *temp = makeNode(OpExpr);
    5356             : 
    5357       18746 :             temp->opno = clause->opno;
    5358       18746 :             temp->opfuncid = InvalidOid;
    5359       18746 :             temp->opresulttype = clause->opresulttype;
    5360       18746 :             temp->opretset = clause->opretset;
    5361       18746 :             temp->opcollid = clause->opcollid;
    5362       18746 :             temp->inputcollid = clause->inputcollid;
    5363       18746 :             temp->args = list_copy(clause->args);
    5364       18746 :             temp->location = clause->location;
    5365             :             /* Commute it --- note this modifies the temp node in-place. */
    5366       18746 :             CommuteOpExpr(temp);
    5367       18746 :             t_list = lappend(t_list, temp);
    5368       18746 :             restrictinfo->outer_is_left = false;
    5369             :         }
    5370             :         else
    5371             :         {
    5372             :             Assert(bms_is_subset(restrictinfo->left_relids, outerrelids));
    5373       26256 :             t_list = lappend(t_list, clause);
    5374       26256 :             restrictinfo->outer_is_left = true;
    5375             :         }
    5376             :     }
    5377       41340 :     return t_list;
    5378             : }
    5379             : 
    5380             : /*
    5381             :  * order_qual_clauses
    5382             :  *      Given a list of qual clauses that will all be evaluated at the same
    5383             :  *      plan node, sort the list into the order we want to check the quals
    5384             :  *      in at runtime.
    5385             :  *
    5386             :  * When security barrier quals are used in the query, we may have quals with
    5387             :  * different security levels in the list.  Quals of lower security_level
    5388             :  * must go before quals of higher security_level, except that we can grant
    5389             :  * exceptions to move up quals that are leakproof.  When security level
    5390             :  * doesn't force the decision, we prefer to order clauses by estimated
    5391             :  * execution cost, cheapest first.
    5392             :  *
    5393             :  * Ideally the order should be driven by a combination of execution cost and
    5394             :  * selectivity, but it's not immediately clear how to account for both,
    5395             :  * and given the uncertainty of the estimates the reliability of the decisions
    5396             :  * would be doubtful anyway.  So we just order by security level then
    5397             :  * estimated per-tuple cost, being careful not to change the order when
    5398             :  * (as is often the case) the estimates are identical.
    5399             :  *
    5400             :  * Although this will work on either bare clauses or RestrictInfos, it's
    5401             :  * much faster to apply it to RestrictInfos, since it can re-use cost
    5402             :  * information that is cached in RestrictInfos.  XXX in the bare-clause
    5403             :  * case, we are also not able to apply security considerations.  That is
    5404             :  * all right for the moment, because the bare-clause case doesn't occur
    5405             :  * anywhere that barrier quals could be present, but it would be better to
    5406             :  * get rid of it.
    5407             :  *
    5408             :  * Note: some callers pass lists that contain entries that will later be
    5409             :  * removed; this is the easiest way to let this routine see RestrictInfos
    5410             :  * instead of bare clauses.  This is another reason why trying to consider
    5411             :  * selectivity in the ordering would likely do the wrong thing.
    5412             :  */
    5413             : static List *
    5414      912064 : order_qual_clauses(PlannerInfo *root, List *clauses)
    5415             : {
    5416             :     typedef struct
    5417             :     {
    5418             :         Node       *clause;
    5419             :         Cost        cost;
    5420             :         Index       security_level;
    5421             :     } QualItem;
    5422      912064 :     int         nitems = list_length(clauses);
    5423             :     QualItem   *items;
    5424             :     ListCell   *lc;
    5425             :     int         i;
    5426             :     List       *result;
    5427             : 
    5428             :     /* No need to work hard for 0 or 1 clause */
    5429      912064 :     if (nitems <= 1)
    5430      841086 :         return clauses;
    5431             : 
    5432             :     /*
    5433             :      * Collect the items and costs into an array.  This is to avoid repeated
    5434             :      * cost_qual_eval work if the inputs aren't RestrictInfos.
    5435             :      */
    5436       70978 :     items = (QualItem *) palloc(nitems * sizeof(QualItem));
    5437       70978 :     i = 0;
    5438      236252 :     foreach(lc, clauses)
    5439             :     {
    5440      165274 :         Node       *clause = (Node *) lfirst(lc);
    5441             :         QualCost    qcost;
    5442             : 
    5443      165274 :         cost_qual_eval_node(&qcost, clause, root);
    5444      165274 :         items[i].clause = clause;
    5445      165274 :         items[i].cost = qcost.per_tuple;
    5446      165274 :         if (IsA(clause, RestrictInfo))
    5447             :         {
    5448      165182 :             RestrictInfo *rinfo = (RestrictInfo *) clause;
    5449             : 
    5450             :             /*
    5451             :              * If a clause is leakproof, it doesn't have to be constrained by
    5452             :              * its nominal security level.  If it's also reasonably cheap
    5453             :              * (here defined as 10X cpu_operator_cost), pretend it has
    5454             :              * security_level 0, which will allow it to go in front of
    5455             :              * more-expensive quals of lower security levels.  Of course, that
    5456             :              * will also force it to go in front of cheaper quals of its own
    5457             :              * security level, which is not so great, but we can alleviate
    5458             :              * that risk by applying the cost limit cutoff.
    5459             :              */
    5460      165182 :             if (rinfo->leakproof && items[i].cost < 10 * cpu_operator_cost)
    5461        1200 :                 items[i].security_level = 0;
    5462             :             else
    5463      163982 :                 items[i].security_level = rinfo->security_level;
    5464             :         }
    5465             :         else
    5466          92 :             items[i].security_level = 0;
    5467      165274 :         i++;
    5468             :     }
    5469             : 
    5470             :     /*
    5471             :      * Sort.  We don't use qsort() because it's not guaranteed stable for
    5472             :      * equal keys.  The expected number of entries is small enough that a
    5473             :      * simple insertion sort should be good enough.
    5474             :      */
    5475      165274 :     for (i = 1; i < nitems; i++)
    5476             :     {
    5477       94296 :         QualItem    newitem = items[i];
    5478             :         int         j;
    5479             : 
    5480             :         /* insert newitem into the already-sorted subarray */
    5481      105058 :         for (j = i; j > 0; j--)
    5482             :         {
    5483       96442 :             QualItem   *olditem = &items[j - 1];
    5484             : 
    5485       96442 :             if (newitem.security_level > olditem->security_level ||
    5486       95710 :                 (newitem.security_level == olditem->security_level &&
    5487       94322 :                  newitem.cost >= olditem->cost))
    5488             :                 break;
    5489       10762 :             items[j] = *olditem;
    5490             :         }
    5491       94296 :         items[j] = newitem;
    5492             :     }
    5493             : 
    5494             :     /* Convert back to a list */
    5495       70978 :     result = NIL;
    5496      236252 :     for (i = 0; i < nitems; i++)
    5497      165274 :         result = lappend(result, items[i].clause);
    5498             : 
    5499       70978 :     return result;
    5500             : }
    5501             : 
    5502             : /*
    5503             :  * Copy cost and size info from a Path node to the Plan node created from it.
    5504             :  * The executor usually won't use this info, but it's needed by EXPLAIN.
    5505             :  * Also copy the parallel-related flags, which the executor *will* use.
    5506             :  */
    5507             : static void
    5508     1119626 : copy_generic_path_info(Plan *dest, Path *src)
    5509             : {
    5510     1119626 :     dest->disabled_nodes = src->disabled_nodes;
    5511     1119626 :     dest->startup_cost = src->startup_cost;
    5512     1119626 :     dest->total_cost = src->total_cost;
    5513     1119626 :     dest->plan_rows = src->rows;
    5514     1119626 :     dest->plan_width = src->pathtarget->width;
    5515     1119626 :     dest->parallel_aware = src->parallel_aware;
    5516     1119626 :     dest->parallel_safe = src->parallel_safe;
    5517     1119626 : }
    5518             : 
    5519             : /*
    5520             :  * Copy cost and size info from a lower plan node to an inserted node.
    5521             :  * (Most callers alter the info after copying it.)
    5522             :  */
    5523             : static void
    5524       43286 : copy_plan_costsize(Plan *dest, Plan *src)
    5525             : {
    5526       43286 :     dest->disabled_nodes = src->disabled_nodes;
    5527       43286 :     dest->startup_cost = src->startup_cost;
    5528       43286 :     dest->total_cost = src->total_cost;
    5529       43286 :     dest->plan_rows = src->plan_rows;
    5530       43286 :     dest->plan_width = src->plan_width;
    5531             :     /* Assume the inserted node is not parallel-aware. */
    5532       43286 :     dest->parallel_aware = false;
    5533             :     /* Assume the inserted node is parallel-safe, if child plan is. */
    5534       43286 :     dest->parallel_safe = src->parallel_safe;
    5535       43286 : }
    5536             : 
    5537             : /*
    5538             :  * Some places in this file build Sort nodes that don't have a directly
    5539             :  * corresponding Path node.  The cost of the sort is, or should have been,
    5540             :  * included in the cost of the Path node we're working from, but since it's
    5541             :  * not split out, we have to re-figure it using cost_sort().  This is just
    5542             :  * to label the Sort node nicely for EXPLAIN.
    5543             :  *
    5544             :  * limit_tuples is as for cost_sort (in particular, pass -1 if no limit)
    5545             :  */
    5546             : static void
    5547       10894 : label_sort_with_costsize(PlannerInfo *root, Sort *plan, double limit_tuples)
    5548             : {
    5549       10894 :     Plan       *lefttree = plan->plan.lefttree;
    5550             :     Path        sort_path;      /* dummy for result of cost_sort */
    5551             : 
    5552             :     Assert(IsA(plan, Sort));
    5553             : 
    5554       10894 :     cost_sort(&sort_path, root, NIL,
    5555             :               plan->plan.disabled_nodes,
    5556             :               lefttree->total_cost,
    5557             :               lefttree->plan_rows,
    5558             :               lefttree->plan_width,
    5559             :               0.0,
    5560             :               work_mem,
    5561             :               limit_tuples);
    5562       10894 :     plan->plan.startup_cost = sort_path.startup_cost;
    5563       10894 :     plan->plan.total_cost = sort_path.total_cost;
    5564       10894 :     plan->plan.plan_rows = lefttree->plan_rows;
    5565       10894 :     plan->plan.plan_width = lefttree->plan_width;
    5566       10894 :     plan->plan.parallel_aware = false;
    5567       10894 :     plan->plan.parallel_safe = lefttree->parallel_safe;
    5568       10894 : }
    5569             : 
    5570             : /*
    5571             :  * Same as label_sort_with_costsize, but labels the IncrementalSort node
    5572             :  * instead.
    5573             :  */
    5574             : static void
    5575          12 : label_incrementalsort_with_costsize(PlannerInfo *root, IncrementalSort *plan,
    5576             :                                     List *pathkeys, double limit_tuples)
    5577             : {
    5578          12 :     Plan       *lefttree = plan->sort.plan.lefttree;
    5579             :     Path        sort_path;      /* dummy for result of cost_incremental_sort */
    5580             : 
    5581             :     Assert(IsA(plan, IncrementalSort));
    5582             : 
    5583          12 :     cost_incremental_sort(&sort_path, root, pathkeys,
    5584             :                           plan->nPresortedCols,
    5585             :                           plan->sort.plan.disabled_nodes,
    5586             :                           lefttree->startup_cost,
    5587             :                           lefttree->total_cost,
    5588             :                           lefttree->plan_rows,
    5589             :                           lefttree->plan_width,
    5590             :                           0.0,
    5591             :                           work_mem,
    5592             :                           limit_tuples);
    5593          12 :     plan->sort.plan.startup_cost = sort_path.startup_cost;
    5594          12 :     plan->sort.plan.total_cost = sort_path.total_cost;
    5595          12 :     plan->sort.plan.plan_rows = lefttree->plan_rows;
    5596          12 :     plan->sort.plan.plan_width = lefttree->plan_width;
    5597          12 :     plan->sort.plan.parallel_aware = false;
    5598          12 :     plan->sort.plan.parallel_safe = lefttree->parallel_safe;
    5599          12 : }
    5600             : 
    5601             : /*
    5602             :  * bitmap_subplan_mark_shared
    5603             :  *   Set isshared flag in bitmap subplan so that it will be created in
    5604             :  *   shared memory.
    5605             :  */
    5606             : static void
    5607          30 : bitmap_subplan_mark_shared(Plan *plan)
    5608             : {
    5609          30 :     if (IsA(plan, BitmapAnd))
    5610           0 :         bitmap_subplan_mark_shared(linitial(((BitmapAnd *) plan)->bitmapplans));
    5611          30 :     else if (IsA(plan, BitmapOr))
    5612             :     {
    5613           0 :         ((BitmapOr *) plan)->isshared = true;
    5614           0 :         bitmap_subplan_mark_shared(linitial(((BitmapOr *) plan)->bitmapplans));
    5615             :     }
    5616          30 :     else if (IsA(plan, BitmapIndexScan))
    5617          30 :         ((BitmapIndexScan *) plan)->isshared = true;
    5618             :     else
    5619           0 :         elog(ERROR, "unrecognized node type: %d", nodeTag(plan));
    5620          30 : }
    5621             : 
    5622             : /*****************************************************************************
    5623             :  *
    5624             :  *  PLAN NODE BUILDING ROUTINES
    5625             :  *
    5626             :  * In general, these functions are not passed the original Path and therefore
    5627             :  * leave it to the caller to fill in the cost/width fields from the Path,
    5628             :  * typically by calling copy_generic_path_info().  This convention is
    5629             :  * somewhat historical, but it does support a few places above where we build
    5630             :  * a plan node without having an exactly corresponding Path node.  Under no
    5631             :  * circumstances should one of these functions do its own cost calculations,
    5632             :  * as that would be redundant with calculations done while building Paths.
    5633             :  *
    5634             :  *****************************************************************************/
    5635             : 
    5636             : static SeqScan *
    5637      216142 : make_seqscan(List *qptlist,
    5638             :              List *qpqual,
    5639             :              Index scanrelid)
    5640             : {
    5641      216142 :     SeqScan    *node = makeNode(SeqScan);
    5642      216142 :     Plan       *plan = &node->scan.plan;
    5643             : 
    5644      216142 :     plan->targetlist = qptlist;
    5645      216142 :     plan->qual = qpqual;
    5646      216142 :     plan->lefttree = NULL;
    5647      216142 :     plan->righttree = NULL;
    5648      216142 :     node->scan.scanrelid = scanrelid;
    5649             : 
    5650      216142 :     return node;
    5651             : }
    5652             : 
    5653             : static SampleScan *
    5654         306 : make_samplescan(List *qptlist,
    5655             :                 List *qpqual,
    5656             :                 Index scanrelid,
    5657             :                 TableSampleClause *tsc)
    5658             : {
    5659         306 :     SampleScan *node = makeNode(SampleScan);
    5660         306 :     Plan       *plan = &node->scan.plan;
    5661             : 
    5662         306 :     plan->targetlist = qptlist;
    5663         306 :     plan->qual = qpqual;
    5664         306 :     plan->lefttree = NULL;
    5665         306 :     plan->righttree = NULL;
    5666         306 :     node->scan.scanrelid = scanrelid;
    5667         306 :     node->tablesample = tsc;
    5668             : 
    5669         306 :     return node;
    5670             : }
    5671             : 
    5672             : static IndexScan *
    5673      164416 : make_indexscan(List *qptlist,
    5674             :                List *qpqual,
    5675             :                Index scanrelid,
    5676             :                Oid indexid,
    5677             :                List *indexqual,
    5678             :                List *indexqualorig,
    5679             :                List *indexorderby,
    5680             :                List *indexorderbyorig,
    5681             :                List *indexorderbyops,
    5682             :                ScanDirection indexscandir)
    5683             : {
    5684      164416 :     IndexScan  *node = makeNode(IndexScan);
    5685      164416 :     Plan       *plan = &node->scan.plan;
    5686             : 
    5687      164416 :     plan->targetlist = qptlist;
    5688      164416 :     plan->qual = qpqual;
    5689      164416 :     plan->lefttree = NULL;
    5690      164416 :     plan->righttree = NULL;
    5691      164416 :     node->scan.scanrelid = scanrelid;
    5692      164416 :     node->indexid = indexid;
    5693      164416 :     node->indexqual = indexqual;
    5694      164416 :     node->indexqualorig = indexqualorig;
    5695      164416 :     node->indexorderby = indexorderby;
    5696      164416 :     node->indexorderbyorig = indexorderbyorig;
    5697      164416 :     node->indexorderbyops = indexorderbyops;
    5698      164416 :     node->indexorderdir = indexscandir;
    5699             : 
    5700      164416 :     return node;
    5701             : }
    5702             : 
    5703             : static IndexOnlyScan *
    5704       16348 : make_indexonlyscan(List *qptlist,
    5705             :                    List *qpqual,
    5706             :                    Index scanrelid,
    5707             :                    Oid indexid,
    5708             :                    List *indexqual,
    5709             :                    List *recheckqual,
    5710             :                    List *indexorderby,
    5711             :                    List *indextlist,
    5712             :                    ScanDirection indexscandir)
    5713             : {
    5714       16348 :     IndexOnlyScan *node = makeNode(IndexOnlyScan);
    5715       16348 :     Plan       *plan = &node->scan.plan;
    5716             : 
    5717       16348 :     plan->targetlist = qptlist;
    5718       16348 :     plan->qual = qpqual;
    5719       16348 :     plan->lefttree = NULL;
    5720       16348 :     plan->righttree = NULL;
    5721       16348 :     node->scan.scanrelid = scanrelid;
    5722       16348 :     node->indexid = indexid;
    5723       16348 :     node->indexqual = indexqual;
    5724       16348 :     node->recheckqual = recheckqual;
    5725       16348 :     node->indexorderby = indexorderby;
    5726       16348 :     node->indextlist = indextlist;
    5727       16348 :     node->indexorderdir = indexscandir;
    5728             : 
    5729       16348 :     return node;
    5730             : }
    5731             : 
    5732             : static BitmapIndexScan *
    5733       21276 : make_bitmap_indexscan(Index scanrelid,
    5734             :                       Oid indexid,
    5735             :                       List *indexqual,
    5736             :                       List *indexqualorig)
    5737             : {
    5738       21276 :     BitmapIndexScan *node = makeNode(BitmapIndexScan);
    5739       21276 :     Plan       *plan = &node->scan.plan;
    5740             : 
    5741       21276 :     plan->targetlist = NIL;      /* not used */
    5742       21276 :     plan->qual = NIL;            /* not used */
    5743       21276 :     plan->lefttree = NULL;
    5744       21276 :     plan->righttree = NULL;
    5745       21276 :     node->scan.scanrelid = scanrelid;
    5746       21276 :     node->indexid = indexid;
    5747       21276 :     node->indexqual = indexqual;
    5748       21276 :     node->indexqualorig = indexqualorig;
    5749             : 
    5750       21276 :     return node;
    5751             : }
    5752             : 
    5753             : static BitmapHeapScan *
    5754       20656 : make_bitmap_heapscan(List *qptlist,
    5755             :                      List *qpqual,
    5756             :                      Plan *lefttree,
    5757             :                      List *bitmapqualorig,
    5758             :                      Index scanrelid)
    5759             : {
    5760       20656 :     BitmapHeapScan *node = makeNode(BitmapHeapScan);
    5761       20656 :     Plan       *plan = &node->scan.plan;
    5762             : 
    5763       20656 :     plan->targetlist = qptlist;
    5764       20656 :     plan->qual = qpqual;
    5765       20656 :     plan->lefttree = lefttree;
    5766       20656 :     plan->righttree = NULL;
    5767       20656 :     node->scan.scanrelid = scanrelid;
    5768       20656 :     node->bitmapqualorig = bitmapqualorig;
    5769             : 
    5770       20656 :     return node;
    5771             : }
    5772             : 
    5773             : static TidScan *
    5774         732 : make_tidscan(List *qptlist,
    5775             :              List *qpqual,
    5776             :              Index scanrelid,
    5777             :              List *tidquals)
    5778             : {
    5779         732 :     TidScan    *node = makeNode(TidScan);
    5780         732 :     Plan       *plan = &node->scan.plan;
    5781             : 
    5782         732 :     plan->targetlist = qptlist;
    5783         732 :     plan->qual = qpqual;
    5784         732 :     plan->lefttree = NULL;
    5785         732 :     plan->righttree = NULL;
    5786         732 :     node->scan.scanrelid = scanrelid;
    5787         732 :     node->tidquals = tidquals;
    5788             : 
    5789         732 :     return node;
    5790             : }
    5791             : 
    5792             : static TidRangeScan *
    5793        1940 : make_tidrangescan(List *qptlist,
    5794             :                   List *qpqual,
    5795             :                   Index scanrelid,
    5796             :                   List *tidrangequals)
    5797             : {
    5798        1940 :     TidRangeScan *node = makeNode(TidRangeScan);
    5799        1940 :     Plan       *plan = &node->scan.plan;
    5800             : 
    5801        1940 :     plan->targetlist = qptlist;
    5802        1940 :     plan->qual = qpqual;
    5803        1940 :     plan->lefttree = NULL;
    5804        1940 :     plan->righttree = NULL;
    5805        1940 :     node->scan.scanrelid = scanrelid;
    5806        1940 :     node->tidrangequals = tidrangequals;
    5807             : 
    5808        1940 :     return node;
    5809             : }
    5810             : 
    5811             : static SubqueryScan *
    5812       27752 : make_subqueryscan(List *qptlist,
    5813             :                   List *qpqual,
    5814             :                   Index scanrelid,
    5815             :                   Plan *subplan)
    5816             : {
    5817       27752 :     SubqueryScan *node = makeNode(SubqueryScan);
    5818       27752 :     Plan       *plan = &node->scan.plan;
    5819             : 
    5820       27752 :     plan->targetlist = qptlist;
    5821       27752 :     plan->qual = qpqual;
    5822       27752 :     plan->lefttree = NULL;
    5823       27752 :     plan->righttree = NULL;
    5824       27752 :     node->scan.scanrelid = scanrelid;
    5825       27752 :     node->subplan = subplan;
    5826       27752 :     node->scanstatus = SUBQUERY_SCAN_UNKNOWN;
    5827             : 
    5828       27752 :     return node;
    5829             : }
    5830             : 
    5831             : static FunctionScan *
    5832       51770 : make_functionscan(List *qptlist,
    5833             :                   List *qpqual,
    5834             :                   Index scanrelid,
    5835             :                   List *functions,
    5836             :                   bool funcordinality)
    5837             : {
    5838       51770 :     FunctionScan *node = makeNode(FunctionScan);
    5839       51770 :     Plan       *plan = &node->scan.plan;
    5840             : 
    5841       51770 :     plan->targetlist = qptlist;
    5842       51770 :     plan->qual = qpqual;
    5843       51770 :     plan->lefttree = NULL;
    5844       51770 :     plan->righttree = NULL;
    5845       51770 :     node->scan.scanrelid = scanrelid;
    5846       51770 :     node->functions = functions;
    5847       51770 :     node->funcordinality = funcordinality;
    5848             : 
    5849       51770 :     return node;
    5850             : }
    5851             : 
    5852             : static TableFuncScan *
    5853         626 : make_tablefuncscan(List *qptlist,
    5854             :                    List *qpqual,
    5855             :                    Index scanrelid,
    5856             :                    TableFunc *tablefunc)
    5857             : {
    5858         626 :     TableFuncScan *node = makeNode(TableFuncScan);
    5859         626 :     Plan       *plan = &node->scan.plan;
    5860             : 
    5861         626 :     plan->targetlist = qptlist;
    5862         626 :     plan->qual = qpqual;
    5863         626 :     plan->lefttree = NULL;
    5864         626 :     plan->righttree = NULL;
    5865         626 :     node->scan.scanrelid = scanrelid;
    5866         626 :     node->tablefunc = tablefunc;
    5867             : 
    5868         626 :     return node;
    5869             : }
    5870             : 
    5871             : static ValuesScan *
    5872        8248 : make_valuesscan(List *qptlist,
    5873             :                 List *qpqual,
    5874             :                 Index scanrelid,
    5875             :                 List *values_lists)
    5876             : {
    5877        8248 :     ValuesScan *node = makeNode(ValuesScan);
    5878        8248 :     Plan       *plan = &node->scan.plan;
    5879             : 
    5880        8248 :     plan->targetlist = qptlist;
    5881        8248 :     plan->qual = qpqual;
    5882        8248 :     plan->lefttree = NULL;
    5883        8248 :     plan->righttree = NULL;
    5884        8248 :     node->scan.scanrelid = scanrelid;
    5885        8248 :     node->values_lists = values_lists;
    5886             : 
    5887        8248 :     return node;
    5888             : }
    5889             : 
    5890             : static CteScan *
    5891        4082 : make_ctescan(List *qptlist,
    5892             :              List *qpqual,
    5893             :              Index scanrelid,
    5894             :              int ctePlanId,
    5895             :              int cteParam)
    5896             : {
    5897        4082 :     CteScan    *node = makeNode(CteScan);
    5898        4082 :     Plan       *plan = &node->scan.plan;
    5899             : 
    5900        4082 :     plan->targetlist = qptlist;
    5901        4082 :     plan->qual = qpqual;
    5902        4082 :     plan->lefttree = NULL;
    5903        4082 :     plan->righttree = NULL;
    5904        4082 :     node->scan.scanrelid = scanrelid;
    5905        4082 :     node->ctePlanId = ctePlanId;
    5906        4082 :     node->cteParam = cteParam;
    5907             : 
    5908        4082 :     return node;
    5909             : }
    5910             : 
    5911             : static NamedTuplestoreScan *
    5912         462 : make_namedtuplestorescan(List *qptlist,
    5913             :                          List *qpqual,
    5914             :                          Index scanrelid,
    5915             :                          char *enrname)
    5916             : {
    5917         462 :     NamedTuplestoreScan *node = makeNode(NamedTuplestoreScan);
    5918         462 :     Plan       *plan = &node->scan.plan;
    5919             : 
    5920             :     /* cost should be inserted by caller */
    5921         462 :     plan->targetlist = qptlist;
    5922         462 :     plan->qual = qpqual;
    5923         462 :     plan->lefttree = NULL;
    5924         462 :     plan->righttree = NULL;
    5925         462 :     node->scan.scanrelid = scanrelid;
    5926         462 :     node->enrname = enrname;
    5927             : 
    5928         462 :     return node;
    5929             : }
    5930             : 
    5931             : static WorkTableScan *
    5932        1004 : make_worktablescan(List *qptlist,
    5933             :                    List *qpqual,
    5934             :                    Index scanrelid,
    5935             :                    int wtParam)
    5936             : {
    5937        1004 :     WorkTableScan *node = makeNode(WorkTableScan);
    5938        1004 :     Plan       *plan = &node->scan.plan;
    5939             : 
    5940        1004 :     plan->targetlist = qptlist;
    5941        1004 :     plan->qual = qpqual;
    5942        1004 :     plan->lefttree = NULL;
    5943        1004 :     plan->righttree = NULL;
    5944        1004 :     node->scan.scanrelid = scanrelid;
    5945        1004 :     node->wtParam = wtParam;
    5946             : 
    5947        1004 :     return node;
    5948             : }
    5949             : 
    5950             : ForeignScan *
    5951        2046 : make_foreignscan(List *qptlist,
    5952             :                  List *qpqual,
    5953             :                  Index scanrelid,
    5954             :                  List *fdw_exprs,
    5955             :                  List *fdw_private,
    5956             :                  List *fdw_scan_tlist,
    5957             :                  List *fdw_recheck_quals,
    5958             :                  Plan *outer_plan)
    5959             : {
    5960        2046 :     ForeignScan *node = makeNode(ForeignScan);
    5961        2046 :     Plan       *plan = &node->scan.plan;
    5962             : 
    5963             :     /* cost will be filled in by create_foreignscan_plan */
    5964        2046 :     plan->targetlist = qptlist;
    5965        2046 :     plan->qual = qpqual;
    5966        2046 :     plan->lefttree = outer_plan;
    5967        2046 :     plan->righttree = NULL;
    5968        2046 :     node->scan.scanrelid = scanrelid;
    5969             : 
    5970             :     /* these may be overridden by the FDW's PlanDirectModify callback. */
    5971        2046 :     node->operation = CMD_SELECT;
    5972        2046 :     node->resultRelation = 0;
    5973             : 
    5974             :     /* checkAsUser, fs_server will be filled in by create_foreignscan_plan */
    5975        2046 :     node->checkAsUser = InvalidOid;
    5976        2046 :     node->fs_server = InvalidOid;
    5977        2046 :     node->fdw_exprs = fdw_exprs;
    5978        2046 :     node->fdw_private = fdw_private;
    5979        2046 :     node->fdw_scan_tlist = fdw_scan_tlist;
    5980        2046 :     node->fdw_recheck_quals = fdw_recheck_quals;
    5981             :     /* fs_relids, fs_base_relids will be filled by create_foreignscan_plan */
    5982        2046 :     node->fs_relids = NULL;
    5983        2046 :     node->fs_base_relids = NULL;
    5984             :     /* fsSystemCol will be filled in by create_foreignscan_plan */
    5985        2046 :     node->fsSystemCol = false;
    5986             : 
    5987        2046 :     return node;
    5988             : }
    5989             : 
    5990             : static RecursiveUnion *
    5991        1004 : make_recursive_union(List *tlist,
    5992             :                      Plan *lefttree,
    5993             :                      Plan *righttree,
    5994             :                      int wtParam,
    5995             :                      List *distinctList,
    5996             :                      long numGroups)
    5997             : {
    5998        1004 :     RecursiveUnion *node = makeNode(RecursiveUnion);
    5999        1004 :     Plan       *plan = &node->plan;
    6000        1004 :     int         numCols = list_length(distinctList);
    6001             : 
    6002        1004 :     plan->targetlist = tlist;
    6003        1004 :     plan->qual = NIL;
    6004        1004 :     plan->lefttree = lefttree;
    6005        1004 :     plan->righttree = righttree;
    6006        1004 :     node->wtParam = wtParam;
    6007             : 
    6008             :     /*
    6009             :      * convert SortGroupClause list into arrays of attr indexes and equality
    6010             :      * operators, as wanted by executor
    6011             :      */
    6012        1004 :     node->numCols = numCols;
    6013        1004 :     if (numCols > 0)
    6014             :     {
    6015         484 :         int         keyno = 0;
    6016             :         AttrNumber *dupColIdx;
    6017             :         Oid        *dupOperators;
    6018             :         Oid        *dupCollations;
    6019             :         ListCell   *slitem;
    6020             : 
    6021         484 :         dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
    6022         484 :         dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
    6023         484 :         dupCollations = (Oid *) palloc(sizeof(Oid) * numCols);
    6024             : 
    6025        1864 :         foreach(slitem, distinctList)
    6026             :         {
    6027        1380 :             SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
    6028        1380 :             TargetEntry *tle = get_sortgroupclause_tle(sortcl,
    6029             :                                                        plan->targetlist);
    6030             : 
    6031        1380 :             dupColIdx[keyno] = tle->resno;
    6032        1380 :             dupOperators[keyno] = sortcl->eqop;
    6033        1380 :             dupCollations[keyno] = exprCollation((Node *) tle->expr);
    6034             :             Assert(OidIsValid(dupOperators[keyno]));
    6035        1380 :             keyno++;
    6036             :         }
    6037         484 :         node->dupColIdx = dupColIdx;
    6038         484 :         node->dupOperators = dupOperators;
    6039         484 :         node->dupCollations = dupCollations;
    6040             :     }
    6041        1004 :     node->numGroups = numGroups;
    6042             : 
    6043        1004 :     return node;
    6044             : }
    6045             : 
    6046             : static BitmapAnd *
    6047         222 : make_bitmap_and(List *bitmapplans)
    6048             : {
    6049         222 :     BitmapAnd  *node = makeNode(BitmapAnd);
    6050         222 :     Plan       *plan = &node->plan;
    6051             : 
    6052         222 :     plan->targetlist = NIL;
    6053         222 :     plan->qual = NIL;
    6054         222 :     plan->lefttree = NULL;
    6055         222 :     plan->righttree = NULL;
    6056         222 :     node->bitmapplans = bitmapplans;
    6057             : 
    6058         222 :     return node;
    6059             : }
    6060             : 
    6061             : static BitmapOr *
    6062         392 : make_bitmap_or(List *bitmapplans)
    6063             : {
    6064         392 :     BitmapOr   *node = makeNode(BitmapOr);
    6065         392 :     Plan       *plan = &node->plan;
    6066             : 
    6067         392 :     plan->targetlist = NIL;
    6068         392 :     plan->qual = NIL;
    6069         392 :     plan->lefttree = NULL;
    6070         392 :     plan->righttree = NULL;
    6071         392 :     node->bitmapplans = bitmapplans;
    6072             : 
    6073         392 :     return node;
    6074             : }
    6075             : 
    6076             : static NestLoop *
    6077       94430 : make_nestloop(List *tlist,
    6078             :               List *joinclauses,
    6079             :               List *otherclauses,
    6080             :               List *nestParams,
    6081             :               Plan *lefttree,
    6082             :               Plan *righttree,
    6083             :               JoinType jointype,
    6084             :               bool inner_unique)
    6085             : {
    6086       94430 :     NestLoop   *node = makeNode(NestLoop);
    6087       94430 :     Plan       *plan = &node->join.plan;
    6088             : 
    6089       94430 :     plan->targetlist = tlist;
    6090       94430 :     plan->qual = otherclauses;
    6091       94430 :     plan->lefttree = lefttree;
    6092       94430 :     plan->righttree = righttree;
    6093       94430 :     node->join.jointype = jointype;
    6094       94430 :     node->join.inner_unique = inner_unique;
    6095       94430 :     node->join.joinqual = joinclauses;
    6096       94430 :     node->nestParams = nestParams;
    6097             : 
    6098       94430 :     return node;
    6099             : }
    6100             : 
    6101             : static HashJoin *
    6102       33270 : make_hashjoin(List *tlist,
    6103             :               List *joinclauses,
    6104             :               List *otherclauses,
    6105             :               List *hashclauses,
    6106             :               List *hashoperators,
    6107             :               List *hashcollations,
    6108             :               List *hashkeys,
    6109             :               Plan *lefttree,
    6110             :               Plan *righttree,
    6111             :               JoinType jointype,
    6112             :               bool inner_unique)
    6113             : {
    6114       33270 :     HashJoin   *node = makeNode(HashJoin);
    6115       33270 :     Plan       *plan = &node->join.plan;
    6116             : 
    6117       33270 :     plan->targetlist = tlist;
    6118       33270 :     plan->qual = otherclauses;
    6119       33270 :     plan->lefttree = lefttree;
    6120       33270 :     plan->righttree = righttree;
    6121       33270 :     node->hashclauses = hashclauses;
    6122       33270 :     node->hashoperators = hashoperators;
    6123       33270 :     node->hashcollations = hashcollations;
    6124       33270 :     node->hashkeys = hashkeys;
    6125       33270 :     node->join.jointype = jointype;
    6126       33270 :     node->join.inner_unique = inner_unique;
    6127       33270 :     node->join.joinqual = joinclauses;
    6128             : 
    6129       33270 :     return node;
    6130             : }
    6131             : 
    6132             : static Hash *
    6133       33270 : make_hash(Plan *lefttree,
    6134             :           List *hashkeys,
    6135             :           Oid skewTable,
    6136             :           AttrNumber skewColumn,
    6137             :           bool skewInherit)
    6138             : {
    6139       33270 :     Hash       *node = makeNode(Hash);
    6140       33270 :     Plan       *plan = &node->plan;
    6141             : 
    6142       33270 :     plan->targetlist = lefttree->targetlist;
    6143       33270 :     plan->qual = NIL;
    6144       33270 :     plan->lefttree = lefttree;
    6145       33270 :     plan->righttree = NULL;
    6146             : 
    6147       33270 :     node->hashkeys = hashkeys;
    6148       33270 :     node->skewTable = skewTable;
    6149       33270 :     node->skewColumn = skewColumn;
    6150       33270 :     node->skewInherit = skewInherit;
    6151             : 
    6152       33270 :     return node;
    6153             : }
    6154             : 
    6155             : static MergeJoin *
    6156        8070 : make_mergejoin(List *tlist,
    6157             :                List *joinclauses,
    6158             :                List *otherclauses,
    6159             :                List *mergeclauses,
    6160             :                Oid *mergefamilies,
    6161             :                Oid *mergecollations,
    6162             :                bool *mergereversals,
    6163             :                bool *mergenullsfirst,
    6164             :                Plan *lefttree,
    6165             :                Plan *righttree,
    6166             :                JoinType jointype,
    6167             :                bool inner_unique,
    6168             :                bool skip_mark_restore)
    6169             : {
    6170        8070 :     MergeJoin  *node = makeNode(MergeJoin);
    6171        8070 :     Plan       *plan = &node->join.plan;
    6172             : 
    6173        8070 :     plan->targetlist = tlist;
    6174        8070 :     plan->qual = otherclauses;
    6175        8070 :     plan->lefttree = lefttree;
    6176        8070 :     plan->righttree = righttree;
    6177        8070 :     node->skip_mark_restore = skip_mark_restore;
    6178        8070 :     node->mergeclauses = mergeclauses;
    6179        8070 :     node->mergeFamilies = mergefamilies;
    6180        8070 :     node->mergeCollations = mergecollations;
    6181        8070 :     node->mergeReversals = mergereversals;
    6182        8070 :     node->mergeNullsFirst = mergenullsfirst;
    6183        8070 :     node->join.jointype = jointype;
    6184        8070 :     node->join.inner_unique = inner_unique;
    6185        8070 :     node->join.joinqual = joinclauses;
    6186             : 
    6187        8070 :     return node;
    6188             : }
    6189             : 
    6190             : /*
    6191             :  * make_sort --- basic routine to build a Sort plan node
    6192             :  *
    6193             :  * Caller must have built the sortColIdx, sortOperators, collations, and
    6194             :  * nullsFirst arrays already.
    6195             :  */
    6196             : static Sort *
    6197       81364 : make_sort(Plan *lefttree, int numCols,
    6198             :           AttrNumber *sortColIdx, Oid *sortOperators,
    6199             :           Oid *collations, bool *nullsFirst)
    6200             : {
    6201             :     Sort       *node;
    6202             :     Plan       *plan;
    6203             : 
    6204       81364 :     node = makeNode(Sort);
    6205             : 
    6206       81364 :     plan = &node->plan;
    6207       81364 :     plan->targetlist = lefttree->targetlist;
    6208       81364 :     plan->disabled_nodes = lefttree->disabled_nodes + (enable_sort == false);
    6209       81364 :     plan->qual = NIL;
    6210       81364 :     plan->lefttree = lefttree;
    6211       81364 :     plan->righttree = NULL;
    6212       81364 :     node->numCols = numCols;
    6213       81364 :     node->sortColIdx = sortColIdx;
    6214       81364 :     node->sortOperators = sortOperators;
    6215       81364 :     node->collations = collations;
    6216       81364 :     node->nullsFirst = nullsFirst;
    6217             : 
    6218       81364 :     return node;
    6219             : }
    6220             : 
    6221             : /*
    6222             :  * make_incrementalsort --- basic routine to build an IncrementalSort plan node
    6223             :  *
    6224             :  * Caller must have built the sortColIdx, sortOperators, collations, and
    6225             :  * nullsFirst arrays already.
    6226             :  */
    6227             : static IncrementalSort *
    6228         980 : make_incrementalsort(Plan *lefttree, int numCols, int nPresortedCols,
    6229             :                      AttrNumber *sortColIdx, Oid *sortOperators,
    6230             :                      Oid *collations, bool *nullsFirst)
    6231             : {
    6232             :     IncrementalSort *node;
    6233             :     Plan       *plan;
    6234             : 
    6235         980 :     node = makeNode(IncrementalSort);
    6236             : 
    6237         980 :     plan = &node->sort.plan;
    6238         980 :     plan->targetlist = lefttree->targetlist;
    6239         980 :     plan->qual = NIL;
    6240         980 :     plan->lefttree = lefttree;
    6241         980 :     plan->righttree = NULL;
    6242         980 :     node->nPresortedCols = nPresortedCols;
    6243         980 :     node->sort.numCols = numCols;
    6244         980 :     node->sort.sortColIdx = sortColIdx;
    6245         980 :     node->sort.sortOperators = sortOperators;
    6246         980 :     node->sort.collations = collations;
    6247         980 :     node->sort.nullsFirst = nullsFirst;
    6248             : 
    6249         980 :     return node;
    6250             : }
    6251             : 
    6252             : /*
    6253             :  * prepare_sort_from_pathkeys
    6254             :  *    Prepare to sort according to given pathkeys
    6255             :  *
    6256             :  * This is used to set up for Sort, MergeAppend, and Gather Merge nodes.  It
    6257             :  * calculates the executor's representation of the sort key information, and
    6258             :  * adjusts the plan targetlist if needed to add resjunk sort columns.
    6259             :  *
    6260             :  * Input parameters:
    6261             :  *    'lefttree' is the plan node which yields input tuples
    6262             :  *    'pathkeys' is the list of pathkeys by which the result is to be sorted
    6263             :  *    'relids' identifies the child relation being sorted, if any
    6264             :  *    'reqColIdx' is NULL or an array of required sort key column numbers
    6265             :  *    'adjust_tlist_in_place' is true if lefttree must be modified in-place
    6266             :  *
    6267             :  * We must convert the pathkey information into arrays of sort key column
    6268             :  * numbers, sort operator OIDs, collation OIDs, and nulls-first flags,
    6269             :  * which is the representation the executor wants.  These are returned into
    6270             :  * the output parameters *p_numsortkeys etc.
    6271             :  *
    6272             :  * When looking for matches to an EquivalenceClass's members, we will only
    6273             :  * consider child EC members if they belong to given 'relids'.  This protects
    6274             :  * against possible incorrect matches to child expressions that contain no
    6275             :  * Vars.
    6276             :  *
    6277             :  * If reqColIdx isn't NULL then it contains sort key column numbers that
    6278             :  * we should match.  This is used when making child plans for a MergeAppend;
    6279             :  * it's an error if we can't match the columns.
    6280             :  *
    6281             :  * If the pathkeys include expressions that aren't simple Vars, we will
    6282             :  * usually need to add resjunk items to the input plan's targetlist to
    6283             :  * compute these expressions, since a Sort or MergeAppend node itself won't
    6284             :  * do any such calculations.  If the input plan type isn't one that can do
    6285             :  * projections, this means adding a Result node just to do the projection.
    6286             :  * However, the caller can pass adjust_tlist_in_place = true to force the
    6287             :  * lefttree tlist to be modified in-place regardless of whether the node type
    6288             :  * can project --- we use this for fixing the tlist of MergeAppend itself.
    6289             :  *
    6290             :  * Returns the node which is to be the input to the Sort (either lefttree,
    6291             :  * or a Result stacked atop lefttree).
    6292             :  */
    6293             : static Plan *
    6294       85422 : prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
    6295             :                            Relids relids,
    6296             :                            const AttrNumber *reqColIdx,
    6297             :                            bool adjust_tlist_in_place,
    6298             :                            int *p_numsortkeys,
    6299             :                            AttrNumber **p_sortColIdx,
    6300             :                            Oid **p_sortOperators,
    6301             :                            Oid **p_collations,
    6302             :                            bool **p_nullsFirst)
    6303             : {
    6304       85422 :     List       *tlist = lefttree->targetlist;
    6305             :     ListCell   *i;
    6306             :     int         numsortkeys;
    6307             :     AttrNumber *sortColIdx;
    6308             :     Oid        *sortOperators;
    6309             :     Oid        *collations;
    6310             :     bool       *nullsFirst;
    6311             : 
    6312             :     /*
    6313             :      * We will need at most list_length(pathkeys) sort columns; possibly less
    6314             :      */
    6315       85422 :     numsortkeys = list_length(pathkeys);
    6316       85422 :     sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
    6317       85422 :     sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
    6318       85422 :     collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
    6319       85422 :     nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
    6320             : 
    6321       85422 :     numsortkeys = 0;
    6322             : 
    6323      211488 :     foreach(i, pathkeys)
    6324             :     {
    6325      126066 :         PathKey    *pathkey = (PathKey *) lfirst(i);
    6326      126066 :         EquivalenceClass *ec = pathkey->pk_eclass;
    6327             :         EquivalenceMember *em;
    6328      126066 :         TargetEntry *tle = NULL;
    6329      126066 :         Oid         pk_datatype = InvalidOid;
    6330             :         Oid         sortop;
    6331             :         ListCell   *j;
    6332             : 
    6333      126066 :         if (ec->ec_has_volatile)
    6334             :         {
    6335             :             /*
    6336             :              * If the pathkey's EquivalenceClass is volatile, then it must
    6337             :              * have come from an ORDER BY clause, and we have to match it to
    6338             :              * that same targetlist entry.
    6339             :              */
    6340         200 :             if (ec->ec_sortref == 0) /* can't happen */
    6341           0 :                 elog(ERROR, "volatile EquivalenceClass has no sortref");
    6342         200 :             tle = get_sortgroupref_tle(ec->ec_sortref, tlist);
    6343             :             Assert(tle);
    6344             :             Assert(list_length(ec->ec_members) == 1);
    6345         200 :             pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
    6346             :         }
    6347      125866 :         else if (reqColIdx != NULL)
    6348             :         {
    6349             :             /*
    6350             :              * If we are given a sort column number to match, only consider
    6351             :              * the single TLE at that position.  It's possible that there is
    6352             :              * no such TLE, in which case fall through and generate a resjunk
    6353             :              * targetentry (we assume this must have happened in the parent
    6354             :              * plan as well).  If there is a TLE but it doesn't match the
    6355             :              * pathkey's EC, we do the same, which is probably the wrong thing
    6356             :              * but we'll leave it to caller to complain about the mismatch.
    6357             :              */
    6358        3136 :             tle = get_tle_by_resno(tlist, reqColIdx[numsortkeys]);
    6359        3136 :             if (tle)
    6360             :             {
    6361        3016 :                 em = find_ec_member_matching_expr(ec, tle->expr, relids);
    6362        3016 :                 if (em)
    6363             :                 {
    6364             :                     /* found expr at right place in tlist */
    6365        3016 :                     pk_datatype = em->em_datatype;
    6366             :                 }
    6367             :                 else
    6368           0 :                     tle = NULL;
    6369             :             }
    6370             :         }
    6371             :         else
    6372             :         {
    6373             :             /*
    6374             :              * Otherwise, we can sort by any non-constant expression listed in
    6375             :              * the pathkey's EquivalenceClass.  For now, we take the first
    6376             :              * tlist item found in the EC. If there's no match, we'll generate
    6377             :              * a resjunk entry using the first EC member that is an expression
    6378             :              * in the input's vars.
    6379             :              *
    6380             :              * XXX if we have a choice, is there any way of figuring out which
    6381             :              * might be cheapest to execute?  (For example, int4lt is likely
    6382             :              * much cheaper to execute than numericlt, but both might appear
    6383             :              * in the same equivalence class...)  Not clear that we ever will
    6384             :              * have an interesting choice in practice, so it may not matter.
    6385             :              */
    6386      308442 :             foreach(j, tlist)
    6387             :             {
    6388      308192 :                 tle = (TargetEntry *) lfirst(j);
    6389      308192 :                 em = find_ec_member_matching_expr(ec, tle->expr, relids);
    6390      308192 :                 if (em)
    6391             :                 {
    6392             :                     /* found expr already in tlist */
    6393      122480 :                     pk_datatype = em->em_datatype;
    6394      122480 :                     break;
    6395             :                 }
    6396      185712 :                 tle = NULL;
    6397             :             }
    6398             :         }
    6399             : 
    6400      126066 :         if (!tle)
    6401             :         {
    6402             :             /*
    6403             :              * No matching tlist item; look for a computable expression.
    6404             :              */
    6405         370 :             em = find_computable_ec_member(NULL, ec, tlist, relids, false);
    6406         370 :             if (!em)
    6407           0 :                 elog(ERROR, "could not find pathkey item to sort");
    6408         370 :             pk_datatype = em->em_datatype;
    6409             : 
    6410             :             /*
    6411             :              * Do we need to insert a Result node?
    6412             :              */
    6413         370 :             if (!adjust_tlist_in_place &&
    6414         334 :                 !is_projection_capable_plan(lefttree))
    6415             :             {
    6416             :                 /* copy needed so we don't modify input's tlist below */
    6417          26 :                 tlist = copyObject(tlist);
    6418          26 :                 lefttree = inject_projection_plan(lefttree, tlist,
    6419          26 :                                                   lefttree->parallel_safe);
    6420             :             }
    6421             : 
    6422             :             /* Don't bother testing is_projection_capable_plan again */
    6423         370 :             adjust_tlist_in_place = true;
    6424             : 
    6425             :             /*
    6426             :              * Add resjunk entry to input's tlist
    6427             :              */
    6428         370 :             tle = makeTargetEntry(copyObject(em->em_expr),
    6429         370 :                                   list_length(tlist) + 1,
    6430             :                                   NULL,
    6431             :                                   true);
    6432         370 :             tlist = lappend(tlist, tle);
    6433         370 :             lefttree->targetlist = tlist;    /* just in case NIL before */
    6434             :         }
    6435             : 
    6436             :         /*
    6437             :          * Look up the correct sort operator from the PathKey's slightly
    6438             :          * abstracted representation.
    6439             :          */
    6440      126066 :         sortop = get_opfamily_member_for_cmptype(pathkey->pk_opfamily,
    6441             :                                                  pk_datatype,
    6442             :                                                  pk_datatype,
    6443             :                                                  pathkey->pk_cmptype);
    6444      126066 :         if (!OidIsValid(sortop))    /* should not happen */
    6445           0 :             elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
    6446             :                  pathkey->pk_cmptype, pk_datatype, pk_datatype,
    6447             :                  pathkey->pk_opfamily);
    6448             : 
    6449             :         /* Add the column to the sort arrays */
    6450      126066 :         sortColIdx[numsortkeys] = tle->resno;
    6451      126066 :         sortOperators[numsortkeys] = sortop;
    6452      126066 :         collations[numsortkeys] = ec->ec_collation;
    6453      126066 :         nullsFirst[numsortkeys] = pathkey->pk_nulls_first;
    6454      126066 :         numsortkeys++;
    6455             :     }
    6456             : 
    6457             :     /* Return results */
    6458       85422 :     *p_numsortkeys = numsortkeys;
    6459       85422 :     *p_sortColIdx = sortColIdx;
    6460       85422 :     *p_sortOperators = sortOperators;
    6461       85422 :     *p_collations = collations;
    6462       85422 :     *p_nullsFirst = nullsFirst;
    6463             : 
    6464       85422 :     return lefttree;
    6465             : }
    6466             : 
    6467             : /*
    6468             :  * make_sort_from_pathkeys
    6469             :  *    Create sort plan to sort according to given pathkeys
    6470             :  *
    6471             :  *    'lefttree' is the node which yields input tuples
    6472             :  *    'pathkeys' is the list of pathkeys by which the result is to be sorted
    6473             :  *    'relids' is the set of relations required by prepare_sort_from_pathkeys()
    6474             :  */
    6475             : static Sort *
    6476       81014 : make_sort_from_pathkeys(Plan *lefttree, List *pathkeys, Relids relids)
    6477             : {
    6478             :     int         numsortkeys;
    6479             :     AttrNumber *sortColIdx;
    6480             :     Oid        *sortOperators;
    6481             :     Oid        *collations;
    6482             :     bool       *nullsFirst;
    6483             : 
    6484             :     /* Compute sort column info, and adjust lefttree as needed */
    6485       81014 :     lefttree = prepare_sort_from_pathkeys(lefttree, pathkeys,
    6486             :                                           relids,
    6487             :                                           NULL,
    6488             :                                           false,
    6489             :                                           &numsortkeys,
    6490             :                                           &sortColIdx,
    6491             :                                           &sortOperators,
    6492             :                                           &collations,
    6493             :                                           &nullsFirst);
    6494             : 
    6495             :     /* Now build the Sort node */
    6496       81014 :     return make_sort(lefttree, numsortkeys,
    6497             :                      sortColIdx, sortOperators,
    6498             :                      collations, nullsFirst);
    6499             : }
    6500             : 
    6501             : /*
    6502             :  * make_incrementalsort_from_pathkeys
    6503             :  *    Create sort plan to sort according to given pathkeys
    6504             :  *
    6505             :  *    'lefttree' is the node which yields input tuples
    6506             :  *    'pathkeys' is the list of pathkeys by which the result is to be sorted
    6507             :  *    'relids' is the set of relations required by prepare_sort_from_pathkeys()
    6508             :  *    'nPresortedCols' is the number of presorted columns in input tuples
    6509             :  */
    6510             : static IncrementalSort *
    6511         980 : make_incrementalsort_from_pathkeys(Plan *lefttree, List *pathkeys,
    6512             :                                    Relids relids, int nPresortedCols)
    6513             : {
    6514             :     int         numsortkeys;
    6515             :     AttrNumber *sortColIdx;
    6516             :     Oid        *sortOperators;
    6517             :     Oid        *collations;
    6518             :     bool       *nullsFirst;
    6519             : 
    6520             :     /* Compute sort column info, and adjust lefttree as needed */
    6521         980 :     lefttree = prepare_sort_from_pathkeys(lefttree, pathkeys,
    6522             :                                           relids,
    6523             :                                           NULL,
    6524             :                                           false,
    6525             :                                           &numsortkeys,
    6526             :                                           &sortColIdx,
    6527             :                                           &sortOperators,
    6528             :                                           &collations,
    6529             :                                           &nullsFirst);
    6530             : 
    6531             :     /* Now build the Sort node */
    6532         980 :     return make_incrementalsort(lefttree, numsortkeys, nPresortedCols,
    6533             :                                 sortColIdx, sortOperators,
    6534             :                                 collations, nullsFirst);
    6535             : }
    6536             : 
    6537             : /*
    6538             :  * make_sort_from_sortclauses
    6539             :  *    Create sort plan to sort according to given sortclauses
    6540             :  *
    6541             :  *    'sortcls' is a list of SortGroupClauses
    6542             :  *    'lefttree' is the node which yields input tuples
    6543             :  */
    6544             : Sort *
    6545          26 : make_sort_from_sortclauses(List *sortcls, Plan *lefttree)
    6546             : {
    6547          26 :     List       *sub_tlist = lefttree->targetlist;
    6548             :     ListCell   *l;
    6549             :     int         numsortkeys;
    6550             :     AttrNumber *sortColIdx;
    6551             :     Oid        *sortOperators;
    6552             :     Oid        *collations;
    6553             :     bool       *nullsFirst;
    6554             : 
    6555             :     /* Convert list-ish representation to arrays wanted by executor */
    6556          26 :     numsortkeys = list_length(sortcls);
    6557          26 :     sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
    6558          26 :     sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
    6559          26 :     collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
    6560          26 :     nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
    6561             : 
    6562          26 :     numsortkeys = 0;
    6563          52 :     foreach(l, sortcls)
    6564             :     {
    6565          26 :         SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
    6566          26 :         TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
    6567             : 
    6568          26 :         sortColIdx[numsortkeys] = tle->resno;
    6569          26 :         sortOperators[numsortkeys] = sortcl->sortop;
    6570          26 :         collations[numsortkeys] = exprCollation((Node *) tle->expr);
    6571          26 :         nullsFirst[numsortkeys] = sortcl->nulls_first;
    6572          26 :         numsortkeys++;
    6573             :     }
    6574             : 
    6575          26 :     return make_sort(lefttree, numsortkeys,
    6576             :                      sortColIdx, sortOperators,
    6577             :                      collations, nullsFirst);
    6578             : }
    6579             : 
    6580             : /*
    6581             :  * make_sort_from_groupcols
    6582             :  *    Create sort plan to sort based on grouping columns
    6583             :  *
    6584             :  * 'groupcls' is the list of SortGroupClauses
    6585             :  * 'grpColIdx' gives the column numbers to use
    6586             :  *
    6587             :  * This might look like it could be merged with make_sort_from_sortclauses,
    6588             :  * but presently we *must* use the grpColIdx[] array to locate sort columns,
    6589             :  * because the child plan's tlist is not marked with ressortgroupref info
    6590             :  * appropriate to the grouping node.  So, only the sort ordering info
    6591             :  * is used from the SortGroupClause entries.
    6592             :  */
    6593             : static Sort *
    6594         240 : make_sort_from_groupcols(List *groupcls,
    6595             :                          AttrNumber *grpColIdx,
    6596             :                          Plan *lefttree)
    6597             : {
    6598         240 :     List       *sub_tlist = lefttree->targetlist;
    6599             :     ListCell   *l;
    6600             :     int         numsortkeys;
    6601             :     AttrNumber *sortColIdx;
    6602             :     Oid        *sortOperators;
    6603             :     Oid        *collations;
    6604             :     bool       *nullsFirst;
    6605             : 
    6606             :     /* Convert list-ish representation to arrays wanted by executor */
    6607         240 :     numsortkeys = list_length(groupcls);
    6608         240 :     sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
    6609         240 :     sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
    6610         240 :     collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
    6611         240 :     nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
    6612             : 
    6613         240 :     numsortkeys = 0;
    6614         570 :     foreach(l, groupcls)
    6615             :     {
    6616         330 :         SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
    6617         330 :         TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[numsortkeys]);
    6618             : 
    6619         330 :         if (!tle)
    6620           0 :             elog(ERROR, "could not retrieve tle for sort-from-groupcols");
    6621             : 
    6622         330 :         sortColIdx[numsortkeys] = tle->resno;
    6623         330 :         sortOperators[numsortkeys] = grpcl->sortop;
    6624         330 :         collations[numsortkeys] = exprCollation((Node *) tle->expr);
    6625         330 :         nullsFirst[numsortkeys] = grpcl->nulls_first;
    6626         330 :         numsortkeys++;
    6627             :     }
    6628             : 
    6629         240 :     return make_sort(lefttree, numsortkeys,
    6630             :                      sortColIdx, sortOperators,
    6631             :                      collations, nullsFirst);
    6632             : }
    6633             : 
    6634             : static Material *
    6635        4894 : make_material(Plan *lefttree)
    6636             : {
    6637        4894 :     Material   *node = makeNode(Material);
    6638        4894 :     Plan       *plan = &node->plan;
    6639             : 
    6640        4894 :     plan->targetlist = lefttree->targetlist;
    6641        4894 :     plan->qual = NIL;
    6642        4894 :     plan->lefttree = lefttree;
    6643        4894 :     plan->righttree = NULL;
    6644             : 
    6645        4894 :     return node;
    6646             : }
    6647             : 
    6648             : /*
    6649             :  * materialize_finished_plan: stick a Material node atop a completed plan
    6650             :  *
    6651             :  * There are a couple of places where we want to attach a Material node
    6652             :  * after completion of create_plan(), without any MaterialPath path.
    6653             :  * Those places should probably be refactored someday to do this on the
    6654             :  * Path representation, but it's not worth the trouble yet.
    6655             :  */
    6656             : Plan *
    6657          74 : materialize_finished_plan(Plan *subplan)
    6658             : {
    6659             :     Plan       *matplan;
    6660             :     Path        matpath;        /* dummy for result of cost_material */
    6661             :     Cost        initplan_cost;
    6662             :     bool        unsafe_initplans;
    6663             : 
    6664          74 :     matplan = (Plan *) make_material(subplan);
    6665             : 
    6666             :     /*
    6667             :      * XXX horrid kluge: if there are any initPlans attached to the subplan,
    6668             :      * move them up to the Material node, which is now effectively the top
    6669             :      * plan node in its query level.  This prevents failure in
    6670             :      * SS_finalize_plan(), which see for comments.
    6671             :      */
    6672          74 :     matplan->initPlan = subplan->initPlan;
    6673          74 :     subplan->initPlan = NIL;
    6674             : 
    6675             :     /* Move the initplans' cost delta, as well */
    6676          74 :     SS_compute_initplan_cost(matplan->initPlan,
    6677             :                              &initplan_cost, &unsafe_initplans);
    6678          74 :     subplan->startup_cost -= initplan_cost;
    6679          74 :     subplan->total_cost -= initplan_cost;
    6680             : 
    6681             :     /* Set cost data */
    6682          74 :     cost_material(&matpath,
    6683             :                   subplan->disabled_nodes,
    6684             :                   subplan->startup_cost,
    6685             :                   subplan->total_cost,
    6686             :                   subplan->plan_rows,
    6687             :                   subplan->plan_width);
    6688          74 :     matplan->disabled_nodes = subplan->disabled_nodes;
    6689          74 :     matplan->startup_cost = matpath.startup_cost + initplan_cost;
    6690          74 :     matplan->total_cost = matpath.total_cost + initplan_cost;
    6691          74 :     matplan->plan_rows = subplan->plan_rows;
    6692          74 :     matplan->plan_width = subplan->plan_width;
    6693          74 :     matplan->parallel_aware = false;
    6694          74 :     matplan->parallel_safe = subplan->parallel_safe;
    6695             : 
    6696          74 :     return matplan;
    6697             : }
    6698             : 
    6699             : static Memoize *
    6700        1914 : make_memoize(Plan *lefttree, Oid *hashoperators, Oid *collations,
    6701             :              List *param_exprs, bool singlerow, bool binary_mode,
    6702             :              uint32 est_entries, Bitmapset *keyparamids)
    6703             : {
    6704        1914 :     Memoize    *node = makeNode(Memoize);
    6705        1914 :     Plan       *plan = &node->plan;
    6706             : 
    6707        1914 :     plan->targetlist = lefttree->targetlist;
    6708        1914 :     plan->qual = NIL;
    6709        1914 :     plan->lefttree = lefttree;
    6710        1914 :     plan->righttree = NULL;
    6711             : 
    6712        1914 :     node->numKeys = list_length(param_exprs);
    6713        1914 :     node->hashOperators = hashoperators;
    6714        1914 :     node->collations = collations;
    6715        1914 :     node->param_exprs = param_exprs;
    6716        1914 :     node->singlerow = singlerow;
    6717        1914 :     node->binary_mode = binary_mode;
    6718        1914 :     node->est_entries = est_entries;
    6719        1914 :     node->keyparamids = keyparamids;
    6720             : 
    6721        1914 :     return node;
    6722             : }
    6723             : 
    6724             : Agg *
    6725       42528 : make_agg(List *tlist, List *qual,
    6726             :          AggStrategy aggstrategy, AggSplit aggsplit,
    6727             :          int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, Oid *grpCollations,
    6728             :          List *groupingSets, List *chain, double dNumGroups,
    6729             :          Size transitionSpace, Plan *lefttree)
    6730             : {
    6731       42528 :     Agg        *node = makeNode(Agg);
    6732       42528 :     Plan       *plan = &node->plan;
    6733             :     long        numGroups;
    6734             : 
    6735             :     /* Reduce to long, but 'ware overflow! */
    6736       42528 :     numGroups = clamp_cardinality_to_long(dNumGroups);
    6737             : 
    6738       42528 :     node->aggstrategy = aggstrategy;
    6739       42528 :     node->aggsplit = aggsplit;
    6740       42528 :     node->numCols = numGroupCols;
    6741       42528 :     node->grpColIdx = grpColIdx;
    6742       42528 :     node->grpOperators = grpOperators;
    6743       42528 :     node->grpCollations = grpCollations;
    6744       42528 :     node->numGroups = numGroups;
    6745       42528 :     node->transitionSpace = transitionSpace;
    6746       42528 :     node->aggParams = NULL;      /* SS_finalize_plan() will fill this */
    6747       42528 :     node->groupingSets = groupingSets;
    6748       42528 :     node->chain = chain;
    6749             : 
    6750       42528 :     plan->qual = qual;
    6751       42528 :     plan->targetlist = tlist;
    6752       42528 :     plan->lefttree = lefttree;
    6753       42528 :     plan->righttree = NULL;
    6754             : 
    6755       42528 :     return node;
    6756             : }
    6757             : 
    6758             : static WindowAgg *
    6759        2546 : make_windowagg(List *tlist, WindowClause *wc,
    6760             :                int partNumCols, AttrNumber *partColIdx, Oid *partOperators, Oid *partCollations,
    6761             :                int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators, Oid *ordCollations,
    6762             :                List *runCondition, List *qual, bool topWindow, Plan *lefttree)
    6763             : {
    6764        2546 :     WindowAgg  *node = makeNode(WindowAgg);
    6765        2546 :     Plan       *plan = &node->plan;
    6766             : 
    6767        2546 :     node->winname = wc->name;
    6768        2546 :     node->winref = wc->winref;
    6769        2546 :     node->partNumCols = partNumCols;
    6770        2546 :     node->partColIdx = partColIdx;
    6771        2546 :     node->partOperators = partOperators;
    6772        2546 :     node->partCollations = partCollations;
    6773        2546 :     node->ordNumCols = ordNumCols;
    6774        2546 :     node->ordColIdx = ordColIdx;
    6775        2546 :     node->ordOperators = ordOperators;
    6776        2546 :     node->ordCollations = ordCollations;
    6777        2546 :     node->frameOptions = wc->frameOptions;
    6778        2546 :     node->startOffset = wc->startOffset;
    6779        2546 :     node->endOffset = wc->endOffset;
    6780        2546 :     node->runCondition = runCondition;
    6781             :     /* a duplicate of the above for EXPLAIN */
    6782        2546 :     node->runConditionOrig = runCondition;
    6783        2546 :     node->startInRangeFunc = wc->startInRangeFunc;
    6784        2546 :     node->endInRangeFunc = wc->endInRangeFunc;
    6785        2546 :     node->inRangeColl = wc->inRangeColl;
    6786        2546 :     node->inRangeAsc = wc->inRangeAsc;
    6787        2546 :     node->inRangeNullsFirst = wc->inRangeNullsFirst;
    6788        2546 :     node->topWindow = topWindow;
    6789             : 
    6790        2546 :     plan->targetlist = tlist;
    6791        2546 :     plan->lefttree = lefttree;
    6792        2546 :     plan->righttree = NULL;
    6793        2546 :     plan->qual = qual;
    6794             : 
    6795        2546 :     return node;
    6796             : }
    6797             : 
    6798             : static Group *
    6799         246 : make_group(List *tlist,
    6800             :            List *qual,
    6801             :            int numGroupCols,
    6802             :            AttrNumber *grpColIdx,
    6803             :            Oid *grpOperators,
    6804             :            Oid *grpCollations,
    6805             :            Plan *lefttree)
    6806             : {
    6807         246 :     Group      *node = makeNode(Group);
    6808         246 :     Plan       *plan = &node->plan;
    6809             : 
    6810         246 :     node->numCols = numGroupCols;
    6811         246 :     node->grpColIdx = grpColIdx;
    6812         246 :     node->grpOperators = grpOperators;
    6813         246 :     node->grpCollations = grpCollations;
    6814             : 
    6815         246 :     plan->qual = qual;
    6816         246 :     plan->targetlist = tlist;
    6817         246 :     plan->lefttree = lefttree;
    6818         246 :     plan->righttree = NULL;
    6819             : 
    6820         246 :     return node;
    6821             : }
    6822             : 
    6823             : /*
    6824             :  * distinctList is a list of SortGroupClauses, identifying the targetlist items
    6825             :  * that should be considered by the Unique filter.  The input path must
    6826             :  * already be sorted accordingly.
    6827             :  */
    6828             : static Unique *
    6829          26 : make_unique_from_sortclauses(Plan *lefttree, List *distinctList)
    6830             : {
    6831          26 :     Unique     *node = makeNode(Unique);
    6832          26 :     Plan       *plan = &node->plan;
    6833          26 :     int         numCols = list_length(distinctList);
    6834          26 :     int         keyno = 0;
    6835             :     AttrNumber *uniqColIdx;
    6836             :     Oid        *uniqOperators;
    6837             :     Oid        *uniqCollations;
    6838             :     ListCell   *slitem;
    6839             : 
    6840          26 :     plan->targetlist = lefttree->targetlist;
    6841          26 :     plan->qual = NIL;
    6842          26 :     plan->lefttree = lefttree;
    6843          26 :     plan->righttree = NULL;
    6844             : 
    6845             :     /*
    6846             :      * convert SortGroupClause list into arrays of attr indexes and equality
    6847             :      * operators, as wanted by executor
    6848             :      */
    6849             :     Assert(numCols > 0);
    6850          26 :     uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
    6851          26 :     uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
    6852          26 :     uniqCollations = (Oid *) palloc(sizeof(Oid) * numCols);
    6853             : 
    6854          52 :     foreach(slitem, distinctList)
    6855             :     {
    6856          26 :         SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
    6857          26 :         TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
    6858             : 
    6859          26 :         uniqColIdx[keyno] = tle->resno;
    6860          26 :         uniqOperators[keyno] = sortcl->eqop;
    6861          26 :         uniqCollations[keyno] = exprCollation((Node *) tle->expr);
    6862             :         Assert(OidIsValid(uniqOperators[keyno]));
    6863          26 :         keyno++;
    6864             :     }
    6865             : 
    6866          26 :     node->numCols = numCols;
    6867          26 :     node->uniqColIdx = uniqColIdx;
    6868          26 :     node->uniqOperators = uniqOperators;
    6869          26 :     node->uniqCollations = uniqCollations;
    6870             : 
    6871          26 :     return node;
    6872             : }
    6873             : 
    6874             : /*
    6875             :  * as above, but use pathkeys to identify the sort columns and semantics
    6876             :  */
    6877             : static Unique *
    6878        5538 : make_unique_from_pathkeys(Plan *lefttree, List *pathkeys, int numCols)
    6879             : {
    6880        5538 :     Unique     *node = makeNode(Unique);
    6881        5538 :     Plan       *plan = &node->plan;
    6882        5538 :     int         keyno = 0;
    6883             :     AttrNumber *uniqColIdx;
    6884             :     Oid        *uniqOperators;
    6885             :     Oid        *uniqCollations;
    6886             :     ListCell   *lc;
    6887             : 
    6888        5538 :     plan->targetlist = lefttree->targetlist;
    6889        5538 :     plan->qual = NIL;
    6890        5538 :     plan->lefttree = lefttree;
    6891        5538 :     plan->righttree = NULL;
    6892             : 
    6893             :     /*
    6894             :      * Convert pathkeys list into arrays of attr indexes and equality
    6895             :      * operators, as wanted by executor.  This has a lot in common with
    6896             :      * prepare_sort_from_pathkeys ... maybe unify sometime?
    6897             :      */
    6898             :     Assert(numCols >= 0 && numCols <= list_length(pathkeys));
    6899        5538 :     uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
    6900        5538 :     uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
    6901        5538 :     uniqCollations = (Oid *) palloc(sizeof(Oid) * numCols);
    6902             : 
    6903       18164 :     foreach(lc, pathkeys)
    6904             :     {
    6905       12668 :         PathKey    *pathkey = (PathKey *) lfirst(lc);
    6906       12668 :         EquivalenceClass *ec = pathkey->pk_eclass;
    6907             :         EquivalenceMember *em;
    6908       12668 :         TargetEntry *tle = NULL;
    6909       12668 :         Oid         pk_datatype = InvalidOid;
    6910             :         Oid         eqop;
    6911             :         ListCell   *j;
    6912             : 
    6913             :         /* Ignore pathkeys beyond the specified number of columns */
    6914       12668 :         if (keyno >= numCols)
    6915          42 :             break;
    6916             : 
    6917       12626 :         if (ec->ec_has_volatile)
    6918             :         {
    6919             :             /*
    6920             :              * If the pathkey's EquivalenceClass is volatile, then it must
    6921             :              * have come from an ORDER BY clause, and we have to match it to
    6922             :              * that same targetlist entry.
    6923             :              */
    6924          30 :             if (ec->ec_sortref == 0) /* can't happen */
    6925           0 :                 elog(ERROR, "volatile EquivalenceClass has no sortref");
    6926          30 :             tle = get_sortgroupref_tle(ec->ec_sortref, plan->targetlist);
    6927             :             Assert(tle);
    6928             :             Assert(list_length(ec->ec_members) == 1);
    6929          30 :             pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
    6930             :         }
    6931             :         else
    6932             :         {
    6933             :             /*
    6934             :              * Otherwise, we can use any non-constant expression listed in the
    6935             :              * pathkey's EquivalenceClass.  For now, we take the first tlist
    6936             :              * item found in the EC.
    6937             :              */
    6938       24352 :             foreach(j, plan->targetlist)
    6939             :             {
    6940       24352 :                 tle = (TargetEntry *) lfirst(j);
    6941       24352 :                 em = find_ec_member_matching_expr(ec, tle->expr, NULL);
    6942       24352 :                 if (em)
    6943             :                 {
    6944             :                     /* found expr already in tlist */
    6945       12596 :                     pk_datatype = em->em_datatype;
    6946       12596 :                     break;
    6947             :                 }
    6948       11756 :                 tle = NULL;
    6949             :             }
    6950             :         }
    6951             : 
    6952       12626 :         if (!tle)
    6953           0 :             elog(ERROR, "could not find pathkey item to sort");
    6954             : 
    6955             :         /*
    6956             :          * Look up the correct equality operator from the PathKey's slightly
    6957             :          * abstracted representation.
    6958             :          */
    6959       12626 :         eqop = get_opfamily_member_for_cmptype(pathkey->pk_opfamily,
    6960             :                                                pk_datatype,
    6961             :                                                pk_datatype,
    6962             :                                                COMPARE_EQ);
    6963       12626 :         if (!OidIsValid(eqop))  /* should not happen */
    6964           0 :             elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
    6965             :                  COMPARE_EQ, pk_datatype, pk_datatype,
    6966             :                  pathkey->pk_opfamily);
    6967             : 
    6968       12626 :         uniqColIdx[keyno] = tle->resno;
    6969       12626 :         uniqOperators[keyno] = eqop;
    6970       12626 :         uniqCollations[keyno] = ec->ec_collation;
    6971             : 
    6972       12626 :         keyno++;
    6973             :     }
    6974             : 
    6975        5538 :     node->numCols = numCols;
    6976        5538 :     node->uniqColIdx = uniqColIdx;
    6977        5538 :     node->uniqOperators = uniqOperators;
    6978        5538 :     node->uniqCollations = uniqCollations;
    6979             : 
    6980        5538 :     return node;
    6981             : }
    6982             : 
    6983             : static Gather *
    6984         950 : make_gather(List *qptlist,
    6985             :             List *qpqual,
    6986             :             int nworkers,
    6987             :             int rescan_param,
    6988             :             bool single_copy,
    6989             :             Plan *subplan)
    6990             : {
    6991         950 :     Gather     *node = makeNode(Gather);
    6992         950 :     Plan       *plan = &node->plan;
    6993             : 
    6994         950 :     plan->targetlist = qptlist;
    6995         950 :     plan->qual = qpqual;
    6996         950 :     plan->lefttree = subplan;
    6997         950 :     plan->righttree = NULL;
    6998         950 :     node->num_workers = nworkers;
    6999         950 :     node->rescan_param = rescan_param;
    7000         950 :     node->single_copy = single_copy;
    7001         950 :     node->invisible = false;
    7002         950 :     node->initParam = NULL;
    7003             : 
    7004         950 :     return node;
    7005             : }
    7006             : 
    7007             : /*
    7008             :  * groupList is a list of SortGroupClauses, identifying the targetlist
    7009             :  * items that should be considered by the SetOp filter.  The input plans must
    7010             :  * already be sorted accordingly, if we're doing SETOP_SORTED mode.
    7011             :  */
    7012             : static SetOp *
    7013         662 : make_setop(SetOpCmd cmd, SetOpStrategy strategy,
    7014             :            List *tlist, Plan *lefttree, Plan *righttree,
    7015             :            List *groupList, long numGroups)
    7016             : {
    7017         662 :     SetOp      *node = makeNode(SetOp);
    7018         662 :     Plan       *plan = &node->plan;
    7019         662 :     int         numCols = list_length(groupList);
    7020         662 :     int         keyno = 0;
    7021             :     AttrNumber *cmpColIdx;
    7022             :     Oid        *cmpOperators;
    7023             :     Oid        *cmpCollations;
    7024             :     bool       *cmpNullsFirst;
    7025             :     ListCell   *slitem;
    7026             : 
    7027         662 :     plan->targetlist = tlist;
    7028         662 :     plan->qual = NIL;
    7029         662 :     plan->lefttree = lefttree;
    7030         662 :     plan->righttree = righttree;
    7031             : 
    7032             :     /*
    7033             :      * convert SortGroupClause list into arrays of attr indexes and comparison
    7034             :      * operators, as wanted by executor
    7035             :      */
    7036         662 :     cmpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
    7037         662 :     cmpOperators = (Oid *) palloc(sizeof(Oid) * numCols);
    7038         662 :     cmpCollations = (Oid *) palloc(sizeof(Oid) * numCols);
    7039         662 :     cmpNullsFirst = (bool *) palloc(sizeof(bool) * numCols);
    7040             : 
    7041        2910 :     foreach(slitem, groupList)
    7042             :     {
    7043        2248 :         SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
    7044        2248 :         TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
    7045             : 
    7046        2248 :         cmpColIdx[keyno] = tle->resno;
    7047        2248 :         if (strategy == SETOP_HASHED)
    7048        1090 :             cmpOperators[keyno] = sortcl->eqop;
    7049             :         else
    7050        1158 :             cmpOperators[keyno] = sortcl->sortop;
    7051             :         Assert(OidIsValid(cmpOperators[keyno]));
    7052        2248 :         cmpCollations[keyno] = exprCollation((Node *) tle->expr);
    7053        2248 :         cmpNullsFirst[keyno] = sortcl->nulls_first;
    7054        2248 :         keyno++;
    7055             :     }
    7056             : 
    7057         662 :     node->cmd = cmd;
    7058         662 :     node->strategy = strategy;
    7059         662 :     node->numCols = numCols;
    7060         662 :     node->cmpColIdx = cmpColIdx;
    7061         662 :     node->cmpOperators = cmpOperators;
    7062         662 :     node->cmpCollations = cmpCollations;
    7063         662 :     node->cmpNullsFirst = cmpNullsFirst;
    7064         662 :     node->numGroups = numGroups;
    7065             : 
    7066         662 :     return node;
    7067             : }
    7068             : 
    7069             : /*
    7070             :  * make_lockrows
    7071             :  *    Build a LockRows plan node
    7072             :  */
    7073             : static LockRows *
    7074        7744 : make_lockrows(Plan *lefttree, List *rowMarks, int epqParam)
    7075             : {
    7076        7744 :     LockRows   *node = makeNode(LockRows);
    7077        7744 :     Plan       *plan = &node->plan;
    7078             : 
    7079        7744 :     plan->targetlist = lefttree->targetlist;
    7080        7744 :     plan->qual = NIL;
    7081        7744 :     plan->lefttree = lefttree;
    7082        7744 :     plan->righttree = NULL;
    7083             : 
    7084        7744 :     node->rowMarks = rowMarks;
    7085        7744 :     node->epqParam = epqParam;
    7086             : 
    7087        7744 :     return node;
    7088             : }
    7089             : 
    7090             : /*
    7091             :  * make_limit
    7092             :  *    Build a Limit plan node
    7093             :  */
    7094             : Limit *
    7095        4802 : make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount,
    7096             :            LimitOption limitOption, int uniqNumCols, AttrNumber *uniqColIdx,
    7097             :            Oid *uniqOperators, Oid *uniqCollations)
    7098             : {
    7099        4802 :     Limit      *node = makeNode(Limit);
    7100        4802 :     Plan       *plan = &node->plan;
    7101             : 
    7102        4802 :     plan->targetlist = lefttree->targetlist;
    7103        4802 :     plan->qual = NIL;
    7104        4802 :     plan->lefttree = lefttree;
    7105        4802 :     plan->righttree = NULL;
    7106             : 
    7107        4802 :     node->limitOffset = limitOffset;
    7108        4802 :     node->limitCount = limitCount;
    7109        4802 :     node->limitOption = limitOption;
    7110        4802 :     node->uniqNumCols = uniqNumCols;
    7111        4802 :     node->uniqColIdx = uniqColIdx;
    7112        4802 :     node->uniqOperators = uniqOperators;
    7113        4802 :     node->uniqCollations = uniqCollations;
    7114             : 
    7115        4802 :     return node;
    7116             : }
    7117             : 
    7118             : /*
    7119             :  * make_result
    7120             :  *    Build a Result plan node
    7121             :  */
    7122             : static Result *
    7123      209936 : make_result(List *tlist,
    7124             :             Node *resconstantqual,
    7125             :             Plan *subplan)
    7126             : {
    7127      209936 :     Result     *node = makeNode(Result);
    7128      209936 :     Plan       *plan = &node->plan;
    7129             : 
    7130      209936 :     plan->targetlist = tlist;
    7131      209936 :     plan->qual = NIL;
    7132      209936 :     plan->lefttree = subplan;
    7133      209936 :     plan->righttree = NULL;
    7134      209936 :     node->resconstantqual = resconstantqual;
    7135             : 
    7136      209936 :     return node;
    7137             : }
    7138             : 
    7139             : /*
    7140             :  * make_project_set
    7141             :  *    Build a ProjectSet plan node
    7142             :  */
    7143             : static ProjectSet *
    7144       12050 : make_project_set(List *tlist,
    7145             :                  Plan *subplan)
    7146             : {
    7147       12050 :     ProjectSet *node = makeNode(ProjectSet);
    7148       12050 :     Plan       *plan = &node->plan;
    7149             : 
    7150       12050 :     plan->targetlist = tlist;
    7151       12050 :     plan->qual = NIL;
    7152       12050 :     plan->lefttree = subplan;
    7153       12050 :     plan->righttree = NULL;
    7154             : 
    7155       12050 :     return node;
    7156             : }
    7157             : 
    7158             : /*
    7159             :  * make_modifytable
    7160             :  *    Build a ModifyTable plan node
    7161             :  */
    7162             : static ModifyTable *
    7163       89028 : make_modifytable(PlannerInfo *root, Plan *subplan,
    7164             :                  CmdType operation, bool canSetTag,
    7165             :                  Index nominalRelation, Index rootRelation,
    7166             :                  bool partColsUpdated,
    7167             :                  List *resultRelations,
    7168             :                  List *updateColnosLists,
    7169             :                  List *withCheckOptionLists, List *returningLists,
    7170             :                  List *rowMarks, OnConflictExpr *onconflict,
    7171             :                  List *mergeActionLists, List *mergeJoinConditions,
    7172             :                  int epqParam)
    7173             : {
    7174       89028 :     ModifyTable *node = makeNode(ModifyTable);
    7175       89028 :     bool        returning_old_or_new = false;
    7176       89028 :     bool        returning_old_or_new_valid = false;
    7177             :     List       *fdw_private_list;
    7178             :     Bitmapset  *direct_modify_plans;
    7179             :     ListCell   *lc;
    7180             :     int         i;
    7181             : 
    7182             :     Assert(operation == CMD_MERGE ||
    7183             :            (operation == CMD_UPDATE ?
    7184             :             list_length(resultRelations) == list_length(updateColnosLists) :
    7185             :             updateColnosLists == NIL));
    7186             :     Assert(withCheckOptionLists == NIL ||
    7187             :            list_length(resultRelations) == list_length(withCheckOptionLists));
    7188             :     Assert(returningLists == NIL ||
    7189             :            list_length(resultRelations) == list_length(returningLists));
    7190             : 
    7191       89028 :     node->plan.lefttree = subplan;
    7192       89028 :     node->plan.righttree = NULL;
    7193       89028 :     node->plan.qual = NIL;
    7194             :     /* setrefs.c will fill in the targetlist, if needed */
    7195       89028 :     node->plan.targetlist = NIL;
    7196             : 
    7197       89028 :     node->operation = operation;
    7198       89028 :     node->canSetTag = canSetTag;
    7199       89028 :     node->nominalRelation = nominalRelation;
    7200       89028 :     node->rootRelation = rootRelation;
    7201       89028 :     node->partColsUpdated = partColsUpdated;
    7202       89028 :     node->resultRelations = resultRelations;
    7203       89028 :     if (!onconflict)
    7204             :     {
    7205       87214 :         node->onConflictAction = ONCONFLICT_NONE;
    7206       87214 :         node->onConflictSet = NIL;
    7207       87214 :         node->onConflictCols = NIL;
    7208       87214 :         node->onConflictWhere = NULL;
    7209       87214 :         node->arbiterIndexes = NIL;
    7210       87214 :         node->exclRelRTI = 0;
    7211       87214 :         node->exclRelTlist = NIL;
    7212             :     }
    7213             :     else
    7214             :     {
    7215        1814 :         node->onConflictAction = onconflict->action;
    7216             : 
    7217             :         /*
    7218             :          * Here we convert the ON CONFLICT UPDATE tlist, if any, to the
    7219             :          * executor's convention of having consecutive resno's.  The actual
    7220             :          * target column numbers are saved in node->onConflictCols.  (This
    7221             :          * could be done earlier, but there seems no need to.)
    7222             :          */
    7223        1814 :         node->onConflictSet = onconflict->onConflictSet;
    7224        1814 :         node->onConflictCols =
    7225        1814 :             extract_update_targetlist_colnos(node->onConflictSet);
    7226        1814 :         node->onConflictWhere = onconflict->onConflictWhere;
    7227             : 
    7228             :         /*
    7229             :          * If a set of unique index inference elements was provided (an
    7230             :          * INSERT...ON CONFLICT "inference specification"), then infer
    7231             :          * appropriate unique indexes (or throw an error if none are
    7232             :          * available).
    7233             :          */
    7234        1814 :         node->arbiterIndexes = infer_arbiter_indexes(root);
    7235             : 
    7236        1422 :         node->exclRelRTI = onconflict->exclRelIndex;
    7237        1422 :         node->exclRelTlist = onconflict->exclRelTlist;
    7238             :     }
    7239       88636 :     node->updateColnosLists = updateColnosLists;
    7240       88636 :     node->withCheckOptionLists = withCheckOptionLists;
    7241       88636 :     node->returningOldAlias = root->parse->returningOldAlias;
    7242       88636 :     node->returningNewAlias = root->parse->returningNewAlias;
    7243       88636 :     node->returningLists = returningLists;
    7244       88636 :     node->rowMarks = rowMarks;
    7245       88636 :     node->mergeActionLists = mergeActionLists;
    7246       88636 :     node->mergeJoinConditions = mergeJoinConditions;
    7247       88636 :     node->epqParam = epqParam;
    7248             : 
    7249             :     /*
    7250             :      * For each result relation that is a foreign table, allow the FDW to
    7251             :      * construct private plan data, and accumulate it all into a list.
    7252             :      */
    7253       88636 :     fdw_private_list = NIL;
    7254       88636 :     direct_modify_plans = NULL;
    7255       88636 :     i = 0;
    7256      179720 :     foreach(lc, resultRelations)
    7257             :     {
    7258       91088 :         Index       rti = lfirst_int(lc);
    7259             :         FdwRoutine *fdwroutine;
    7260             :         List       *fdw_private;
    7261             :         bool        direct_modify;
    7262             : 
    7263             :         /*
    7264             :          * If possible, we want to get the FdwRoutine from our RelOptInfo for
    7265             :          * the table.  But sometimes we don't have a RelOptInfo and must get
    7266             :          * it the hard way.  (In INSERT, the target relation is not scanned,
    7267             :          * so it's not a baserel; and there are also corner cases for
    7268             :          * updatable views where the target rel isn't a baserel.)
    7269             :          */
    7270       91088 :         if (rti < root->simple_rel_array_size &&
    7271       91088 :             root->simple_rel_array[rti] != NULL)
    7272       22216 :         {
    7273       22216 :             RelOptInfo *resultRel = root->simple_rel_array[rti];
    7274             : 
    7275       22216 :             fdwroutine = resultRel->fdwroutine;
    7276             :         }
    7277             :         else
    7278             :         {
    7279       68872 :             RangeTblEntry *rte = planner_rt_fetch(rti, root);
    7280             : 
    7281       68872 :             if (rte->rtekind == RTE_RELATION &&
    7282       68872 :                 rte->relkind == RELKIND_FOREIGN_TABLE)
    7283             :             {
    7284             :                 /* Check if the access to foreign tables is restricted */
    7285         178 :                 if (unlikely((restrict_nonsystem_relation_kind & RESTRICT_RELKIND_FOREIGN_TABLE) != 0))
    7286             :                 {
    7287             :                     /* there must not be built-in foreign tables */
    7288             :                     Assert(rte->relid >= FirstNormalObjectId);
    7289           2 :                     ereport(ERROR,
    7290             :                             (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    7291             :                              errmsg("access to non-system foreign table is restricted")));
    7292             :                 }
    7293             : 
    7294         176 :                 fdwroutine = GetFdwRoutineByRelId(rte->relid);
    7295             :             }
    7296             :             else
    7297       68694 :                 fdwroutine = NULL;
    7298             :         }
    7299             : 
    7300             :         /*
    7301             :          * MERGE is not currently supported for foreign tables.  We already
    7302             :          * checked that when the table mentioned in the query is foreign; but
    7303             :          * we can still get here if a partitioned table has a foreign table as
    7304             :          * partition.  Disallow that now, to avoid an uglier error message
    7305             :          * later.
    7306             :          */
    7307       91086 :         if (operation == CMD_MERGE && fdwroutine != NULL)
    7308             :         {
    7309           2 :             RangeTblEntry *rte = planner_rt_fetch(rti, root);
    7310             : 
    7311           2 :             ereport(ERROR,
    7312             :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7313             :                     errmsg("cannot execute MERGE on relation \"%s\"",
    7314             :                            get_rel_name(rte->relid)),
    7315             :                     errdetail_relkind_not_supported(rte->relkind));
    7316             :         }
    7317             : 
    7318             :         /*
    7319             :          * Try to modify the foreign table directly if (1) the FDW provides
    7320             :          * callback functions needed for that and (2) there are no local
    7321             :          * structures that need to be run for each modified row: row-level
    7322             :          * triggers on the foreign table, stored generated columns, WITH CHECK
    7323             :          * OPTIONs from parent views, or Vars returning OLD/NEW in the
    7324             :          * RETURNING list.
    7325             :          */
    7326       91084 :         direct_modify = false;
    7327       91084 :         if (fdwroutine != NULL &&
    7328         540 :             fdwroutine->PlanDirectModify != NULL &&
    7329         530 :             fdwroutine->BeginDirectModify != NULL &&
    7330         530 :             fdwroutine->IterateDirectModify != NULL &&
    7331         530 :             fdwroutine->EndDirectModify != NULL &&
    7332         498 :             withCheckOptionLists == NIL &&
    7333         498 :             !has_row_triggers(root, rti, operation) &&
    7334         420 :             !has_stored_generated_columns(root, rti))
    7335             :         {
    7336             :             /* returning_old_or_new is the same for all result relations */
    7337         402 :             if (!returning_old_or_new_valid)
    7338             :             {
    7339             :                 returning_old_or_new =
    7340         386 :                     contain_vars_returning_old_or_new((Node *)
    7341         386 :                                                       root->parse->returningList);
    7342         386 :                 returning_old_or_new_valid = true;
    7343             :             }
    7344         402 :             if (!returning_old_or_new)
    7345         388 :                 direct_modify = fdwroutine->PlanDirectModify(root, node, rti, i);
    7346             :         }
    7347       91084 :         if (direct_modify)
    7348         208 :             direct_modify_plans = bms_add_member(direct_modify_plans, i);
    7349             : 
    7350       91084 :         if (!direct_modify &&
    7351         332 :             fdwroutine != NULL &&
    7352         332 :             fdwroutine->PlanForeignModify != NULL)
    7353         322 :             fdw_private = fdwroutine->PlanForeignModify(root, node, rti, i);
    7354             :         else
    7355       90762 :             fdw_private = NIL;
    7356       91084 :         fdw_private_list = lappend(fdw_private_list, fdw_private);
    7357       91084 :         i++;
    7358             :     }
    7359       88632 :     node->fdwPrivLists = fdw_private_list;
    7360       88632 :     node->fdwDirectModifyPlans = direct_modify_plans;
    7361             : 
    7362       88632 :     return node;
    7363             : }
    7364             : 
    7365             : /*
    7366             :  * is_projection_capable_path
    7367             :  *      Check whether a given Path node is able to do projection.
    7368             :  */
    7369             : bool
    7370      731706 : is_projection_capable_path(Path *path)
    7371             : {
    7372             :     /* Most plan types can project, so just list the ones that can't */
    7373      731706 :     switch (path->pathtype)
    7374             :     {
    7375         940 :         case T_Hash:
    7376             :         case T_Material:
    7377             :         case T_Memoize:
    7378             :         case T_Sort:
    7379             :         case T_IncrementalSort:
    7380             :         case T_Unique:
    7381             :         case T_SetOp:
    7382             :         case T_LockRows:
    7383             :         case T_Limit:
    7384             :         case T_ModifyTable:
    7385             :         case T_MergeAppend:
    7386             :         case T_RecursiveUnion:
    7387         940 :             return false;
    7388           0 :         case T_CustomScan:
    7389           0 :             if (castNode(CustomPath, path)->flags & CUSTOMPATH_SUPPORT_PROJECTION)
    7390           0 :                 return true;
    7391           0 :             return false;
    7392        2056 :         case T_Append:
    7393             : 
    7394             :             /*
    7395             :              * Append can't project, but if an AppendPath is being used to
    7396             :              * represent a dummy path, what will actually be generated is a
    7397             :              * Result which can project.
    7398             :              */
    7399        2056 :             return IS_DUMMY_APPEND(path);
    7400        3294 :         case T_ProjectSet:
    7401             : 
    7402             :             /*
    7403             :              * Although ProjectSet certainly projects, say "no" because we
    7404             :              * don't want the planner to randomly replace its tlist with
    7405             :              * something else; the SRFs have to stay at top level.  This might
    7406             :              * get relaxed later.
    7407             :              */
    7408        3294 :             return false;
    7409      725416 :         default:
    7410      725416 :             break;
    7411             :     }
    7412      725416 :     return true;
    7413             : }
    7414             : 
    7415             : /*
    7416             :  * is_projection_capable_plan
    7417             :  *      Check whether a given Plan node is able to do projection.
    7418             :  */
    7419             : bool
    7420         530 : is_projection_capable_plan(Plan *plan)
    7421             : {
    7422             :     /* Most plan types can project, so just list the ones that can't */
    7423         530 :     switch (nodeTag(plan))
    7424             :     {
    7425          50 :         case T_Hash:
    7426             :         case T_Material:
    7427             :         case T_Memoize:
    7428             :         case T_Sort:
    7429             :         case T_Unique:
    7430             :         case T_SetOp:
    7431             :         case T_LockRows:
    7432             :         case T_Limit:
    7433             :         case T_ModifyTable:
    7434             :         case T_Append:
    7435             :         case T_MergeAppend:
    7436             :         case T_RecursiveUnion:
    7437          50 :             return false;
    7438           0 :         case T_CustomScan:
    7439           0 :             if (((CustomScan *) plan)->flags & CUSTOMPATH_SUPPORT_PROJECTION)
    7440           0 :                 return true;
    7441           0 :             return false;
    7442           0 :         case T_ProjectSet:
    7443             : 
    7444             :             /*
    7445             :              * Although ProjectSet certainly projects, say "no" because we
    7446             :              * don't want the planner to randomly replace its tlist with
    7447             :              * something else; the SRFs have to stay at top level.  This might
    7448             :              * get relaxed later.
    7449             :              */
    7450           0 :             return false;
    7451         480 :         default:
    7452         480 :             break;
    7453             :     }
    7454         480 :     return true;
    7455             : }

Generated by: LCOV version 1.16