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

Generated by: LCOV version 1.16