LCOV - code coverage report
Current view: top level - src/backend/optimizer/plan - createplan.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 2207 2319 95.2 %
Date: 2025-10-10 10:17:52 Functions: 112 114 98.2 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.16