LCOV - code coverage report
Current view: top level - src/backend/optimizer/plan - createplan.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 2258 2359 95.7 %
Date: 2024-11-21 08:14:44 Functions: 114 115 99.1 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14