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

Generated by: LCOV version 1.16