LCOV - code coverage report
Current view: top level - src/backend/optimizer/plan - createplan.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 2271 2372 95.7 %
Date: 2025-01-18 04:15:08 Functions: 114 115 99.1 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * createplan.c
       4             :  *    Routines to create the desired plan for processing a query.
       5             :  *    Planning is complete, we just need to convert the selected
       6             :  *    Path into a Plan.
       7             :  *
       8             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
       9             :  * Portions Copyright (c) 1994, Regents of the University of California
      10             :  *
      11             :  *
      12             :  * IDENTIFICATION
      13             :  *    src/backend/optimizer/plan/createplan.c
      14             :  *
      15             :  *-------------------------------------------------------------------------
      16             :  */
      17             : #include "postgres.h"
      18             : 
      19             : #include <math.h>
      20             : 
      21             : #include "access/sysattr.h"
      22             : #include "catalog/pg_class.h"
      23             : #include "foreign/fdwapi.h"
      24             : #include "miscadmin.h"
      25             : #include "nodes/extensible.h"
      26             : #include "nodes/makefuncs.h"
      27             : #include "nodes/nodeFuncs.h"
      28             : #include "optimizer/clauses.h"
      29             : #include "optimizer/cost.h"
      30             : #include "optimizer/optimizer.h"
      31             : #include "optimizer/paramassign.h"
      32             : #include "optimizer/pathnode.h"
      33             : #include "optimizer/paths.h"
      34             : #include "optimizer/placeholder.h"
      35             : #include "optimizer/plancat.h"
      36             : #include "optimizer/planmain.h"
      37             : #include "optimizer/prep.h"
      38             : #include "optimizer/restrictinfo.h"
      39             : #include "optimizer/subselect.h"
      40             : #include "optimizer/tlist.h"
      41             : #include "parser/parse_clause.h"
      42             : #include "parser/parsetree.h"
      43             : #include "partitioning/partprune.h"
      44             : #include "tcop/tcopprot.h"
      45             : #include "utils/lsyscache.h"
      46             : 
      47             : 
      48             : /*
      49             :  * Flag bits that can appear in the flags argument of create_plan_recurse().
      50             :  * These can be OR-ed together.
      51             :  *
      52             :  * CP_EXACT_TLIST specifies that the generated plan node must return exactly
      53             :  * the tlist specified by the path's pathtarget (this overrides both
      54             :  * CP_SMALL_TLIST and CP_LABEL_TLIST, if those are set).  Otherwise, the
      55             :  * plan node is allowed to return just the Vars and PlaceHolderVars needed
      56             :  * to evaluate the pathtarget.
      57             :  *
      58             :  * CP_SMALL_TLIST specifies that a narrower tlist is preferred.  This is
      59             :  * passed down by parent nodes such as Sort and Hash, which will have to
      60             :  * store the returned tuples.
      61             :  *
      62             :  * CP_LABEL_TLIST specifies that the plan node must return columns matching
      63             :  * any sortgrouprefs specified in its pathtarget, with appropriate
      64             :  * ressortgroupref labels.  This is passed down by parent nodes such as Sort
      65             :  * and Group, which need these values to be available in their inputs.
      66             :  *
      67             :  * CP_IGNORE_TLIST specifies that the caller plans to replace the targetlist,
      68             :  * and therefore it doesn't matter a bit what target list gets generated.
      69             :  */
      70             : #define CP_EXACT_TLIST      0x0001  /* Plan must return specified tlist */
      71             : #define CP_SMALL_TLIST      0x0002  /* Prefer narrower tlists */
      72             : #define CP_LABEL_TLIST      0x0004  /* tlist must contain sortgrouprefs */
      73             : #define CP_IGNORE_TLIST     0x0008  /* caller will replace tlist */
      74             : 
      75             : 
      76             : static Plan *create_plan_recurse(PlannerInfo *root, Path *best_path,
      77             :                                  int flags);
      78             : static Plan *create_scan_plan(PlannerInfo *root, Path *best_path,
      79             :                               int flags);
      80             : static List *build_path_tlist(PlannerInfo *root, Path *path);
      81             : static bool use_physical_tlist(PlannerInfo *root, Path *path, int flags);
      82             : static List *get_gating_quals(PlannerInfo *root, List *quals);
      83             : static Plan *create_gating_plan(PlannerInfo *root, Path *path, Plan *plan,
      84             :                                 List *gating_quals);
      85             : static Plan *create_join_plan(PlannerInfo *root, JoinPath *best_path);
      86             : static bool mark_async_capable_plan(Plan *plan, Path *path);
      87             : static Plan *create_append_plan(PlannerInfo *root, AppendPath *best_path,
      88             :                                 int flags);
      89             : static Plan *create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path,
      90             :                                       int flags);
      91             : static Result *create_group_result_plan(PlannerInfo *root,
      92             :                                         GroupResultPath *best_path);
      93             : static ProjectSet *create_project_set_plan(PlannerInfo *root, ProjectSetPath *best_path);
      94             : static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path,
      95             :                                       int flags);
      96             : static Memoize *create_memoize_plan(PlannerInfo *root, MemoizePath *best_path,
      97             :                                     int flags);
      98             : static Plan *create_unique_plan(PlannerInfo *root, UniquePath *best_path,
      99             :                                 int flags);
     100             : static Gather *create_gather_plan(PlannerInfo *root, GatherPath *best_path);
     101             : static Plan *create_projection_plan(PlannerInfo *root,
     102             :                                     ProjectionPath *best_path,
     103             :                                     int flags);
     104             : static Plan *inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe);
     105             : static Sort *create_sort_plan(PlannerInfo *root, SortPath *best_path, int flags);
     106             : static IncrementalSort *create_incrementalsort_plan(PlannerInfo *root,
     107             :                                                     IncrementalSortPath *best_path, int flags);
     108             : static Group *create_group_plan(PlannerInfo *root, GroupPath *best_path);
     109             : static Unique *create_upper_unique_plan(PlannerInfo *root, UpperUniquePath *best_path,
     110             :                                         int flags);
     111             : static Agg *create_agg_plan(PlannerInfo *root, AggPath *best_path);
     112             : static Plan *create_groupingsets_plan(PlannerInfo *root, GroupingSetsPath *best_path);
     113             : static Result *create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path);
     114             : static WindowAgg *create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path);
     115             : static SetOp *create_setop_plan(PlannerInfo *root, SetOpPath *best_path,
     116             :                                 int flags);
     117             : static RecursiveUnion *create_recursiveunion_plan(PlannerInfo *root, RecursiveUnionPath *best_path);
     118             : static LockRows *create_lockrows_plan(PlannerInfo *root, LockRowsPath *best_path,
     119             :                                       int flags);
     120             : static ModifyTable *create_modifytable_plan(PlannerInfo *root, ModifyTablePath *best_path);
     121             : static Limit *create_limit_plan(PlannerInfo *root, LimitPath *best_path,
     122             :                                 int flags);
     123             : static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path,
     124             :                                     List *tlist, List *scan_clauses);
     125             : static SampleScan *create_samplescan_plan(PlannerInfo *root, Path *best_path,
     126             :                                           List *tlist, List *scan_clauses);
     127             : static Scan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path,
     128             :                                    List *tlist, List *scan_clauses, bool indexonly);
     129             : static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
     130             :                                                BitmapHeapPath *best_path,
     131             :                                                List *tlist, List *scan_clauses);
     132             : static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
     133             :                                    List **qual, List **indexqual, List **indexECs);
     134             : static void bitmap_subplan_mark_shared(Plan *plan);
     135             : static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
     136             :                                     List *tlist, List *scan_clauses);
     137             : static TidRangeScan *create_tidrangescan_plan(PlannerInfo *root,
     138             :                                               TidRangePath *best_path,
     139             :                                               List *tlist,
     140             :                                               List *scan_clauses);
     141             : static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root,
     142             :                                               SubqueryScanPath *best_path,
     143             :                                               List *tlist, List *scan_clauses);
     144             : static FunctionScan *create_functionscan_plan(PlannerInfo *root, Path *best_path,
     145             :                                               List *tlist, List *scan_clauses);
     146             : static ValuesScan *create_valuesscan_plan(PlannerInfo *root, Path *best_path,
     147             :                                           List *tlist, List *scan_clauses);
     148             : static TableFuncScan *create_tablefuncscan_plan(PlannerInfo *root, Path *best_path,
     149             :                                                 List *tlist, List *scan_clauses);
     150             : static CteScan *create_ctescan_plan(PlannerInfo *root, Path *best_path,
     151             :                                     List *tlist, List *scan_clauses);
     152             : static NamedTuplestoreScan *create_namedtuplestorescan_plan(PlannerInfo *root,
     153             :                                                             Path *best_path, List *tlist, List *scan_clauses);
     154             : static Result *create_resultscan_plan(PlannerInfo *root, Path *best_path,
     155             :                                       List *tlist, List *scan_clauses);
     156             : static WorkTableScan *create_worktablescan_plan(PlannerInfo *root, Path *best_path,
     157             :                                                 List *tlist, List *scan_clauses);
     158             : static ForeignScan *create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
     159             :                                             List *tlist, List *scan_clauses);
     160             : static CustomScan *create_customscan_plan(PlannerInfo *root,
     161             :                                           CustomPath *best_path,
     162             :                                           List *tlist, List *scan_clauses);
     163             : static NestLoop *create_nestloop_plan(PlannerInfo *root, NestPath *best_path);
     164             : static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path);
     165             : static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path);
     166             : static Node *replace_nestloop_params(PlannerInfo *root, Node *expr);
     167             : static Node *replace_nestloop_params_mutator(Node *node, PlannerInfo *root);
     168             : static void fix_indexqual_references(PlannerInfo *root, IndexPath *index_path,
     169             :                                      List **stripped_indexquals_p,
     170             :                                      List **fixed_indexquals_p);
     171             : static List *fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path);
     172             : static Node *fix_indexqual_clause(PlannerInfo *root,
     173             :                                   IndexOptInfo *index, int indexcol,
     174             :                                   Node *clause, List *indexcolnos);
     175             : static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol);
     176             : static List *get_switched_clauses(List *clauses, Relids outerrelids);
     177             : static List *order_qual_clauses(PlannerInfo *root, List *clauses);
     178             : static void copy_generic_path_info(Plan *dest, Path *src);
     179             : static void copy_plan_costsize(Plan *dest, Plan *src);
     180             : static void label_sort_with_costsize(PlannerInfo *root, Sort *plan,
     181             :                                      double limit_tuples);
     182             : static void label_incrementalsort_with_costsize(PlannerInfo *root, IncrementalSort *plan,
     183             :                                                 List *pathkeys, double limit_tuples);
     184             : static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
     185             : static SampleScan *make_samplescan(List *qptlist, List *qpqual, Index scanrelid,
     186             :                                    TableSampleClause *tsc);
     187             : static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
     188             :                                  Oid indexid, List *indexqual, List *indexqualorig,
     189             :                                  List *indexorderby, List *indexorderbyorig,
     190             :                                  List *indexorderbyops,
     191             :                                  ScanDirection indexscandir);
     192             : static IndexOnlyScan *make_indexonlyscan(List *qptlist, List *qpqual,
     193             :                                          Index scanrelid, Oid indexid,
     194             :                                          List *indexqual, List *recheckqual,
     195             :                                          List *indexorderby,
     196             :                                          List *indextlist,
     197             :                                          ScanDirection indexscandir);
     198             : static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid,
     199             :                                               List *indexqual,
     200             :                                               List *indexqualorig);
     201             : static BitmapHeapScan *make_bitmap_heapscan(List *qptlist,
     202             :                                             List *qpqual,
     203             :                                             Plan *lefttree,
     204             :                                             List *bitmapqualorig,
     205             :                                             Index scanrelid);
     206             : static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
     207             :                              List *tidquals);
     208             : static TidRangeScan *make_tidrangescan(List *qptlist, List *qpqual,
     209             :                                        Index scanrelid, List *tidrangequals);
     210             : static SubqueryScan *make_subqueryscan(List *qptlist,
     211             :                                        List *qpqual,
     212             :                                        Index scanrelid,
     213             :                                        Plan *subplan);
     214             : static FunctionScan *make_functionscan(List *qptlist, List *qpqual,
     215             :                                        Index scanrelid, List *functions, bool funcordinality);
     216             : static ValuesScan *make_valuesscan(List *qptlist, List *qpqual,
     217             :                                    Index scanrelid, List *values_lists);
     218             : static TableFuncScan *make_tablefuncscan(List *qptlist, List *qpqual,
     219             :                                          Index scanrelid, TableFunc *tablefunc);
     220             : static CteScan *make_ctescan(List *qptlist, List *qpqual,
     221             :                              Index scanrelid, int ctePlanId, int cteParam);
     222             : static NamedTuplestoreScan *make_namedtuplestorescan(List *qptlist, List *qpqual,
     223             :                                                      Index scanrelid, char *enrname);
     224             : static WorkTableScan *make_worktablescan(List *qptlist, List *qpqual,
     225             :                                          Index scanrelid, int wtParam);
     226             : static RecursiveUnion *make_recursive_union(List *tlist,
     227             :                                             Plan *lefttree,
     228             :                                             Plan *righttree,
     229             :                                             int wtParam,
     230             :                                             List *distinctList,
     231             :                                             long numGroups);
     232             : static BitmapAnd *make_bitmap_and(List *bitmapplans);
     233             : static BitmapOr *make_bitmap_or(List *bitmapplans);
     234             : static NestLoop *make_nestloop(List *tlist,
     235             :                                List *joinclauses, List *otherclauses, List *nestParams,
     236             :                                Plan *lefttree, Plan *righttree,
     237             :                                JoinType jointype, bool inner_unique);
     238             : static HashJoin *make_hashjoin(List *tlist,
     239             :                                List *joinclauses, List *otherclauses,
     240             :                                List *hashclauses,
     241             :                                List *hashoperators, List *hashcollations,
     242             :                                List *hashkeys,
     243             :                                Plan *lefttree, Plan *righttree,
     244             :                                JoinType jointype, bool inner_unique);
     245             : static Hash *make_hash(Plan *lefttree,
     246             :                        List *hashkeys,
     247             :                        Oid skewTable,
     248             :                        AttrNumber skewColumn,
     249             :                        bool skewInherit);
     250             : static MergeJoin *make_mergejoin(List *tlist,
     251             :                                  List *joinclauses, List *otherclauses,
     252             :                                  List *mergeclauses,
     253             :                                  Oid *mergefamilies,
     254             :                                  Oid *mergecollations,
     255             :                                  bool *mergereversals,
     256             :                                  bool *mergenullsfirst,
     257             :                                  Plan *lefttree, Plan *righttree,
     258             :                                  JoinType jointype, bool inner_unique,
     259             :                                  bool skip_mark_restore);
     260             : static Sort *make_sort(Plan *lefttree, int numCols,
     261             :                        AttrNumber *sortColIdx, Oid *sortOperators,
     262             :                        Oid *collations, bool *nullsFirst);
     263             : static IncrementalSort *make_incrementalsort(Plan *lefttree,
     264             :                                              int numCols, int nPresortedCols,
     265             :                                              AttrNumber *sortColIdx, Oid *sortOperators,
     266             :                                              Oid *collations, bool *nullsFirst);
     267             : static Plan *prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
     268             :                                         Relids relids,
     269             :                                         const AttrNumber *reqColIdx,
     270             :                                         bool adjust_tlist_in_place,
     271             :                                         int *p_numsortkeys,
     272             :                                         AttrNumber **p_sortColIdx,
     273             :                                         Oid **p_sortOperators,
     274             :                                         Oid **p_collations,
     275             :                                         bool **p_nullsFirst);
     276             : static Sort *make_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
     277             :                                      Relids relids);
     278             : static IncrementalSort *make_incrementalsort_from_pathkeys(Plan *lefttree,
     279             :                                                            List *pathkeys, Relids relids, int nPresortedCols);
     280             : static Sort *make_sort_from_groupcols(List *groupcls,
     281             :                                       AttrNumber *grpColIdx,
     282             :                                       Plan *lefttree);
     283             : static Material *make_material(Plan *lefttree);
     284             : static Memoize *make_memoize(Plan *lefttree, Oid *hashoperators,
     285             :                              Oid *collations, List *param_exprs,
     286             :                              bool singlerow, bool binary_mode,
     287             :                              uint32 est_entries, Bitmapset *keyparamids);
     288             : static WindowAgg *make_windowagg(List *tlist, 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,
     305             :                          List *tlist, Plan *lefttree, Plan *righttree,
     306             :                          List *groupList, 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      506626 : 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      506626 :     root->curOuterRels = NULL;
     349      506626 :     root->curOuterParams = NIL;
     350             : 
     351             :     /* Recursively process the path tree, demanding the correct tlist result */
     352      506626 :     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      506230 :     if (!IsA(plan, ModifyTable))
     362      415714 :         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      506230 :     SS_attach_initplans(root, plan);
     372             : 
     373             :     /* Check we successfully assigned all NestLoopParams to plan nodes */
     374      506230 :     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      506230 :     root->plan_params = NIL;
     382             : 
     383      506230 :     return plan;
     384             : }
     385             : 
     386             : /*
     387             :  * create_plan_recurse
     388             :  *    Recursive guts of create_plan().
     389             :  */
     390             : static Plan *
     391     1358914 : 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     1358914 :     check_stack_depth();
     397             : 
     398     1358914 :     switch (best_path->pathtype)
     399             :     {
     400      440638 :         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      440638 :             plan = create_scan_plan(root, best_path, flags);
     417      440638 :             break;
     418      119774 :         case T_HashJoin:
     419             :         case T_MergeJoin:
     420             :         case T_NestLoop:
     421      119774 :             plan = create_join_plan(root,
     422             :                                     (JoinPath *) best_path);
     423      119774 :             break;
     424       20582 :         case T_Append:
     425       20582 :             plan = create_append_plan(root,
     426             :                                       (AppendPath *) best_path,
     427             :                                       flags);
     428       20582 :             break;
     429         512 :         case T_MergeAppend:
     430         512 :             plan = create_merge_append_plan(root,
     431             :                                             (MergeAppendPath *) best_path,
     432             :                                             flags);
     433         512 :             break;
     434      550822 :         case T_Result:
     435      550822 :             if (IsA(best_path, ProjectionPath))
     436             :             {
     437      337682 :                 plan = create_projection_plan(root,
     438             :                                               (ProjectionPath *) best_path,
     439             :                                               flags);
     440             :             }
     441      213140 :             else if (IsA(best_path, MinMaxAggPath))
     442             :             {
     443         364 :                 plan = (Plan *) create_minmaxagg_plan(root,
     444             :                                                       (MinMaxAggPath *) best_path);
     445             :             }
     446      212776 :             else if (IsA(best_path, GroupResultPath))
     447             :             {
     448      211318 :                 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      550822 :             break;
     458        8734 :         case T_ProjectSet:
     459        8734 :             plan = (Plan *) create_project_set_plan(root,
     460             :                                                     (ProjectSetPath *) best_path);
     461        8734 :             break;
     462        3658 :         case T_Material:
     463        3658 :             plan = (Plan *) create_material_plan(root,
     464             :                                                  (MaterialPath *) best_path,
     465             :                                                  flags);
     466        3658 :             break;
     467        1374 :         case T_Memoize:
     468        1374 :             plan = (Plan *) create_memoize_plan(root,
     469             :                                                 (MemoizePath *) best_path,
     470             :                                                 flags);
     471        1374 :             break;
     472        5548 :         case T_Unique:
     473        5548 :             if (IsA(best_path, UpperUniquePath))
     474             :             {
     475        5048 :                 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        5548 :             break;
     487         934 :         case T_Gather:
     488         934 :             plan = (Plan *) create_gather_plan(root,
     489             :                                                (GatherPath *) best_path);
     490         934 :             break;
     491       59178 :         case T_Sort:
     492       59178 :             plan = (Plan *) create_sort_plan(root,
     493             :                                              (SortPath *) best_path,
     494             :                                              flags);
     495       59178 :             break;
     496         758 :         case T_IncrementalSort:
     497         758 :             plan = (Plan *) create_incrementalsort_plan(root,
     498             :                                                         (IncrementalSortPath *) best_path,
     499             :                                                         flags);
     500         758 :             break;
     501         246 :         case T_Group:
     502         246 :             plan = (Plan *) create_group_plan(root,
     503             :                                               (GroupPath *) best_path);
     504         246 :             break;
     505       38926 :         case T_Agg:
     506       38926 :             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       38090 :                 plan = (Plan *) create_agg_plan(root,
     513             :                                                 (AggPath *) best_path);
     514             :             }
     515       38926 :             break;
     516        2486 :         case T_WindowAgg:
     517        2486 :             plan = (Plan *) create_windowagg_plan(root,
     518             :                                                   (WindowAggPath *) best_path);
     519        2486 :             break;
     520         680 :         case T_SetOp:
     521         680 :             plan = (Plan *) create_setop_plan(root,
     522             :                                               (SetOpPath *) best_path,
     523             :                                               flags);
     524         680 :             break;
     525         816 :         case T_RecursiveUnion:
     526         816 :             plan = (Plan *) create_recursiveunion_plan(root,
     527             :                                                        (RecursiveUnionPath *) best_path);
     528         816 :             break;
     529        7846 :         case T_LockRows:
     530        7846 :             plan = (Plan *) create_lockrows_plan(root,
     531             :                                                  (LockRowsPath *) best_path,
     532             :                                                  flags);
     533        7846 :             break;
     534       90912 :         case T_ModifyTable:
     535       90912 :             plan = (Plan *) create_modifytable_plan(root,
     536             :                                                     (ModifyTablePath *) best_path);
     537       90516 :             break;
     538        4160 :         case T_Limit:
     539        4160 :             plan = (Plan *) create_limit_plan(root,
     540             :                                               (LimitPath *) best_path,
     541             :                                               flags);
     542        4160 :             break;
     543         330 :         case T_GatherMerge:
     544         330 :             plan = (Plan *) create_gather_merge_plan(root,
     545             :                                                      (GatherMergePath *) best_path);
     546         330 :             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     1358518 :     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      442096 : create_scan_plan(PlannerInfo *root, Path *best_path, int flags)
     563             : {
     564      442096 :     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      442096 :     switch (best_path->pathtype)
     583             :     {
     584      145750 :         case T_IndexScan:
     585             :         case T_IndexOnlyScan:
     586      145750 :             scan_clauses = castNode(IndexPath, best_path)->indexinfo->indrestrictinfo;
     587      145750 :             break;
     588      296346 :         default:
     589      296346 :             scan_clauses = rel->baserestrictinfo;
     590      296346 :             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      442096 :     if (best_path->param_info)
     600       43134 :         scan_clauses = list_concat_copy(scan_clauses,
     601       43134 :                                         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      442096 :     if (IS_JOIN_REL(rel))
     614         302 :     {
     615             :         List       *join_clauses;
     616             : 
     617             :         Assert(best_path->pathtype == T_ForeignScan ||
     618             :                best_path->pathtype == T_CustomScan);
     619         302 :         if (best_path->pathtype == T_ForeignScan)
     620         302 :             join_clauses = ((ForeignPath *) best_path)->fdw_restrictinfo;
     621             :         else
     622           0 :             join_clauses = ((CustomPath *) best_path)->custom_restrictinfo;
     623             : 
     624         302 :         gating_clauses = get_gating_quals(root, join_clauses);
     625             :     }
     626             :     else
     627      441794 :         gating_clauses = get_gating_quals(root, scan_clauses);
     628      442096 :     if (gating_clauses)
     629        6190 :         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      442096 :     if (flags == CP_IGNORE_TLIST)
     642             :     {
     643       69640 :         tlist = NULL;
     644             :     }
     645      372456 :     else if (use_physical_tlist(root, best_path, flags))
     646             :     {
     647      175826 :         if (best_path->pathtype == T_IndexOnlyScan)
     648             :         {
     649             :             /* For index-only scan, the preferred tlist is the index's */
     650        8132 :             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        8132 :             if (flags & CP_LABEL_TLIST)
     657        1914 :                 apply_pathtarget_labeling_to_tlist(tlist, best_path->pathtarget);
     658             :         }
     659             :         else
     660             :         {
     661      167694 :             tlist = build_physical_tlist(root, rel);
     662      167694 :             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      167534 :                 if (flags & CP_LABEL_TLIST)
     671       12422 :                     apply_pathtarget_labeling_to_tlist(tlist, best_path->pathtarget);
     672             :             }
     673             :         }
     674             :     }
     675             :     else
     676             :     {
     677      196630 :         tlist = build_path_tlist(root, best_path);
     678             :     }
     679             : 
     680      442096 :     switch (best_path->pathtype)
     681             :     {
     682      191710 :         case T_SeqScan:
     683      191710 :             plan = (Plan *) create_seqscan_plan(root,
     684             :                                                 best_path,
     685             :                                                 tlist,
     686             :                                                 scan_clauses);
     687      191710 :             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      130460 :         case T_IndexScan:
     697      130460 :             plan = (Plan *) create_indexscan_plan(root,
     698             :                                                   (IndexPath *) best_path,
     699             :                                                   tlist,
     700             :                                                   scan_clauses,
     701             :                                                   false);
     702      130460 :             break;
     703             : 
     704       15290 :         case T_IndexOnlyScan:
     705       15290 :             plan = (Plan *) create_indexscan_plan(root,
     706             :                                                   (IndexPath *) best_path,
     707             :                                                   tlist,
     708             :                                                   scan_clauses,
     709             :                                                   true);
     710       15290 :             break;
     711             : 
     712       20156 :         case T_BitmapHeapScan:
     713       20156 :             plan = (Plan *) create_bitmap_scan_plan(root,
     714             :                                                     (BitmapHeapPath *) best_path,
     715             :                                                     tlist,
     716             :                                                     scan_clauses);
     717       20156 :             break;
     718             : 
     719         700 :         case T_TidScan:
     720         700 :             plan = (Plan *) create_tidscan_plan(root,
     721             :                                                 (TidPath *) best_path,
     722             :                                                 tlist,
     723             :                                                 scan_clauses);
     724         700 :             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       22574 :         case T_SubqueryScan:
     734       22574 :             plan = (Plan *) create_subqueryscan_plan(root,
     735             :                                                      (SubqueryScanPath *) best_path,
     736             :                                                      tlist,
     737             :                                                      scan_clauses);
     738       22574 :             break;
     739             : 
     740       44176 :         case T_FunctionScan:
     741       44176 :             plan = (Plan *) create_functionscan_plan(root,
     742             :                                                      best_path,
     743             :                                                      tlist,
     744             :                                                      scan_clauses);
     745       44176 :             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        7980 :         case T_ValuesScan:
     755        7980 :             plan = (Plan *) create_valuesscan_plan(root,
     756             :                                                    best_path,
     757             :                                                    tlist,
     758             :                                                    scan_clauses);
     759        7980 :             break;
     760             : 
     761        3186 :         case T_CteScan:
     762        3186 :             plan = (Plan *) create_ctescan_plan(root,
     763             :                                                 best_path,
     764             :                                                 tlist,
     765             :                                                 scan_clauses);
     766        3186 :             break;
     767             : 
     768         438 :         case T_NamedTuplestoreScan:
     769         438 :             plan = (Plan *) create_namedtuplestorescan_plan(root,
     770             :                                                             best_path,
     771             :                                                             tlist,
     772             :                                                             scan_clauses);
     773         438 :             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         816 :         case T_WorkTableScan:
     783         816 :             plan = (Plan *) create_worktablescan_plan(root,
     784             :                                                       best_path,
     785             :                                                       tlist,
     786             :                                                       scan_clauses);
     787         816 :             break;
     788             : 
     789        2024 :         case T_ForeignScan:
     790        2024 :             plan = (Plan *) create_foreignscan_plan(root,
     791             :                                                     (ForeignPath *) best_path,
     792             :                                                     tlist,
     793             :                                                     scan_clauses);
     794        2024 :             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      442096 :     if (gating_clauses)
     816        6190 :         plan = create_gating_plan(root, best_path, plan, gating_clauses);
     817             : 
     818      442096 :     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      949224 : build_path_tlist(PlannerInfo *root, Path *path)
     829             : {
     830      949224 :     List       *tlist = NIL;
     831      949224 :     Index      *sortgrouprefs = path->pathtarget->sortgrouprefs;
     832      949224 :     int         resno = 1;
     833             :     ListCell   *v;
     834             : 
     835     3042446 :     foreach(v, path->pathtarget->exprs)
     836             :     {
     837     2093222 :         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     2093222 :         if (path->param_info)
     847       13598 :             node = replace_nestloop_params(root, node);
     848             : 
     849     2093222 :         tle = makeTargetEntry((Expr *) node,
     850             :                               resno,
     851             :                               NULL,
     852             :                               false);
     853     2093222 :         if (sortgrouprefs)
     854     1370200 :             tle->ressortgroupref = sortgrouprefs[resno - 1];
     855             : 
     856     2093222 :         tlist = lappend(tlist, tle);
     857     2093222 :         resno++;
     858             :     }
     859      949224 :     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      710138 : use_physical_tlist(PlannerInfo *root, Path *path, int flags)
     869             : {
     870      710138 :     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      710138 :     if (flags & (CP_EXACT_TLIST | CP_SMALL_TLIST))
     878      499132 :         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      211006 :     if (rel->rtekind != RTE_RELATION &&
     885       33288 :         rel->rtekind != RTE_SUBQUERY &&
     886       31046 :         rel->rtekind != RTE_FUNCTION &&
     887       10958 :         rel->rtekind != RTE_TABLEFUNC &&
     888       10724 :         rel->rtekind != RTE_VALUES &&
     889        9450 :         rel->rtekind != RTE_CTE)
     890        8586 :         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      202420 :     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      197786 :     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      197786 :     if (IsA(path, BitmapHeapPath) &&
     915       10314 :         path->pathtarget->exprs == NIL)
     916        3130 :         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     1359758 :     for (i = rel->min_attr; i <= 0; i++)
     924             :     {
     925     1182074 :         if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
     926       16972 :             return false;
     927             :     }
     928             : 
     929             :     /*
     930             :      * Can't do it if the rel is required to emit any placeholder expressions,
     931             :      * either.
     932             :      */
     933      178932 :     foreach(lc, root->placeholder_list)
     934             :     {
     935        1448 :         PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
     936             : 
     937        2854 :         if (bms_nonempty_difference(phinfo->ph_needed, rel->relids) &&
     938        1406 :             bms_is_subset(phinfo->ph_eval_at, rel->relids))
     939         200 :             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      177484 :     if (path->pathtype == T_IndexOnlyScan)
     948             :     {
     949        8148 :         IndexOptInfo *indexinfo = ((IndexPath *) path)->indexinfo;
     950             : 
     951       17470 :         for (i = 0; i < indexinfo->ncolumns; i++)
     952             :         {
     953        9338 :             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      177468 :     if ((flags & CP_LABEL_TLIST) && path->pathtarget->sortgrouprefs)
     968             :     {
     969        2142 :         Bitmapset  *sortgroupatts = NULL;
     970             : 
     971        2142 :         i = 0;
     972        5400 :         foreach(lc, path->pathtarget->exprs)
     973             :         {
     974        3936 :             Expr       *expr = (Expr *) lfirst(lc);
     975             : 
     976        3936 :             if (path->pathtarget->sortgrouprefs[i])
     977             :             {
     978        3240 :                 if (expr && IsA(expr, Var))
     979        2562 :                 {
     980        2574 :                     int         attno = ((Var *) expr)->varattno;
     981             : 
     982        2574 :                     attno -= FirstLowInvalidHeapAttributeNumber;
     983        2574 :                     if (bms_is_member(attno, sortgroupatts))
     984         678 :                         return false;
     985        2562 :                     sortgroupatts = bms_add_member(sortgroupatts, attno);
     986             :                 }
     987             :                 else
     988         666 :                     return false;
     989             :             }
     990        3258 :             i++;
     991             :         }
     992             :     }
     993             : 
     994      176790 :     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      561870 : get_gating_quals(PlannerInfo *root, List *quals)
    1006             : {
    1007             :     /* No need to look if we know there are no pseudoconstants */
    1008      561870 :     if (!root->hasPseudoConstantQuals)
    1009      541244 :         return NIL;
    1010             : 
    1011             :     /* Sort into desirable execution order while still in RestrictInfo form */
    1012       20626 :     quals = order_qual_clauses(root, quals);
    1013             : 
    1014             :     /* Pull out any pseudoconstant quals from the RestrictInfo list */
    1015       20626 :     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        9016 : 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        9016 :     splan = plan;
    1040        9016 :     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        9016 :     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        9016 :     copy_plan_costsize(gplan, plan);
    1071             : 
    1072             :     /* Gating quals could be unsafe, so better use the Path's safety flag */
    1073        9016 :     gplan->parallel_safe = path->parallel_safe;
    1074             : 
    1075        9016 :     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      119774 : create_join_plan(PlannerInfo *root, JoinPath *best_path)
    1085             : {
    1086             :     Plan       *plan;
    1087             :     List       *gating_clauses;
    1088             : 
    1089      119774 :     switch (best_path->path.pathtype)
    1090             :     {
    1091        7094 :         case T_MergeJoin:
    1092        7094 :             plan = (Plan *) create_mergejoin_plan(root,
    1093             :                                                   (MergePath *) best_path);
    1094        7094 :             break;
    1095       28878 :         case T_HashJoin:
    1096       28878 :             plan = (Plan *) create_hashjoin_plan(root,
    1097             :                                                  (HashPath *) best_path);
    1098       28878 :             break;
    1099       83802 :         case T_NestLoop:
    1100       83802 :             plan = (Plan *) create_nestloop_plan(root,
    1101             :                                                  (NestPath *) best_path);
    1102       83802 :             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      119774 :     gating_clauses = get_gating_quals(root, best_path->joinrestrictinfo);
    1116      119774 :     if (gating_clauses)
    1117        2826 :         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      119774 :     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       27022 : mark_async_capable_plan(Plan *plan, Path *path)
    1144             : {
    1145       27022 :     switch (nodeTag(path))
    1146             :     {
    1147        9818 :         case T_SubqueryScanPath:
    1148             :             {
    1149        9818 :                 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        9818 :                 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       13492 :                 if (trivial_subqueryscan(scan_plan) &&
    1163        3678 :                     mark_async_capable_plan(scan_plan->subplan,
    1164             :                                             ((SubqueryScanPath *) path)->subpath))
    1165          16 :                     break;
    1166        9798 :                 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        4930 :         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        4930 :             if (IsA(plan, Result))
    1192         166 :                 return false;
    1193             : 
    1194             :             /*
    1195             :              * create_projection_plan() would have pulled up the subplan, so
    1196             :              * check the capability using the subpath.
    1197             :              */
    1198        4764 :             if (mark_async_capable_plan(plan,
    1199             :                                         ((ProjectionPath *) path)->subpath))
    1200          32 :                 return true;
    1201        4732 :             return false;
    1202       11794 :         default:
    1203       11794 :             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       20582 : create_append_plan(PlannerInfo *root, AppendPath *best_path, int flags)
    1220             : {
    1221             :     Append     *plan;
    1222       20582 :     List       *tlist = build_path_tlist(root, &best_path->path);
    1223       20582 :     int         orig_tlist_length = list_length(tlist);
    1224       20582 :     bool        tlist_was_changed = false;
    1225       20582 :     List       *pathkeys = best_path->path.pathkeys;
    1226       20582 :     List       *subplans = NIL;
    1227             :     ListCell   *subpaths;
    1228       20582 :     int         nasyncplans = 0;
    1229       20582 :     RelOptInfo *rel = best_path->path.parent;
    1230       20582 :     PartitionPruneInfo *partpruneinfo = NULL;
    1231       20582 :     int         nodenumsortkeys = 0;
    1232       20582 :     AttrNumber *nodeSortColIdx = NULL;
    1233       20582 :     Oid        *nodeSortOperators = NULL;
    1234       20582 :     Oid        *nodeCollations = NULL;
    1235       20582 :     bool       *nodeNullsFirst = NULL;
    1236       20582 :     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       20582 :     if (best_path->subpaths == NIL)
    1248             :     {
    1249             :         /* Generate a Result plan with constant-FALSE gating qual */
    1250             :         Plan       *plan;
    1251             : 
    1252         972 :         plan = (Plan *) make_result(tlist,
    1253         972 :                                     (Node *) list_make1(makeBoolConst(false,
    1254             :                                                                       false)),
    1255             :                                     NULL);
    1256             : 
    1257         972 :         copy_generic_path_info(plan, (Path *) best_path);
    1258             : 
    1259         972 :         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       19610 :     plan = makeNode(Append);
    1274       19610 :     plan->plan.targetlist = tlist;
    1275       19610 :     plan->plan.qual = NIL;
    1276       19610 :     plan->plan.lefttree = NULL;
    1277       19610 :     plan->plan.righttree = NULL;
    1278       19610 :     plan->apprelids = rel->relids;
    1279             : 
    1280       19610 :     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       19610 :     consider_async = (enable_async_append && pathkeys == NIL &&
    1302       48648 :                       !best_path->path.parallel_safe &&
    1303        9428 :                       list_length(best_path->subpaths) > 1);
    1304             : 
    1305             :     /* Build the plan for each child */
    1306       65106 :     foreach(subpaths, best_path->subpaths)
    1307             :     {
    1308       45496 :         Path       *subpath = (Path *) lfirst(subpaths);
    1309             :         Plan       *subplan;
    1310             : 
    1311             :         /* Must insist that all children return the same tlist */
    1312       45496 :         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       45496 :         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       45496 :         if (consider_async && mark_async_capable_plan(subplan, subpath))
    1373             :         {
    1374             :             Assert(subplan->async_capable);
    1375         194 :             ++nasyncplans;
    1376             :         }
    1377             : 
    1378       45496 :         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       19610 :     if (enable_partition_pruning)
    1387             :     {
    1388             :         List       *prunequal;
    1389             : 
    1390       19556 :         prunequal = extract_actual_clauses(rel->baserestrictinfo, false);
    1391             : 
    1392       19556 :         if (best_path->path.param_info)
    1393             :         {
    1394         342 :             List       *prmquals = best_path->path.param_info->ppi_clauses;
    1395             : 
    1396         342 :             prmquals = extract_actual_clauses(prmquals, false);
    1397         342 :             prmquals = (List *) replace_nestloop_params(root,
    1398             :                                                         (Node *) prmquals);
    1399             : 
    1400         342 :             prunequal = list_concat(prunequal, prmquals);
    1401             :         }
    1402             : 
    1403       19556 :         if (prunequal != NIL)
    1404             :             partpruneinfo =
    1405        8872 :                 make_partition_pruneinfo(root, rel,
    1406             :                                          best_path->subpaths,
    1407             :                                          prunequal);
    1408             :     }
    1409             : 
    1410       19610 :     plan->appendplans = subplans;
    1411       19610 :     plan->nasyncplans = nasyncplans;
    1412       19610 :     plan->first_partial_plan = best_path->first_partial_path;
    1413       19610 :     plan->part_prune_info = partpruneinfo;
    1414             : 
    1415       19610 :     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       19610 :     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       19610 :         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         512 : create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path,
    1441             :                          int flags)
    1442             : {
    1443         512 :     MergeAppend *node = makeNode(MergeAppend);
    1444         512 :     Plan       *plan = &node->plan;
    1445         512 :     List       *tlist = build_path_tlist(root, &best_path->path);
    1446         512 :     int         orig_tlist_length = list_length(tlist);
    1447             :     bool        tlist_was_changed;
    1448         512 :     List       *pathkeys = best_path->path.pathkeys;
    1449         512 :     List       *subplans = NIL;
    1450             :     ListCell   *subpaths;
    1451         512 :     RelOptInfo *rel = best_path->path.parent;
    1452         512 :     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         512 :     copy_generic_path_info(plan, (Path *) best_path);
    1461         512 :     plan->targetlist = tlist;
    1462         512 :     plan->qual = NIL;
    1463         512 :     plan->lefttree = NULL;
    1464         512 :     plan->righttree = NULL;
    1465         512 :     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         512 :     (void) prepare_sort_from_pathkeys(plan, pathkeys,
    1474         512 :                                       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         512 :     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        1948 :     foreach(subpaths, best_path->subpaths)
    1490             :     {
    1491        1436 :         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        1436 :         subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
    1502             : 
    1503             :         /* Compute sort column info, and adjust subplan's tlist as needed */
    1504        1436 :         subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
    1505        1436 :                                              subpath->parent->relids,
    1506        1436 :                                              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        1436 :         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        1436 :         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        1436 :         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         512 :     if (enable_partition_pruning)
    1551             :     {
    1552             :         List       *prunequal;
    1553             : 
    1554         512 :         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         512 :         if (prunequal != NIL)
    1560         156 :             partpruneinfo = make_partition_pruneinfo(root, rel,
    1561             :                                                      best_path->subpaths,
    1562             :                                                      prunequal);
    1563             :     }
    1564             : 
    1565         512 :     node->mergeplans = subplans;
    1566         512 :     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         512 :     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         512 :         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      211318 : create_group_result_plan(PlannerInfo *root, GroupResultPath *best_path)
    1591             : {
    1592             :     Result     *plan;
    1593             :     List       *tlist;
    1594             :     List       *quals;
    1595             : 
    1596      211318 :     tlist = build_path_tlist(root, &best_path->path);
    1597             : 
    1598             :     /* best_path->quals is just bare clauses */
    1599      211318 :     quals = order_qual_clauses(root, best_path->quals);
    1600             : 
    1601      211318 :     plan = make_result(tlist, (Node *) quals, NULL);
    1602             : 
    1603      211318 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    1604             : 
    1605      211318 :     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        8734 : 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        8734 :     subplan = create_plan_recurse(root, best_path->subpath, 0);
    1623             : 
    1624        8734 :     tlist = build_path_tlist(root, &best_path->path);
    1625             : 
    1626        8734 :     plan = make_project_set(tlist, subplan);
    1627             : 
    1628        8734 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    1629             : 
    1630        8734 :     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        3658 : 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        3658 :     subplan = create_plan_recurse(root, best_path->subpath,
    1652             :                                   flags | CP_SMALL_TLIST);
    1653             : 
    1654        3658 :     plan = make_material(subplan);
    1655             : 
    1656        3658 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    1657             : 
    1658        3658 :     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        1374 : 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        1374 :     List       *param_exprs = NIL;
    1677             :     ListCell   *lc;
    1678             :     ListCell   *lc2;
    1679             :     int         nkeys;
    1680             :     int         i;
    1681             : 
    1682        1374 :     subplan = create_plan_recurse(root, best_path->subpath,
    1683             :                                   flags | CP_SMALL_TLIST);
    1684             : 
    1685        1374 :     param_exprs = (List *) replace_nestloop_params(root, (Node *)
    1686        1374 :                                                    best_path->param_exprs);
    1687             : 
    1688        1374 :     nkeys = list_length(param_exprs);
    1689             :     Assert(nkeys > 0);
    1690        1374 :     operators = palloc(nkeys * sizeof(Oid));
    1691        1374 :     collations = palloc(nkeys * sizeof(Oid));
    1692             : 
    1693        1374 :     i = 0;
    1694        2790 :     forboth(lc, param_exprs, lc2, best_path->hash_operators)
    1695             :     {
    1696        1416 :         Expr       *param_expr = (Expr *) lfirst(lc);
    1697        1416 :         Oid         opno = lfirst_oid(lc2);
    1698             : 
    1699        1416 :         operators[i] = opno;
    1700        1416 :         collations[i] = exprCollation((Node *) param_expr);
    1701        1416 :         i++;
    1702             :     }
    1703             : 
    1704        1374 :     keyparamids = pull_paramids((Expr *) param_exprs);
    1705             : 
    1706        1374 :     plan = make_memoize(subplan, operators, collations, param_exprs,
    1707        1374 :                         best_path->singlerow, best_path->binary_mode,
    1708             :                         best_path->est_entries, keyparamids);
    1709             : 
    1710        1374 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    1711             : 
    1712        1374 :     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         934 : 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         934 :     subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
    1936             : 
    1937         934 :     tlist = build_path_tlist(root, &best_path->path);
    1938             : 
    1939         934 :     gather_plan = make_gather(tlist,
    1940             :                               NIL,
    1941             :                               best_path->num_workers,
    1942             :                               assign_special_exec_param(root),
    1943         934 :                               best_path->single_copy,
    1944             :                               subplan);
    1945             : 
    1946         934 :     copy_generic_path_info(&gather_plan->plan, &best_path->path);
    1947             : 
    1948             :     /* use parallel mode for parallel plans. */
    1949         934 :     root->glob->parallelModeNeeded = true;
    1950             : 
    1951         934 :     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         330 : create_gather_merge_plan(PlannerInfo *root, GatherMergePath *best_path)
    1962             : {
    1963             :     GatherMerge *gm_plan;
    1964             :     Plan       *subplan;
    1965         330 :     List       *pathkeys = best_path->path.pathkeys;
    1966         330 :     List       *tlist = build_path_tlist(root, &best_path->path);
    1967             : 
    1968             :     /* As with Gather, project away columns in the workers. */
    1969         330 :     subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
    1970             : 
    1971             :     /* Create a shell for a GatherMerge plan. */
    1972         330 :     gm_plan = makeNode(GatherMerge);
    1973         330 :     gm_plan->plan.targetlist = tlist;
    1974         330 :     gm_plan->num_workers = best_path->num_workers;
    1975         330 :     copy_generic_path_info(&gm_plan->plan, &best_path->path);
    1976             : 
    1977             :     /* Assign the rescan Param. */
    1978         330 :     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         330 :     subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
    1985         330 :                                          best_path->subpath->parent->relids,
    1986         330 :                                          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         330 :     gm_plan->plan.lefttree = subplan;
    2002             : 
    2003             :     /* use parallel mode for parallel plans. */
    2004         330 :     root->glob->parallelModeNeeded = true;
    2005             : 
    2006         330 :     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      337682 : create_projection_plan(PlannerInfo *root, ProjectionPath *best_path, int flags)
    2018             : {
    2019             :     Plan       *plan;
    2020             :     Plan       *subplan;
    2021             :     List       *tlist;
    2022      337682 :     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      337682 :     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         964 :         subplan = create_plan_recurse(root, best_path->subpath, 0);
    2045         964 :         tlist = subplan->targetlist;
    2046         964 :         if (flags & CP_LABEL_TLIST)
    2047         396 :             apply_pathtarget_labeling_to_tlist(tlist,
    2048             :                                                best_path->path.pathtarget);
    2049             :     }
    2050      336718 :     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      334924 :         subplan = create_plan_recurse(root, best_path->subpath,
    2059             :                                       CP_IGNORE_TLIST);
    2060             :         Assert(is_projection_capable_plan(subplan));
    2061      334924 :         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        1794 :         subplan = create_plan_recurse(root, best_path->subpath, 0);
    2070        1794 :         tlist = build_path_tlist(root, &best_path->path);
    2071        1794 :         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      337682 :     if (!needs_result_node)
    2083             :     {
    2084             :         /* Don't need a separate Result, just assign tlist to subplan */
    2085      336026 :         plan = subplan;
    2086      336026 :         plan->targetlist = tlist;
    2087             : 
    2088             :         /* Label plan with the estimated costs we actually used */
    2089      336026 :         plan->startup_cost = best_path->path.startup_cost;
    2090      336026 :         plan->total_cost = best_path->path.total_cost;
    2091      336026 :         plan->plan_rows = best_path->path.rows;
    2092      336026 :         plan->plan_width = best_path->path.pathtarget->width;
    2093      336026 :         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        1656 :         plan = (Plan *) make_result(tlist, NULL, subplan);
    2100             : 
    2101        1656 :         copy_generic_path_info(plan, (Path *) best_path);
    2102             :     }
    2103             : 
    2104      337682 :     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         130 : 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         130 :     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         128 :         subplan->targetlist = tlist;
    2167         128 :         subplan->parallel_safe &= tlist_parallel_safe;
    2168             :     }
    2169         130 :     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       59178 : 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       59178 :     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       59178 :     plan = make_sort_from_pathkeys(subplan, best_path->path.pathkeys,
    2199       59178 :                                    IS_OTHER_REL(best_path->subpath->parent) ?
    2200         348 :                                    best_path->path.parent->relids : NULL);
    2201             : 
    2202       59178 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2203             : 
    2204       59178 :     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         758 : 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         758 :     subplan = create_plan_recurse(root, best_path->spath.subpath,
    2221             :                                   flags | CP_SMALL_TLIST);
    2222         758 :     plan = make_incrementalsort_from_pathkeys(subplan,
    2223             :                                               best_path->spath.path.pathkeys,
    2224         758 :                                               IS_OTHER_REL(best_path->spath.subpath->parent) ?
    2225           0 :                                               best_path->spath.path.parent->relids : NULL,
    2226             :                                               best_path->nPresortedCols);
    2227             : 
    2228         758 :     copy_generic_path_info(&plan->sort.plan, (Path *) best_path);
    2229             : 
    2230         758 :     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         246 : 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         246 :     subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
    2252             : 
    2253         246 :     tlist = build_path_tlist(root, &best_path->path);
    2254             : 
    2255         246 :     quals = order_qual_clauses(root, best_path->qual);
    2256             : 
    2257         492 :     plan = make_group(tlist,
    2258             :                       quals,
    2259         246 :                       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         246 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2268             : 
    2269         246 :     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        5048 : 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        5048 :     subplan = create_plan_recurse(root, best_path->subpath,
    2289             :                                   flags | CP_LABEL_TLIST);
    2290             : 
    2291        5048 :     plan = make_unique_from_pathkeys(subplan,
    2292             :                                      best_path->path.pathkeys,
    2293             :                                      best_path->numkeys);
    2294             : 
    2295        5048 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2296             : 
    2297        5048 :     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       38090 : 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       38090 :     subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
    2319             : 
    2320       38090 :     tlist = build_path_tlist(root, &best_path->path);
    2321             : 
    2322       38090 :     quals = order_qual_clauses(root, best_path->qual);
    2323             : 
    2324       76180 :     plan = make_agg(tlist, quals,
    2325             :                     best_path->aggstrategy,
    2326             :                     best_path->aggsplit,
    2327       38090 :                     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       38090 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2340             : 
    2341       38090 :     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        2486 : create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path)
    2617             : {
    2618             :     WindowAgg  *plan;
    2619        2486 :     WindowClause *wc = best_path->winclause;
    2620        2486 :     int         numPart = list_length(wc->partitionClause);
    2621        2486 :     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        2486 :     subplan = create_plan_recurse(root, best_path->subpath,
    2641             :                                   CP_LABEL_TLIST | CP_SMALL_TLIST);
    2642             : 
    2643        2486 :     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        2486 :     partColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numPart);
    2650        2486 :     partOperators = (Oid *) palloc(sizeof(Oid) * numPart);
    2651        2486 :     partCollations = (Oid *) palloc(sizeof(Oid) * numPart);
    2652             : 
    2653        2486 :     partNumCols = 0;
    2654        3186 :     foreach(lc, wc->partitionClause)
    2655             :     {
    2656         700 :         SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
    2657         700 :         TargetEntry *tle = get_sortgroupclause_tle(sgc, subplan->targetlist);
    2658             : 
    2659             :         Assert(OidIsValid(sgc->eqop));
    2660         700 :         partColIdx[partNumCols] = tle->resno;
    2661         700 :         partOperators[partNumCols] = sgc->eqop;
    2662         700 :         partCollations[partNumCols] = exprCollation((Node *) tle->expr);
    2663         700 :         partNumCols++;
    2664             :     }
    2665             : 
    2666        2486 :     ordColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numOrder);
    2667        2486 :     ordOperators = (Oid *) palloc(sizeof(Oid) * numOrder);
    2668        2486 :     ordCollations = (Oid *) palloc(sizeof(Oid) * numOrder);
    2669             : 
    2670        2486 :     ordNumCols = 0;
    2671        4630 :     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        2486 :     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        2486 :                           wc->inRangeAsc,
    2701        2486 :                           wc->inRangeNullsFirst,
    2702             :                           best_path->runCondition,
    2703             :                           best_path->qual,
    2704        2486 :                           best_path->topwindow,
    2705             :                           subplan);
    2706             : 
    2707        2486 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2708             : 
    2709        2486 :     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         680 : create_setop_plan(PlannerInfo *root, SetOpPath *best_path, int flags)
    2720             : {
    2721             :     SetOp      *plan;
    2722         680 :     List       *tlist = build_path_tlist(root, &best_path->path);
    2723             :     Plan       *leftplan;
    2724             :     Plan       *rightplan;
    2725             :     long        numGroups;
    2726             : 
    2727             :     /*
    2728             :      * SetOp doesn't project, so tlist requirements pass through; moreover we
    2729             :      * need grouping columns to be labeled.
    2730             :      */
    2731         680 :     leftplan = create_plan_recurse(root, best_path->leftpath,
    2732             :                                    flags | CP_LABEL_TLIST);
    2733         680 :     rightplan = create_plan_recurse(root, best_path->rightpath,
    2734             :                                     flags | CP_LABEL_TLIST);
    2735             : 
    2736             :     /* Convert numGroups to long int --- but 'ware overflow! */
    2737         680 :     numGroups = clamp_cardinality_to_long(best_path->numGroups);
    2738             : 
    2739         680 :     plan = make_setop(best_path->cmd,
    2740             :                       best_path->strategy,
    2741             :                       tlist,
    2742             :                       leftplan,
    2743             :                       rightplan,
    2744             :                       best_path->groupList,
    2745             :                       numGroups);
    2746             : 
    2747         680 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2748             : 
    2749         680 :     return plan;
    2750             : }
    2751             : 
    2752             : /*
    2753             :  * create_recursiveunion_plan
    2754             :  *
    2755             :  *    Create a RecursiveUnion plan for 'best_path' and (recursively) plans
    2756             :  *    for its subpaths.
    2757             :  */
    2758             : static RecursiveUnion *
    2759         816 : create_recursiveunion_plan(PlannerInfo *root, RecursiveUnionPath *best_path)
    2760             : {
    2761             :     RecursiveUnion *plan;
    2762             :     Plan       *leftplan;
    2763             :     Plan       *rightplan;
    2764             :     List       *tlist;
    2765             :     long        numGroups;
    2766             : 
    2767             :     /* Need both children to produce same tlist, so force it */
    2768         816 :     leftplan = create_plan_recurse(root, best_path->leftpath, CP_EXACT_TLIST);
    2769         816 :     rightplan = create_plan_recurse(root, best_path->rightpath, CP_EXACT_TLIST);
    2770             : 
    2771         816 :     tlist = build_path_tlist(root, &best_path->path);
    2772             : 
    2773             :     /* Convert numGroups to long int --- but 'ware overflow! */
    2774         816 :     numGroups = clamp_cardinality_to_long(best_path->numGroups);
    2775             : 
    2776         816 :     plan = make_recursive_union(tlist,
    2777             :                                 leftplan,
    2778             :                                 rightplan,
    2779             :                                 best_path->wtParam,
    2780             :                                 best_path->distinctList,
    2781             :                                 numGroups);
    2782             : 
    2783         816 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2784             : 
    2785         816 :     return plan;
    2786             : }
    2787             : 
    2788             : /*
    2789             :  * create_lockrows_plan
    2790             :  *
    2791             :  *    Create a LockRows plan for 'best_path' and (recursively) plans
    2792             :  *    for its subpaths.
    2793             :  */
    2794             : static LockRows *
    2795        7846 : create_lockrows_plan(PlannerInfo *root, LockRowsPath *best_path,
    2796             :                      int flags)
    2797             : {
    2798             :     LockRows   *plan;
    2799             :     Plan       *subplan;
    2800             : 
    2801             :     /* LockRows doesn't project, so tlist requirements pass through */
    2802        7846 :     subplan = create_plan_recurse(root, best_path->subpath, flags);
    2803             : 
    2804        7846 :     plan = make_lockrows(subplan, best_path->rowMarks, best_path->epqParam);
    2805             : 
    2806        7846 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2807             : 
    2808        7846 :     return plan;
    2809             : }
    2810             : 
    2811             : /*
    2812             :  * create_modifytable_plan
    2813             :  *    Create a ModifyTable plan for 'best_path'.
    2814             :  *
    2815             :  *    Returns a Plan node.
    2816             :  */
    2817             : static ModifyTable *
    2818       90912 : create_modifytable_plan(PlannerInfo *root, ModifyTablePath *best_path)
    2819             : {
    2820             :     ModifyTable *plan;
    2821       90912 :     Path       *subpath = best_path->subpath;
    2822             :     Plan       *subplan;
    2823             : 
    2824             :     /* Subplan must produce exactly the specified tlist */
    2825       90912 :     subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
    2826             : 
    2827             :     /* Transfer resname/resjunk labeling, too, to keep executor happy */
    2828       90912 :     apply_tlist_labeling(subplan->targetlist, root->processed_tlist);
    2829             : 
    2830       90912 :     plan = make_modifytable(root,
    2831             :                             subplan,
    2832             :                             best_path->operation,
    2833       90912 :                             best_path->canSetTag,
    2834             :                             best_path->nominalRelation,
    2835             :                             best_path->rootRelation,
    2836       90912 :                             best_path->partColsUpdated,
    2837             :                             best_path->resultRelations,
    2838             :                             best_path->updateColnosLists,
    2839             :                             best_path->withCheckOptionLists,
    2840             :                             best_path->returningLists,
    2841             :                             best_path->rowMarks,
    2842             :                             best_path->onconflict,
    2843             :                             best_path->mergeActionLists,
    2844             :                             best_path->mergeJoinConditions,
    2845             :                             best_path->epqParam);
    2846             : 
    2847       90516 :     copy_generic_path_info(&plan->plan, &best_path->path);
    2848             : 
    2849       90516 :     return plan;
    2850             : }
    2851             : 
    2852             : /*
    2853             :  * create_limit_plan
    2854             :  *
    2855             :  *    Create a Limit plan for 'best_path' and (recursively) plans
    2856             :  *    for its subpaths.
    2857             :  */
    2858             : static Limit *
    2859        4160 : create_limit_plan(PlannerInfo *root, LimitPath *best_path, int flags)
    2860             : {
    2861             :     Limit      *plan;
    2862             :     Plan       *subplan;
    2863        4160 :     int         numUniqkeys = 0;
    2864        4160 :     AttrNumber *uniqColIdx = NULL;
    2865        4160 :     Oid        *uniqOperators = NULL;
    2866        4160 :     Oid        *uniqCollations = NULL;
    2867             : 
    2868             :     /* Limit doesn't project, so tlist requirements pass through */
    2869        4160 :     subplan = create_plan_recurse(root, best_path->subpath, flags);
    2870             : 
    2871             :     /* Extract information necessary for comparing rows for WITH TIES. */
    2872        4160 :     if (best_path->limitOption == LIMIT_OPTION_WITH_TIES)
    2873             :     {
    2874          30 :         Query      *parse = root->parse;
    2875             :         ListCell   *l;
    2876             : 
    2877          30 :         numUniqkeys = list_length(parse->sortClause);
    2878          30 :         uniqColIdx = (AttrNumber *) palloc(numUniqkeys * sizeof(AttrNumber));
    2879          30 :         uniqOperators = (Oid *) palloc(numUniqkeys * sizeof(Oid));
    2880          30 :         uniqCollations = (Oid *) palloc(numUniqkeys * sizeof(Oid));
    2881             : 
    2882          30 :         numUniqkeys = 0;
    2883          60 :         foreach(l, parse->sortClause)
    2884             :         {
    2885          30 :             SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
    2886          30 :             TargetEntry *tle = get_sortgroupclause_tle(sortcl, parse->targetList);
    2887             : 
    2888          30 :             uniqColIdx[numUniqkeys] = tle->resno;
    2889          30 :             uniqOperators[numUniqkeys] = sortcl->eqop;
    2890          30 :             uniqCollations[numUniqkeys] = exprCollation((Node *) tle->expr);
    2891          30 :             numUniqkeys++;
    2892             :         }
    2893             :     }
    2894             : 
    2895        4160 :     plan = make_limit(subplan,
    2896             :                       best_path->limitOffset,
    2897             :                       best_path->limitCount,
    2898             :                       best_path->limitOption,
    2899             :                       numUniqkeys, uniqColIdx, uniqOperators, uniqCollations);
    2900             : 
    2901        4160 :     copy_generic_path_info(&plan->plan, (Path *) best_path);
    2902             : 
    2903        4160 :     return plan;
    2904             : }
    2905             : 
    2906             : 
    2907             : /*****************************************************************************
    2908             :  *
    2909             :  *  BASE-RELATION SCAN METHODS
    2910             :  *
    2911             :  *****************************************************************************/
    2912             : 
    2913             : 
    2914             : /*
    2915             :  * create_seqscan_plan
    2916             :  *   Returns a seqscan plan for the base relation scanned by 'best_path'
    2917             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    2918             :  */
    2919             : static SeqScan *
    2920      191710 : create_seqscan_plan(PlannerInfo *root, Path *best_path,
    2921             :                     List *tlist, List *scan_clauses)
    2922             : {
    2923             :     SeqScan    *scan_plan;
    2924      191710 :     Index       scan_relid = best_path->parent->relid;
    2925             : 
    2926             :     /* it should be a base rel... */
    2927             :     Assert(scan_relid > 0);
    2928             :     Assert(best_path->parent->rtekind == RTE_RELATION);
    2929             : 
    2930             :     /* Sort clauses into best execution order */
    2931      191710 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    2932             : 
    2933             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    2934      191710 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    2935             : 
    2936             :     /* Replace any outer-relation variables with nestloop params */
    2937      191710 :     if (best_path->param_info)
    2938             :     {
    2939             :         scan_clauses = (List *)
    2940         468 :             replace_nestloop_params(root, (Node *) scan_clauses);
    2941             :     }
    2942             : 
    2943      191710 :     scan_plan = make_seqscan(tlist,
    2944             :                              scan_clauses,
    2945             :                              scan_relid);
    2946             : 
    2947      191710 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    2948             : 
    2949      191710 :     return scan_plan;
    2950             : }
    2951             : 
    2952             : /*
    2953             :  * create_samplescan_plan
    2954             :  *   Returns a samplescan plan for the base relation scanned by 'best_path'
    2955             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    2956             :  */
    2957             : static SampleScan *
    2958         300 : create_samplescan_plan(PlannerInfo *root, Path *best_path,
    2959             :                        List *tlist, List *scan_clauses)
    2960             : {
    2961             :     SampleScan *scan_plan;
    2962         300 :     Index       scan_relid = best_path->parent->relid;
    2963             :     RangeTblEntry *rte;
    2964             :     TableSampleClause *tsc;
    2965             : 
    2966             :     /* it should be a base rel with a tablesample clause... */
    2967             :     Assert(scan_relid > 0);
    2968         300 :     rte = planner_rt_fetch(scan_relid, root);
    2969             :     Assert(rte->rtekind == RTE_RELATION);
    2970         300 :     tsc = rte->tablesample;
    2971             :     Assert(tsc != NULL);
    2972             : 
    2973             :     /* Sort clauses into best execution order */
    2974         300 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    2975             : 
    2976             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    2977         300 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    2978             : 
    2979             :     /* Replace any outer-relation variables with nestloop params */
    2980         300 :     if (best_path->param_info)
    2981             :     {
    2982             :         scan_clauses = (List *)
    2983          66 :             replace_nestloop_params(root, (Node *) scan_clauses);
    2984             :         tsc = (TableSampleClause *)
    2985          66 :             replace_nestloop_params(root, (Node *) tsc);
    2986             :     }
    2987             : 
    2988         300 :     scan_plan = make_samplescan(tlist,
    2989             :                                 scan_clauses,
    2990             :                                 scan_relid,
    2991             :                                 tsc);
    2992             : 
    2993         300 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    2994             : 
    2995         300 :     return scan_plan;
    2996             : }
    2997             : 
    2998             : /*
    2999             :  * create_indexscan_plan
    3000             :  *    Returns an indexscan plan for the base relation scanned by 'best_path'
    3001             :  *    with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3002             :  *
    3003             :  * We use this for both plain IndexScans and IndexOnlyScans, because the
    3004             :  * qual preprocessing work is the same for both.  Note that the caller tells
    3005             :  * us which to build --- we don't look at best_path->path.pathtype, because
    3006             :  * create_bitmap_subplan needs to be able to override the prior decision.
    3007             :  */
    3008             : static Scan *
    3009      166364 : create_indexscan_plan(PlannerInfo *root,
    3010             :                       IndexPath *best_path,
    3011             :                       List *tlist,
    3012             :                       List *scan_clauses,
    3013             :                       bool indexonly)
    3014             : {
    3015             :     Scan       *scan_plan;
    3016      166364 :     List       *indexclauses = best_path->indexclauses;
    3017      166364 :     List       *indexorderbys = best_path->indexorderbys;
    3018      166364 :     Index       baserelid = best_path->path.parent->relid;
    3019      166364 :     IndexOptInfo *indexinfo = best_path->indexinfo;
    3020      166364 :     Oid         indexoid = indexinfo->indexoid;
    3021             :     List       *qpqual;
    3022             :     List       *stripped_indexquals;
    3023             :     List       *fixed_indexquals;
    3024             :     List       *fixed_indexorderbys;
    3025      166364 :     List       *indexorderbyops = NIL;
    3026             :     ListCell   *l;
    3027             : 
    3028             :     /* it should be a base rel... */
    3029             :     Assert(baserelid > 0);
    3030             :     Assert(best_path->path.parent->rtekind == RTE_RELATION);
    3031             :     /* check the scan direction is valid */
    3032             :     Assert(best_path->indexscandir == ForwardScanDirection ||
    3033             :            best_path->indexscandir == BackwardScanDirection);
    3034             : 
    3035             :     /*
    3036             :      * Extract the index qual expressions (stripped of RestrictInfos) from the
    3037             :      * IndexClauses list, and prepare a copy with index Vars substituted for
    3038             :      * table Vars.  (This step also does replace_nestloop_params on the
    3039             :      * fixed_indexquals.)
    3040             :      */
    3041      166364 :     fix_indexqual_references(root, best_path,
    3042             :                              &stripped_indexquals,
    3043             :                              &fixed_indexquals);
    3044             : 
    3045             :     /*
    3046             :      * Likewise fix up index attr references in the ORDER BY expressions.
    3047             :      */
    3048      166364 :     fixed_indexorderbys = fix_indexorderby_references(root, best_path);
    3049             : 
    3050             :     /*
    3051             :      * The qpqual list must contain all restrictions not automatically handled
    3052             :      * by the index, other than pseudoconstant clauses which will be handled
    3053             :      * by a separate gating plan node.  All the predicates in the indexquals
    3054             :      * will be checked (either by the index itself, or by nodeIndexscan.c),
    3055             :      * but if there are any "special" operators involved then they must be
    3056             :      * included in qpqual.  The upshot is that qpqual must contain
    3057             :      * scan_clauses minus whatever appears in indexquals.
    3058             :      *
    3059             :      * is_redundant_with_indexclauses() detects cases where a scan clause is
    3060             :      * present in the indexclauses list or is generated from the same
    3061             :      * EquivalenceClass as some indexclause, and is therefore redundant with
    3062             :      * it, though not equal.  (The latter happens when indxpath.c prefers a
    3063             :      * different derived equality than what generate_join_implied_equalities
    3064             :      * picked for a parameterized scan's ppi_clauses.)  Note that it will not
    3065             :      * match to lossy index clauses, which is critical because we have to
    3066             :      * include the original clause in qpqual in that case.
    3067             :      *
    3068             :      * In some situations (particularly with OR'd index conditions) we may
    3069             :      * have scan_clauses that are not equal to, but are logically implied by,
    3070             :      * the index quals; so we also try a predicate_implied_by() check to see
    3071             :      * if we can discard quals that way.  (predicate_implied_by assumes its
    3072             :      * first input contains only immutable functions, so we have to check
    3073             :      * that.)
    3074             :      *
    3075             :      * Note: if you change this bit of code you should also look at
    3076             :      * extract_nonindex_conditions() in costsize.c.
    3077             :      */
    3078      166364 :     qpqual = NIL;
    3079      396880 :     foreach(l, scan_clauses)
    3080             :     {
    3081      230516 :         RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
    3082             : 
    3083      230516 :         if (rinfo->pseudoconstant)
    3084        1612 :             continue;           /* we may drop pseudoconstants here */
    3085      228904 :         if (is_redundant_with_indexclauses(rinfo, indexclauses))
    3086      155728 :             continue;           /* dup or derived from same EquivalenceClass */
    3087      145072 :         if (!contain_mutable_functions((Node *) rinfo->clause) &&
    3088       71896 :             predicate_implied_by(list_make1(rinfo->clause), stripped_indexquals,
    3089             :                                  false))
    3090         174 :             continue;           /* provably implied by indexquals */
    3091       73002 :         qpqual = lappend(qpqual, rinfo);
    3092             :     }
    3093             : 
    3094             :     /* Sort clauses into best execution order */
    3095      166364 :     qpqual = order_qual_clauses(root, qpqual);
    3096             : 
    3097             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3098      166364 :     qpqual = extract_actual_clauses(qpqual, false);
    3099             : 
    3100             :     /*
    3101             :      * We have to replace any outer-relation variables with nestloop params in
    3102             :      * the indexqualorig, qpqual, and indexorderbyorig expressions.  A bit
    3103             :      * annoying to have to do this separately from the processing in
    3104             :      * fix_indexqual_references --- rethink this when generalizing the inner
    3105             :      * indexscan support.  But note we can't really do this earlier because
    3106             :      * it'd break the comparisons to predicates above ... (or would it?  Those
    3107             :      * wouldn't have outer refs)
    3108             :      */
    3109      166364 :     if (best_path->path.param_info)
    3110             :     {
    3111       33166 :         stripped_indexquals = (List *)
    3112       33166 :             replace_nestloop_params(root, (Node *) stripped_indexquals);
    3113             :         qpqual = (List *)
    3114       33166 :             replace_nestloop_params(root, (Node *) qpqual);
    3115             :         indexorderbys = (List *)
    3116       33166 :             replace_nestloop_params(root, (Node *) indexorderbys);
    3117             :     }
    3118             : 
    3119             :     /*
    3120             :      * If there are ORDER BY expressions, look up the sort operators for their
    3121             :      * result datatypes.
    3122             :      */
    3123      166364 :     if (indexorderbys)
    3124             :     {
    3125             :         ListCell   *pathkeyCell,
    3126             :                    *exprCell;
    3127             : 
    3128             :         /*
    3129             :          * PathKey contains OID of the btree opfamily we're sorting by, but
    3130             :          * that's not quite enough because we need the expression's datatype
    3131             :          * to look up the sort operator in the operator family.
    3132             :          */
    3133             :         Assert(list_length(best_path->path.pathkeys) == list_length(indexorderbys));
    3134         766 :         forboth(pathkeyCell, best_path->path.pathkeys, exprCell, indexorderbys)
    3135             :         {
    3136         386 :             PathKey    *pathkey = (PathKey *) lfirst(pathkeyCell);
    3137         386 :             Node       *expr = (Node *) lfirst(exprCell);
    3138         386 :             Oid         exprtype = exprType(expr);
    3139             :             Oid         sortop;
    3140             : 
    3141             :             /* Get sort operator from opfamily */
    3142         386 :             sortop = get_opfamily_member(pathkey->pk_opfamily,
    3143             :                                          exprtype,
    3144             :                                          exprtype,
    3145         386 :                                          pathkey->pk_strategy);
    3146         386 :             if (!OidIsValid(sortop))
    3147           0 :                 elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
    3148             :                      pathkey->pk_strategy, exprtype, exprtype, pathkey->pk_opfamily);
    3149         386 :             indexorderbyops = lappend_oid(indexorderbyops, sortop);
    3150             :         }
    3151             :     }
    3152             : 
    3153             :     /*
    3154             :      * For an index-only scan, we must mark indextlist entries as resjunk if
    3155             :      * they are columns that the index AM can't return; this cues setrefs.c to
    3156             :      * not generate references to those columns.
    3157             :      */
    3158      166364 :     if (indexonly)
    3159             :     {
    3160       15290 :         int         i = 0;
    3161             : 
    3162       36014 :         foreach(l, indexinfo->indextlist)
    3163             :         {
    3164       20724 :             TargetEntry *indextle = (TargetEntry *) lfirst(l);
    3165             : 
    3166       20724 :             indextle->resjunk = !indexinfo->canreturn[i];
    3167       20724 :             i++;
    3168             :         }
    3169             :     }
    3170             : 
    3171             :     /* Finally ready to build the plan node */
    3172      166364 :     if (indexonly)
    3173       15290 :         scan_plan = (Scan *) make_indexonlyscan(tlist,
    3174             :                                                 qpqual,
    3175             :                                                 baserelid,
    3176             :                                                 indexoid,
    3177             :                                                 fixed_indexquals,
    3178             :                                                 stripped_indexquals,
    3179             :                                                 fixed_indexorderbys,
    3180             :                                                 indexinfo->indextlist,
    3181             :                                                 best_path->indexscandir);
    3182             :     else
    3183      151074 :         scan_plan = (Scan *) make_indexscan(tlist,
    3184             :                                             qpqual,
    3185             :                                             baserelid,
    3186             :                                             indexoid,
    3187             :                                             fixed_indexquals,
    3188             :                                             stripped_indexquals,
    3189             :                                             fixed_indexorderbys,
    3190             :                                             indexorderbys,
    3191             :                                             indexorderbyops,
    3192             :                                             best_path->indexscandir);
    3193             : 
    3194      166364 :     copy_generic_path_info(&scan_plan->plan, &best_path->path);
    3195             : 
    3196      166364 :     return scan_plan;
    3197             : }
    3198             : 
    3199             : /*
    3200             :  * create_bitmap_scan_plan
    3201             :  *    Returns a bitmap scan plan for the base relation scanned by 'best_path'
    3202             :  *    with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3203             :  */
    3204             : static BitmapHeapScan *
    3205       20156 : create_bitmap_scan_plan(PlannerInfo *root,
    3206             :                         BitmapHeapPath *best_path,
    3207             :                         List *tlist,
    3208             :                         List *scan_clauses)
    3209             : {
    3210       20156 :     Index       baserelid = best_path->path.parent->relid;
    3211             :     Plan       *bitmapqualplan;
    3212             :     List       *bitmapqualorig;
    3213             :     List       *indexquals;
    3214             :     List       *indexECs;
    3215             :     List       *qpqual;
    3216             :     ListCell   *l;
    3217             :     BitmapHeapScan *scan_plan;
    3218             : 
    3219             :     /* it should be a base rel... */
    3220             :     Assert(baserelid > 0);
    3221             :     Assert(best_path->path.parent->rtekind == RTE_RELATION);
    3222             : 
    3223             :     /* Process the bitmapqual tree into a Plan tree and qual lists */
    3224       20156 :     bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
    3225             :                                            &bitmapqualorig, &indexquals,
    3226             :                                            &indexECs);
    3227             : 
    3228       20156 :     if (best_path->path.parallel_aware)
    3229          30 :         bitmap_subplan_mark_shared(bitmapqualplan);
    3230             : 
    3231             :     /*
    3232             :      * The qpqual list must contain all restrictions not automatically handled
    3233             :      * by the index, other than pseudoconstant clauses which will be handled
    3234             :      * by a separate gating plan node.  All the predicates in the indexquals
    3235             :      * will be checked (either by the index itself, or by
    3236             :      * nodeBitmapHeapscan.c), but if there are any "special" operators
    3237             :      * involved then they must be added to qpqual.  The upshot is that qpqual
    3238             :      * must contain scan_clauses minus whatever appears in indexquals.
    3239             :      *
    3240             :      * This loop is similar to the comparable code in create_indexscan_plan(),
    3241             :      * but with some differences because it has to compare the scan clauses to
    3242             :      * stripped (no RestrictInfos) indexquals.  See comments there for more
    3243             :      * info.
    3244             :      *
    3245             :      * In normal cases simple equal() checks will be enough to spot duplicate
    3246             :      * clauses, so we try that first.  We next see if the scan clause is
    3247             :      * redundant with any top-level indexqual by virtue of being generated
    3248             :      * from the same EC.  After that, try predicate_implied_by().
    3249             :      *
    3250             :      * Unlike create_indexscan_plan(), the predicate_implied_by() test here is
    3251             :      * useful for getting rid of qpquals that are implied by index predicates,
    3252             :      * because the predicate conditions are included in the "indexquals"
    3253             :      * returned by create_bitmap_subplan().  Bitmap scans have to do it that
    3254             :      * way because predicate conditions need to be rechecked if the scan
    3255             :      * becomes lossy, so they have to be included in bitmapqualorig.
    3256             :      */
    3257       20156 :     qpqual = NIL;
    3258       46378 :     foreach(l, scan_clauses)
    3259             :     {
    3260       26222 :         RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
    3261       26222 :         Node       *clause = (Node *) rinfo->clause;
    3262             : 
    3263       26222 :         if (rinfo->pseudoconstant)
    3264          24 :             continue;           /* we may drop pseudoconstants here */
    3265       26198 :         if (list_member(indexquals, clause))
    3266       20184 :             continue;           /* simple duplicate */
    3267        6014 :         if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
    3268          18 :             continue;           /* derived from same EquivalenceClass */
    3269       11864 :         if (!contain_mutable_functions(clause) &&
    3270        5868 :             predicate_implied_by(list_make1(clause), indexquals, false))
    3271        1096 :             continue;           /* provably implied by indexquals */
    3272        4900 :         qpqual = lappend(qpqual, rinfo);
    3273             :     }
    3274             : 
    3275             :     /* Sort clauses into best execution order */
    3276       20156 :     qpqual = order_qual_clauses(root, qpqual);
    3277             : 
    3278             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3279       20156 :     qpqual = extract_actual_clauses(qpqual, false);
    3280             : 
    3281             :     /*
    3282             :      * When dealing with special operators, we will at this point have
    3283             :      * duplicate clauses in qpqual and bitmapqualorig.  We may as well drop
    3284             :      * 'em from bitmapqualorig, since there's no point in making the tests
    3285             :      * twice.
    3286             :      */
    3287       20156 :     bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
    3288             : 
    3289             :     /*
    3290             :      * We have to replace any outer-relation variables with nestloop params in
    3291             :      * the qpqual and bitmapqualorig expressions.  (This was already done for
    3292             :      * expressions attached to plan nodes in the bitmapqualplan tree.)
    3293             :      */
    3294       20156 :     if (best_path->path.param_info)
    3295             :     {
    3296             :         qpqual = (List *)
    3297         742 :             replace_nestloop_params(root, (Node *) qpqual);
    3298         742 :         bitmapqualorig = (List *)
    3299         742 :             replace_nestloop_params(root, (Node *) bitmapqualorig);
    3300             :     }
    3301             : 
    3302             :     /* Finally ready to build the plan node */
    3303       20156 :     scan_plan = make_bitmap_heapscan(tlist,
    3304             :                                      qpqual,
    3305             :                                      bitmapqualplan,
    3306             :                                      bitmapqualorig,
    3307             :                                      baserelid);
    3308             : 
    3309       20156 :     copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
    3310             : 
    3311       20156 :     return scan_plan;
    3312             : }
    3313             : 
    3314             : /*
    3315             :  * Given a bitmapqual tree, generate the Plan tree that implements it
    3316             :  *
    3317             :  * As byproducts, we also return in *qual and *indexqual the qual lists
    3318             :  * (in implicit-AND form, without RestrictInfos) describing the original index
    3319             :  * conditions and the generated indexqual conditions.  (These are the same in
    3320             :  * simple cases, but when special index operators are involved, the former
    3321             :  * list includes the special conditions while the latter includes the actual
    3322             :  * indexable conditions derived from them.)  Both lists include partial-index
    3323             :  * predicates, because we have to recheck predicates as well as index
    3324             :  * conditions if the bitmap scan becomes lossy.
    3325             :  *
    3326             :  * In addition, we return a list of EquivalenceClass pointers for all the
    3327             :  * top-level indexquals that were possibly-redundantly derived from ECs.
    3328             :  * This allows removal of scan_clauses that are redundant with such quals.
    3329             :  * (We do not attempt to detect such redundancies for quals that are within
    3330             :  * OR subtrees.  This could be done in a less hacky way if we returned the
    3331             :  * indexquals in RestrictInfo form, but that would be slower and still pretty
    3332             :  * messy, since we'd have to build new RestrictInfos in many cases.)
    3333             :  */
    3334             : static Plan *
    3335       21066 : create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
    3336             :                       List **qual, List **indexqual, List **indexECs)
    3337             : {
    3338             :     Plan       *plan;
    3339             : 
    3340       21066 :     if (IsA(bitmapqual, BitmapAndPath))
    3341             :     {
    3342         152 :         BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
    3343         152 :         List       *subplans = NIL;
    3344         152 :         List       *subquals = NIL;
    3345         152 :         List       *subindexquals = NIL;
    3346         152 :         List       *subindexECs = NIL;
    3347             :         ListCell   *l;
    3348             : 
    3349             :         /*
    3350             :          * There may well be redundant quals among the subplans, since a
    3351             :          * top-level WHERE qual might have gotten used to form several
    3352             :          * different index quals.  We don't try exceedingly hard to eliminate
    3353             :          * redundancies, but we do eliminate obvious duplicates by using
    3354             :          * list_concat_unique.
    3355             :          */
    3356         456 :         foreach(l, apath->bitmapquals)
    3357             :         {
    3358             :             Plan       *subplan;
    3359             :             List       *subqual;
    3360             :             List       *subindexqual;
    3361             :             List       *subindexEC;
    3362             : 
    3363         304 :             subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
    3364             :                                             &subqual, &subindexqual,
    3365             :                                             &subindexEC);
    3366         304 :             subplans = lappend(subplans, subplan);
    3367         304 :             subquals = list_concat_unique(subquals, subqual);
    3368         304 :             subindexquals = list_concat_unique(subindexquals, subindexqual);
    3369             :             /* Duplicates in indexECs aren't worth getting rid of */
    3370         304 :             subindexECs = list_concat(subindexECs, subindexEC);
    3371             :         }
    3372         152 :         plan = (Plan *) make_bitmap_and(subplans);
    3373         152 :         plan->startup_cost = apath->path.startup_cost;
    3374         152 :         plan->total_cost = apath->path.total_cost;
    3375         152 :         plan->plan_rows =
    3376         152 :             clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
    3377         152 :         plan->plan_width = 0;    /* meaningless */
    3378         152 :         plan->parallel_aware = false;
    3379         152 :         plan->parallel_safe = apath->path.parallel_safe;
    3380         152 :         *qual = subquals;
    3381         152 :         *indexqual = subindexquals;
    3382         152 :         *indexECs = subindexECs;
    3383             :     }
    3384       20914 :     else if (IsA(bitmapqual, BitmapOrPath))
    3385             :     {
    3386         300 :         BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
    3387         300 :         List       *subplans = NIL;
    3388         300 :         List       *subquals = NIL;
    3389         300 :         List       *subindexquals = NIL;
    3390         300 :         bool        const_true_subqual = false;
    3391         300 :         bool        const_true_subindexqual = false;
    3392             :         ListCell   *l;
    3393             : 
    3394             :         /*
    3395             :          * Here, we only detect qual-free subplans.  A qual-free subplan would
    3396             :          * cause us to generate "... OR true ..."  which we may as well reduce
    3397             :          * to just "true".  We do not try to eliminate redundant subclauses
    3398             :          * because (a) it's not as likely as in the AND case, and (b) we might
    3399             :          * well be working with hundreds or even thousands of OR conditions,
    3400             :          * perhaps from a long IN list.  The performance of list_append_unique
    3401             :          * would be unacceptable.
    3402             :          */
    3403         906 :         foreach(l, opath->bitmapquals)
    3404             :         {
    3405             :             Plan       *subplan;
    3406             :             List       *subqual;
    3407             :             List       *subindexqual;
    3408             :             List       *subindexEC;
    3409             : 
    3410         606 :             subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
    3411             :                                             &subqual, &subindexqual,
    3412             :                                             &subindexEC);
    3413         606 :             subplans = lappend(subplans, subplan);
    3414         606 :             if (subqual == NIL)
    3415           0 :                 const_true_subqual = true;
    3416         606 :             else if (!const_true_subqual)
    3417         606 :                 subquals = lappend(subquals,
    3418         606 :                                    make_ands_explicit(subqual));
    3419         606 :             if (subindexqual == NIL)
    3420           0 :                 const_true_subindexqual = true;
    3421         606 :             else if (!const_true_subindexqual)
    3422         606 :                 subindexquals = lappend(subindexquals,
    3423         606 :                                         make_ands_explicit(subindexqual));
    3424             :         }
    3425             : 
    3426             :         /*
    3427             :          * In the presence of ScalarArrayOpExpr quals, we might have built
    3428             :          * BitmapOrPaths with just one subpath; don't add an OR step.
    3429             :          */
    3430         300 :         if (list_length(subplans) == 1)
    3431             :         {
    3432           0 :             plan = (Plan *) linitial(subplans);
    3433             :         }
    3434             :         else
    3435             :         {
    3436         300 :             plan = (Plan *) make_bitmap_or(subplans);
    3437         300 :             plan->startup_cost = opath->path.startup_cost;
    3438         300 :             plan->total_cost = opath->path.total_cost;
    3439         300 :             plan->plan_rows =
    3440         300 :                 clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
    3441         300 :             plan->plan_width = 0;    /* meaningless */
    3442         300 :             plan->parallel_aware = false;
    3443         300 :             plan->parallel_safe = opath->path.parallel_safe;
    3444             :         }
    3445             : 
    3446             :         /*
    3447             :          * If there were constant-TRUE subquals, the OR reduces to constant
    3448             :          * TRUE.  Also, avoid generating one-element ORs, which could happen
    3449             :          * due to redundancy elimination or ScalarArrayOpExpr quals.
    3450             :          */
    3451         300 :         if (const_true_subqual)
    3452           0 :             *qual = NIL;
    3453         300 :         else if (list_length(subquals) <= 1)
    3454           0 :             *qual = subquals;
    3455             :         else
    3456         300 :             *qual = list_make1(make_orclause(subquals));
    3457         300 :         if (const_true_subindexqual)
    3458           0 :             *indexqual = NIL;
    3459         300 :         else if (list_length(subindexquals) <= 1)
    3460           0 :             *indexqual = subindexquals;
    3461             :         else
    3462         300 :             *indexqual = list_make1(make_orclause(subindexquals));
    3463         300 :         *indexECs = NIL;
    3464             :     }
    3465       20614 :     else if (IsA(bitmapqual, IndexPath))
    3466             :     {
    3467       20614 :         IndexPath  *ipath = (IndexPath *) bitmapqual;
    3468             :         IndexScan  *iscan;
    3469             :         List       *subquals;
    3470             :         List       *subindexquals;
    3471             :         List       *subindexECs;
    3472             :         ListCell   *l;
    3473             : 
    3474             :         /* Use the regular indexscan plan build machinery... */
    3475       20614 :         iscan = castNode(IndexScan,
    3476             :                          create_indexscan_plan(root, ipath,
    3477             :                                                NIL, NIL, false));
    3478             :         /* then convert to a bitmap indexscan */
    3479       20614 :         plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
    3480             :                                               iscan->indexid,
    3481             :                                               iscan->indexqual,
    3482             :                                               iscan->indexqualorig);
    3483             :         /* and set its cost/width fields appropriately */
    3484       20614 :         plan->startup_cost = 0.0;
    3485       20614 :         plan->total_cost = ipath->indextotalcost;
    3486       20614 :         plan->plan_rows =
    3487       20614 :             clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
    3488       20614 :         plan->plan_width = 0;    /* meaningless */
    3489       20614 :         plan->parallel_aware = false;
    3490       20614 :         plan->parallel_safe = ipath->path.parallel_safe;
    3491             :         /* Extract original index clauses, actual index quals, relevant ECs */
    3492       20614 :         subquals = NIL;
    3493       20614 :         subindexquals = NIL;
    3494       20614 :         subindexECs = NIL;
    3495       42424 :         foreach(l, ipath->indexclauses)
    3496             :         {
    3497       21810 :             IndexClause *iclause = (IndexClause *) lfirst(l);
    3498       21810 :             RestrictInfo *rinfo = iclause->rinfo;
    3499             : 
    3500             :             Assert(!rinfo->pseudoconstant);
    3501       21810 :             subquals = lappend(subquals, rinfo->clause);
    3502       21810 :             subindexquals = list_concat(subindexquals,
    3503       21810 :                                         get_actual_clauses(iclause->indexquals));
    3504       21810 :             if (rinfo->parent_ec)
    3505         592 :                 subindexECs = lappend(subindexECs, rinfo->parent_ec);
    3506             :         }
    3507             :         /* We can add any index predicate conditions, too */
    3508       20784 :         foreach(l, ipath->indexinfo->indpred)
    3509             :         {
    3510         170 :             Expr       *pred = (Expr *) lfirst(l);
    3511             : 
    3512             :             /*
    3513             :              * We know that the index predicate must have been implied by the
    3514             :              * query condition as a whole, but it may or may not be implied by
    3515             :              * the conditions that got pushed into the bitmapqual.  Avoid
    3516             :              * generating redundant conditions.
    3517             :              */
    3518         170 :             if (!predicate_implied_by(list_make1(pred), subquals, false))
    3519             :             {
    3520         140 :                 subquals = lappend(subquals, pred);
    3521         140 :                 subindexquals = lappend(subindexquals, pred);
    3522             :             }
    3523             :         }
    3524       20614 :         *qual = subquals;
    3525       20614 :         *indexqual = subindexquals;
    3526       20614 :         *indexECs = subindexECs;
    3527             :     }
    3528             :     else
    3529             :     {
    3530           0 :         elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
    3531             :         plan = NULL;            /* keep compiler quiet */
    3532             :     }
    3533             : 
    3534       21066 :     return plan;
    3535             : }
    3536             : 
    3537             : /*
    3538             :  * create_tidscan_plan
    3539             :  *   Returns a tidscan plan for the base relation scanned by 'best_path'
    3540             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3541             :  */
    3542             : static TidScan *
    3543         700 : create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
    3544             :                     List *tlist, List *scan_clauses)
    3545             : {
    3546             :     TidScan    *scan_plan;
    3547         700 :     Index       scan_relid = best_path->path.parent->relid;
    3548         700 :     List       *tidquals = best_path->tidquals;
    3549             : 
    3550             :     /* it should be a base rel... */
    3551             :     Assert(scan_relid > 0);
    3552             :     Assert(best_path->path.parent->rtekind == RTE_RELATION);
    3553             : 
    3554             :     /*
    3555             :      * The qpqual list must contain all restrictions not enforced by the
    3556             :      * tidquals list.  Since tidquals has OR semantics, we have to be careful
    3557             :      * about matching it up to scan_clauses.  It's convenient to handle the
    3558             :      * single-tidqual case separately from the multiple-tidqual case.  In the
    3559             :      * single-tidqual case, we look through the scan_clauses while they are
    3560             :      * still in RestrictInfo form, and drop any that are redundant with the
    3561             :      * tidqual.
    3562             :      *
    3563             :      * In normal cases simple pointer equality checks will be enough to spot
    3564             :      * duplicate RestrictInfos, so we try that first.
    3565             :      *
    3566             :      * Another common case is that a scan_clauses entry is generated from the
    3567             :      * same EquivalenceClass as some tidqual, and is therefore redundant with
    3568             :      * it, though not equal.
    3569             :      *
    3570             :      * Unlike indexpaths, we don't bother with predicate_implied_by(); the
    3571             :      * number of cases where it could win are pretty small.
    3572             :      */
    3573         700 :     if (list_length(tidquals) == 1)
    3574             :     {
    3575         676 :         List       *qpqual = NIL;
    3576             :         ListCell   *l;
    3577             : 
    3578        1436 :         foreach(l, scan_clauses)
    3579             :         {
    3580         760 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
    3581             : 
    3582         760 :             if (rinfo->pseudoconstant)
    3583           0 :                 continue;       /* we may drop pseudoconstants here */
    3584         760 :             if (list_member_ptr(tidquals, rinfo))
    3585         676 :                 continue;       /* simple duplicate */
    3586          84 :             if (is_redundant_derived_clause(rinfo, tidquals))
    3587           0 :                 continue;       /* derived from same EquivalenceClass */
    3588          84 :             qpqual = lappend(qpqual, rinfo);
    3589             :         }
    3590         676 :         scan_clauses = qpqual;
    3591             :     }
    3592             : 
    3593             :     /* Sort clauses into best execution order */
    3594         700 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3595             : 
    3596             :     /* Reduce RestrictInfo lists to bare expressions; ignore pseudoconstants */
    3597         700 :     tidquals = extract_actual_clauses(tidquals, false);
    3598         700 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3599             : 
    3600             :     /*
    3601             :      * If we have multiple tidquals, it's more convenient to remove duplicate
    3602             :      * scan_clauses after stripping the RestrictInfos.  In this situation,
    3603             :      * because the tidquals represent OR sub-clauses, they could not have come
    3604             :      * from EquivalenceClasses so we don't have to worry about matching up
    3605             :      * non-identical clauses.  On the other hand, because tidpath.c will have
    3606             :      * extracted those sub-clauses from some OR clause and built its own list,
    3607             :      * we will certainly not have pointer equality to any scan clause.  So
    3608             :      * convert the tidquals list to an explicit OR clause and see if we can
    3609             :      * match it via equal() to any scan clause.
    3610             :      */
    3611         700 :     if (list_length(tidquals) > 1)
    3612          24 :         scan_clauses = list_difference(scan_clauses,
    3613          24 :                                        list_make1(make_orclause(tidquals)));
    3614             : 
    3615             :     /* Replace any outer-relation variables with nestloop params */
    3616         700 :     if (best_path->path.param_info)
    3617             :     {
    3618             :         tidquals = (List *)
    3619          24 :             replace_nestloop_params(root, (Node *) tidquals);
    3620             :         scan_clauses = (List *)
    3621          24 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3622             :     }
    3623             : 
    3624         700 :     scan_plan = make_tidscan(tlist,
    3625             :                              scan_clauses,
    3626             :                              scan_relid,
    3627             :                              tidquals);
    3628             : 
    3629         700 :     copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
    3630             : 
    3631         700 :     return scan_plan;
    3632             : }
    3633             : 
    3634             : /*
    3635             :  * create_tidrangescan_plan
    3636             :  *   Returns a tidrangescan plan for the base relation scanned by 'best_path'
    3637             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3638             :  */
    3639             : static TidRangeScan *
    3640         202 : create_tidrangescan_plan(PlannerInfo *root, TidRangePath *best_path,
    3641             :                          List *tlist, List *scan_clauses)
    3642             : {
    3643             :     TidRangeScan *scan_plan;
    3644         202 :     Index       scan_relid = best_path->path.parent->relid;
    3645         202 :     List       *tidrangequals = best_path->tidrangequals;
    3646             : 
    3647             :     /* it should be a base rel... */
    3648             :     Assert(scan_relid > 0);
    3649             :     Assert(best_path->path.parent->rtekind == RTE_RELATION);
    3650             : 
    3651             :     /*
    3652             :      * The qpqual list must contain all restrictions not enforced by the
    3653             :      * tidrangequals list.  tidrangequals has AND semantics, so we can simply
    3654             :      * remove any qual that appears in it.
    3655             :      */
    3656             :     {
    3657         202 :         List       *qpqual = NIL;
    3658             :         ListCell   *l;
    3659             : 
    3660         434 :         foreach(l, scan_clauses)
    3661             :         {
    3662         232 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
    3663             : 
    3664         232 :             if (rinfo->pseudoconstant)
    3665           0 :                 continue;       /* we may drop pseudoconstants here */
    3666         232 :             if (list_member_ptr(tidrangequals, rinfo))
    3667         232 :                 continue;       /* simple duplicate */
    3668           0 :             qpqual = lappend(qpqual, rinfo);
    3669             :         }
    3670         202 :         scan_clauses = qpqual;
    3671             :     }
    3672             : 
    3673             :     /* Sort clauses into best execution order */
    3674         202 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3675             : 
    3676             :     /* Reduce RestrictInfo lists to bare expressions; ignore pseudoconstants */
    3677         202 :     tidrangequals = extract_actual_clauses(tidrangequals, false);
    3678         202 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3679             : 
    3680             :     /* Replace any outer-relation variables with nestloop params */
    3681         202 :     if (best_path->path.param_info)
    3682             :     {
    3683             :         tidrangequals = (List *)
    3684           0 :             replace_nestloop_params(root, (Node *) tidrangequals);
    3685             :         scan_clauses = (List *)
    3686           0 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3687             :     }
    3688             : 
    3689         202 :     scan_plan = make_tidrangescan(tlist,
    3690             :                                   scan_clauses,
    3691             :                                   scan_relid,
    3692             :                                   tidrangequals);
    3693             : 
    3694         202 :     copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
    3695             : 
    3696         202 :     return scan_plan;
    3697             : }
    3698             : 
    3699             : /*
    3700             :  * create_subqueryscan_plan
    3701             :  *   Returns a subqueryscan plan for the base relation scanned by 'best_path'
    3702             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3703             :  */
    3704             : static SubqueryScan *
    3705       22574 : create_subqueryscan_plan(PlannerInfo *root, SubqueryScanPath *best_path,
    3706             :                          List *tlist, List *scan_clauses)
    3707             : {
    3708             :     SubqueryScan *scan_plan;
    3709       22574 :     RelOptInfo *rel = best_path->path.parent;
    3710       22574 :     Index       scan_relid = rel->relid;
    3711             :     Plan       *subplan;
    3712             : 
    3713             :     /* it should be a subquery base rel... */
    3714             :     Assert(scan_relid > 0);
    3715             :     Assert(rel->rtekind == RTE_SUBQUERY);
    3716             : 
    3717             :     /*
    3718             :      * Recursively create Plan from Path for subquery.  Since we are entering
    3719             :      * a different planner context (subroot), recurse to create_plan not
    3720             :      * create_plan_recurse.
    3721             :      */
    3722       22574 :     subplan = create_plan(rel->subroot, best_path->subpath);
    3723             : 
    3724             :     /* Sort clauses into best execution order */
    3725       22574 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3726             : 
    3727             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3728       22574 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3729             : 
    3730             :     /*
    3731             :      * Replace any outer-relation variables with nestloop params.
    3732             :      *
    3733             :      * We must provide nestloop params for both lateral references of the
    3734             :      * subquery and outer vars in the scan_clauses.  It's better to assign the
    3735             :      * former first, because that code path requires specific param IDs, while
    3736             :      * replace_nestloop_params can adapt to the IDs assigned by
    3737             :      * process_subquery_nestloop_params.  This avoids possibly duplicating
    3738             :      * nestloop params when the same Var is needed for both reasons.
    3739             :      */
    3740       22574 :     if (best_path->path.param_info)
    3741             :     {
    3742         478 :         process_subquery_nestloop_params(root,
    3743             :                                          rel->subplan_params);
    3744             :         scan_clauses = (List *)
    3745         478 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3746             :     }
    3747             : 
    3748       22574 :     scan_plan = make_subqueryscan(tlist,
    3749             :                                   scan_clauses,
    3750             :                                   scan_relid,
    3751             :                                   subplan);
    3752             : 
    3753       22574 :     copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
    3754             : 
    3755       22574 :     return scan_plan;
    3756             : }
    3757             : 
    3758             : /*
    3759             :  * create_functionscan_plan
    3760             :  *   Returns a functionscan plan for the base relation scanned by 'best_path'
    3761             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3762             :  */
    3763             : static FunctionScan *
    3764       44176 : create_functionscan_plan(PlannerInfo *root, Path *best_path,
    3765             :                          List *tlist, List *scan_clauses)
    3766             : {
    3767             :     FunctionScan *scan_plan;
    3768       44176 :     Index       scan_relid = best_path->parent->relid;
    3769             :     RangeTblEntry *rte;
    3770             :     List       *functions;
    3771             : 
    3772             :     /* it should be a function base rel... */
    3773             :     Assert(scan_relid > 0);
    3774       44176 :     rte = planner_rt_fetch(scan_relid, root);
    3775             :     Assert(rte->rtekind == RTE_FUNCTION);
    3776       44176 :     functions = rte->functions;
    3777             : 
    3778             :     /* Sort clauses into best execution order */
    3779       44176 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3780             : 
    3781             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3782       44176 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3783             : 
    3784             :     /* Replace any outer-relation variables with nestloop params */
    3785       44176 :     if (best_path->param_info)
    3786             :     {
    3787             :         scan_clauses = (List *)
    3788        8498 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3789             :         /* The function expressions could contain nestloop params, too */
    3790        8498 :         functions = (List *) replace_nestloop_params(root, (Node *) functions);
    3791             :     }
    3792             : 
    3793       44176 :     scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
    3794       44176 :                                   functions, rte->funcordinality);
    3795             : 
    3796       44176 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    3797             : 
    3798       44176 :     return scan_plan;
    3799             : }
    3800             : 
    3801             : /*
    3802             :  * create_tablefuncscan_plan
    3803             :  *   Returns a tablefuncscan plan for the base relation scanned by 'best_path'
    3804             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3805             :  */
    3806             : static TableFuncScan *
    3807         626 : create_tablefuncscan_plan(PlannerInfo *root, Path *best_path,
    3808             :                           List *tlist, List *scan_clauses)
    3809             : {
    3810             :     TableFuncScan *scan_plan;
    3811         626 :     Index       scan_relid = best_path->parent->relid;
    3812             :     RangeTblEntry *rte;
    3813             :     TableFunc  *tablefunc;
    3814             : 
    3815             :     /* it should be a function base rel... */
    3816             :     Assert(scan_relid > 0);
    3817         626 :     rte = planner_rt_fetch(scan_relid, root);
    3818             :     Assert(rte->rtekind == RTE_TABLEFUNC);
    3819         626 :     tablefunc = rte->tablefunc;
    3820             : 
    3821             :     /* Sort clauses into best execution order */
    3822         626 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3823             : 
    3824             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3825         626 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3826             : 
    3827             :     /* Replace any outer-relation variables with nestloop params */
    3828         626 :     if (best_path->param_info)
    3829             :     {
    3830             :         scan_clauses = (List *)
    3831         234 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3832             :         /* The function expressions could contain nestloop params, too */
    3833         234 :         tablefunc = (TableFunc *) replace_nestloop_params(root, (Node *) tablefunc);
    3834             :     }
    3835             : 
    3836         626 :     scan_plan = make_tablefuncscan(tlist, scan_clauses, scan_relid,
    3837             :                                    tablefunc);
    3838             : 
    3839         626 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    3840             : 
    3841         626 :     return scan_plan;
    3842             : }
    3843             : 
    3844             : /*
    3845             :  * create_valuesscan_plan
    3846             :  *   Returns a valuesscan plan for the base relation scanned by 'best_path'
    3847             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3848             :  */
    3849             : static ValuesScan *
    3850        7980 : create_valuesscan_plan(PlannerInfo *root, Path *best_path,
    3851             :                        List *tlist, List *scan_clauses)
    3852             : {
    3853             :     ValuesScan *scan_plan;
    3854        7980 :     Index       scan_relid = best_path->parent->relid;
    3855             :     RangeTblEntry *rte;
    3856             :     List       *values_lists;
    3857             : 
    3858             :     /* it should be a values base rel... */
    3859             :     Assert(scan_relid > 0);
    3860        7980 :     rte = planner_rt_fetch(scan_relid, root);
    3861             :     Assert(rte->rtekind == RTE_VALUES);
    3862        7980 :     values_lists = rte->values_lists;
    3863             : 
    3864             :     /* Sort clauses into best execution order */
    3865        7980 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3866             : 
    3867             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3868        7980 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3869             : 
    3870             :     /* Replace any outer-relation variables with nestloop params */
    3871        7980 :     if (best_path->param_info)
    3872             :     {
    3873             :         scan_clauses = (List *)
    3874          48 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3875             :         /* The values lists could contain nestloop params, too */
    3876             :         values_lists = (List *)
    3877          48 :             replace_nestloop_params(root, (Node *) values_lists);
    3878             :     }
    3879             : 
    3880        7980 :     scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid,
    3881             :                                 values_lists);
    3882             : 
    3883        7980 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    3884             : 
    3885        7980 :     return scan_plan;
    3886             : }
    3887             : 
    3888             : /*
    3889             :  * create_ctescan_plan
    3890             :  *   Returns a ctescan plan for the base relation scanned by 'best_path'
    3891             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    3892             :  */
    3893             : static CteScan *
    3894        3186 : create_ctescan_plan(PlannerInfo *root, Path *best_path,
    3895             :                     List *tlist, List *scan_clauses)
    3896             : {
    3897             :     CteScan    *scan_plan;
    3898        3186 :     Index       scan_relid = best_path->parent->relid;
    3899             :     RangeTblEntry *rte;
    3900        3186 :     SubPlan    *ctesplan = NULL;
    3901             :     int         plan_id;
    3902             :     int         cte_param_id;
    3903             :     PlannerInfo *cteroot;
    3904             :     Index       levelsup;
    3905             :     int         ndx;
    3906             :     ListCell   *lc;
    3907             : 
    3908             :     Assert(scan_relid > 0);
    3909        3186 :     rte = planner_rt_fetch(scan_relid, root);
    3910             :     Assert(rte->rtekind == RTE_CTE);
    3911             :     Assert(!rte->self_reference);
    3912             : 
    3913             :     /*
    3914             :      * Find the referenced CTE, and locate the SubPlan previously made for it.
    3915             :      */
    3916        3186 :     levelsup = rte->ctelevelsup;
    3917        3186 :     cteroot = root;
    3918        5658 :     while (levelsup-- > 0)
    3919             :     {
    3920        2472 :         cteroot = cteroot->parent_root;
    3921        2472 :         if (!cteroot)           /* shouldn't happen */
    3922           0 :             elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
    3923             :     }
    3924             : 
    3925             :     /*
    3926             :      * Note: cte_plan_ids can be shorter than cteList, if we are still working
    3927             :      * on planning the CTEs (ie, this is a side-reference from another CTE).
    3928             :      * So we mustn't use forboth here.
    3929             :      */
    3930        3186 :     ndx = 0;
    3931        4602 :     foreach(lc, cteroot->parse->cteList)
    3932             :     {
    3933        4602 :         CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
    3934             : 
    3935        4602 :         if (strcmp(cte->ctename, rte->ctename) == 0)
    3936        3186 :             break;
    3937        1416 :         ndx++;
    3938             :     }
    3939        3186 :     if (lc == NULL)             /* shouldn't happen */
    3940           0 :         elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
    3941        3186 :     if (ndx >= list_length(cteroot->cte_plan_ids))
    3942           0 :         elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
    3943        3186 :     plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
    3944        3186 :     if (plan_id <= 0)
    3945           0 :         elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
    3946        3796 :     foreach(lc, cteroot->init_plans)
    3947             :     {
    3948        3796 :         ctesplan = (SubPlan *) lfirst(lc);
    3949        3796 :         if (ctesplan->plan_id == plan_id)
    3950        3186 :             break;
    3951             :     }
    3952        3186 :     if (lc == NULL)             /* shouldn't happen */
    3953           0 :         elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
    3954             : 
    3955             :     /*
    3956             :      * We need the CTE param ID, which is the sole member of the SubPlan's
    3957             :      * setParam list.
    3958             :      */
    3959        3186 :     cte_param_id = linitial_int(ctesplan->setParam);
    3960             : 
    3961             :     /* Sort clauses into best execution order */
    3962        3186 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    3963             : 
    3964             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    3965        3186 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    3966             : 
    3967             :     /* Replace any outer-relation variables with nestloop params */
    3968        3186 :     if (best_path->param_info)
    3969             :     {
    3970             :         scan_clauses = (List *)
    3971           0 :             replace_nestloop_params(root, (Node *) scan_clauses);
    3972             :     }
    3973             : 
    3974        3186 :     scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
    3975             :                              plan_id, cte_param_id);
    3976             : 
    3977        3186 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    3978             : 
    3979        3186 :     return scan_plan;
    3980             : }
    3981             : 
    3982             : /*
    3983             :  * create_namedtuplestorescan_plan
    3984             :  *   Returns a tuplestorescan plan for the base relation scanned by
    3985             :  *  'best_path' with restriction clauses 'scan_clauses' and targetlist
    3986             :  *  'tlist'.
    3987             :  */
    3988             : static NamedTuplestoreScan *
    3989         438 : create_namedtuplestorescan_plan(PlannerInfo *root, Path *best_path,
    3990             :                                 List *tlist, List *scan_clauses)
    3991             : {
    3992             :     NamedTuplestoreScan *scan_plan;
    3993         438 :     Index       scan_relid = best_path->parent->relid;
    3994             :     RangeTblEntry *rte;
    3995             : 
    3996             :     Assert(scan_relid > 0);
    3997         438 :     rte = planner_rt_fetch(scan_relid, root);
    3998             :     Assert(rte->rtekind == RTE_NAMEDTUPLESTORE);
    3999             : 
    4000             :     /* Sort clauses into best execution order */
    4001         438 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    4002             : 
    4003             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    4004         438 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    4005             : 
    4006             :     /* Replace any outer-relation variables with nestloop params */
    4007         438 :     if (best_path->param_info)
    4008             :     {
    4009             :         scan_clauses = (List *)
    4010           0 :             replace_nestloop_params(root, (Node *) scan_clauses);
    4011             :     }
    4012             : 
    4013         438 :     scan_plan = make_namedtuplestorescan(tlist, scan_clauses, scan_relid,
    4014             :                                          rte->enrname);
    4015             : 
    4016         438 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    4017             : 
    4018         438 :     return scan_plan;
    4019             : }
    4020             : 
    4021             : /*
    4022             :  * create_resultscan_plan
    4023             :  *   Returns a Result plan for the RTE_RESULT base relation scanned by
    4024             :  *  'best_path' with restriction clauses 'scan_clauses' and targetlist
    4025             :  *  'tlist'.
    4026             :  */
    4027             : static Result *
    4028        1458 : create_resultscan_plan(PlannerInfo *root, Path *best_path,
    4029             :                        List *tlist, List *scan_clauses)
    4030             : {
    4031             :     Result     *scan_plan;
    4032        1458 :     Index       scan_relid = best_path->parent->relid;
    4033             :     RangeTblEntry *rte PG_USED_FOR_ASSERTS_ONLY;
    4034             : 
    4035             :     Assert(scan_relid > 0);
    4036        1458 :     rte = planner_rt_fetch(scan_relid, root);
    4037             :     Assert(rte->rtekind == RTE_RESULT);
    4038             : 
    4039             :     /* Sort clauses into best execution order */
    4040        1458 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    4041             : 
    4042             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    4043        1458 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    4044             : 
    4045             :     /* Replace any outer-relation variables with nestloop params */
    4046        1458 :     if (best_path->param_info)
    4047             :     {
    4048             :         scan_clauses = (List *)
    4049         132 :             replace_nestloop_params(root, (Node *) scan_clauses);
    4050             :     }
    4051             : 
    4052        1458 :     scan_plan = make_result(tlist, (Node *) scan_clauses, NULL);
    4053             : 
    4054        1458 :     copy_generic_path_info(&scan_plan->plan, best_path);
    4055             : 
    4056        1458 :     return scan_plan;
    4057             : }
    4058             : 
    4059             : /*
    4060             :  * create_worktablescan_plan
    4061             :  *   Returns a worktablescan plan for the base relation scanned by 'best_path'
    4062             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    4063             :  */
    4064             : static WorkTableScan *
    4065         816 : create_worktablescan_plan(PlannerInfo *root, Path *best_path,
    4066             :                           List *tlist, List *scan_clauses)
    4067             : {
    4068             :     WorkTableScan *scan_plan;
    4069         816 :     Index       scan_relid = best_path->parent->relid;
    4070             :     RangeTblEntry *rte;
    4071             :     Index       levelsup;
    4072             :     PlannerInfo *cteroot;
    4073             : 
    4074             :     Assert(scan_relid > 0);
    4075         816 :     rte = planner_rt_fetch(scan_relid, root);
    4076             :     Assert(rte->rtekind == RTE_CTE);
    4077             :     Assert(rte->self_reference);
    4078             : 
    4079             :     /*
    4080             :      * We need to find the worktable param ID, which is in the plan level
    4081             :      * that's processing the recursive UNION, which is one level *below* where
    4082             :      * the CTE comes from.
    4083             :      */
    4084         816 :     levelsup = rte->ctelevelsup;
    4085         816 :     if (levelsup == 0)          /* shouldn't happen */
    4086           0 :         elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
    4087         816 :     levelsup--;
    4088         816 :     cteroot = root;
    4089        1852 :     while (levelsup-- > 0)
    4090             :     {
    4091        1036 :         cteroot = cteroot->parent_root;
    4092        1036 :         if (!cteroot)           /* shouldn't happen */
    4093           0 :             elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
    4094             :     }
    4095         816 :     if (cteroot->wt_param_id < 0) /* shouldn't happen */
    4096           0 :         elog(ERROR, "could not find param ID for CTE \"%s\"", rte->ctename);
    4097             : 
    4098             :     /* Sort clauses into best execution order */
    4099         816 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    4100             : 
    4101             :     /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
    4102         816 :     scan_clauses = extract_actual_clauses(scan_clauses, false);
    4103             : 
    4104             :     /* Replace any outer-relation variables with nestloop params */
    4105         816 :     if (best_path->param_info)
    4106             :     {
    4107             :         scan_clauses = (List *)
    4108           0 :             replace_nestloop_params(root, (Node *) scan_clauses);
    4109             :     }
    4110             : 
    4111         816 :     scan_plan = make_worktablescan(tlist, scan_clauses, scan_relid,
    4112             :                                    cteroot->wt_param_id);
    4113             : 
    4114         816 :     copy_generic_path_info(&scan_plan->scan.plan, best_path);
    4115             : 
    4116         816 :     return scan_plan;
    4117             : }
    4118             : 
    4119             : /*
    4120             :  * create_foreignscan_plan
    4121             :  *   Returns a foreignscan plan for the relation scanned by 'best_path'
    4122             :  *   with restriction clauses 'scan_clauses' and targetlist 'tlist'.
    4123             :  */
    4124             : static ForeignScan *
    4125        2024 : create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
    4126             :                         List *tlist, List *scan_clauses)
    4127             : {
    4128             :     ForeignScan *scan_plan;
    4129        2024 :     RelOptInfo *rel = best_path->path.parent;
    4130        2024 :     Index       scan_relid = rel->relid;
    4131        2024 :     Oid         rel_oid = InvalidOid;
    4132        2024 :     Plan       *outer_plan = NULL;
    4133             : 
    4134             :     Assert(rel->fdwroutine != NULL);
    4135             : 
    4136             :     /* transform the child path if any */
    4137        2024 :     if (best_path->fdw_outerpath)
    4138          44 :         outer_plan = create_plan_recurse(root, best_path->fdw_outerpath,
    4139             :                                          CP_EXACT_TLIST);
    4140             : 
    4141             :     /*
    4142             :      * If we're scanning a base relation, fetch its OID.  (Irrelevant if
    4143             :      * scanning a join relation.)
    4144             :      */
    4145        2024 :     if (scan_relid > 0)
    4146             :     {
    4147             :         RangeTblEntry *rte;
    4148             : 
    4149             :         Assert(rel->rtekind == RTE_RELATION);
    4150        1472 :         rte = planner_rt_fetch(scan_relid, root);
    4151             :         Assert(rte->rtekind == RTE_RELATION);
    4152        1472 :         rel_oid = rte->relid;
    4153             :     }
    4154             : 
    4155             :     /*
    4156             :      * Sort clauses into best execution order.  We do this first since the FDW
    4157             :      * might have more info than we do and wish to adjust the ordering.
    4158             :      */
    4159        2024 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    4160             : 
    4161             :     /*
    4162             :      * Let the FDW perform its processing on the restriction clauses and
    4163             :      * generate the plan node.  Note that the FDW might remove restriction
    4164             :      * clauses that it intends to execute remotely, or even add more (if it
    4165             :      * has selected some join clauses for remote use but also wants them
    4166             :      * rechecked locally).
    4167             :      */
    4168        2024 :     scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid,
    4169             :                                                 best_path,
    4170             :                                                 tlist, scan_clauses,
    4171             :                                                 outer_plan);
    4172             : 
    4173             :     /* Copy cost data from Path to Plan; no need to make FDW do this */
    4174        2024 :     copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
    4175             : 
    4176             :     /* Copy user OID to access as; likewise no need to make FDW do this */
    4177        2024 :     scan_plan->checkAsUser = rel->userid;
    4178             : 
    4179             :     /* Copy foreign server OID; likewise, no need to make FDW do this */
    4180        2024 :     scan_plan->fs_server = rel->serverid;
    4181             : 
    4182             :     /*
    4183             :      * Likewise, copy the relids that are represented by this foreign scan. An
    4184             :      * upper rel doesn't have relids set, but it covers all the relations
    4185             :      * participating in the underlying scan/join, so use root->all_query_rels.
    4186             :      */
    4187        2024 :     if (rel->reloptkind == RELOPT_UPPER_REL)
    4188         238 :         scan_plan->fs_relids = root->all_query_rels;
    4189             :     else
    4190        1786 :         scan_plan->fs_relids = best_path->path.parent->relids;
    4191             : 
    4192             :     /*
    4193             :      * Join relid sets include relevant outer joins, but FDWs may need to know
    4194             :      * which are the included base rels.  That's a bit tedious to get without
    4195             :      * access to the plan-time data structures, so compute it here.
    4196             :      */
    4197        4048 :     scan_plan->fs_base_relids = bms_difference(scan_plan->fs_relids,
    4198        2024 :                                                root->outer_join_rels);
    4199             : 
    4200             :     /*
    4201             :      * If this is a foreign join, and to make it valid to push down we had to
    4202             :      * assume that the current user is the same as some user explicitly named
    4203             :      * in the query, mark the finished plan as depending on the current user.
    4204             :      */
    4205        2024 :     if (rel->useridiscurrent)
    4206           4 :         root->glob->dependsOnRole = true;
    4207             : 
    4208             :     /*
    4209             :      * Replace any outer-relation variables with nestloop params in the qual,
    4210             :      * fdw_exprs and fdw_recheck_quals expressions.  We do this last so that
    4211             :      * the FDW doesn't have to be involved.  (Note that parts of fdw_exprs or
    4212             :      * fdw_recheck_quals could have come from join clauses, so doing this
    4213             :      * beforehand on the scan_clauses wouldn't work.)  We assume
    4214             :      * fdw_scan_tlist contains no such variables.
    4215             :      */
    4216        2024 :     if (best_path->path.param_info)
    4217             :     {
    4218          26 :         scan_plan->scan.plan.qual = (List *)
    4219          26 :             replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
    4220          26 :         scan_plan->fdw_exprs = (List *)
    4221          26 :             replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
    4222          26 :         scan_plan->fdw_recheck_quals = (List *)
    4223          26 :             replace_nestloop_params(root,
    4224          26 :                                     (Node *) scan_plan->fdw_recheck_quals);
    4225             :     }
    4226             : 
    4227             :     /*
    4228             :      * If rel is a base relation, detect whether any system columns are
    4229             :      * requested from the rel.  (If rel is a join relation, rel->relid will be
    4230             :      * 0, but there can be no Var with relid 0 in the rel's targetlist or the
    4231             :      * restriction clauses, so we skip this in that case.  Note that any such
    4232             :      * columns in base relations that were joined are assumed to be contained
    4233             :      * in fdw_scan_tlist.)  This is a bit of a kluge and might go away
    4234             :      * someday, so we intentionally leave it out of the API presented to FDWs.
    4235             :      */
    4236        2024 :     scan_plan->fsSystemCol = false;
    4237        2024 :     if (scan_relid > 0)
    4238             :     {
    4239        1472 :         Bitmapset  *attrs_used = NULL;
    4240             :         ListCell   *lc;
    4241             :         int         i;
    4242             : 
    4243             :         /*
    4244             :          * First, examine all the attributes needed for joins or final output.
    4245             :          * Note: we must look at rel's targetlist, not the attr_needed data,
    4246             :          * because attr_needed isn't computed for inheritance child rels.
    4247             :          */
    4248        1472 :         pull_varattnos((Node *) rel->reltarget->exprs, scan_relid, &attrs_used);
    4249             : 
    4250             :         /* Add all the attributes used by restriction clauses. */
    4251        2168 :         foreach(lc, rel->baserestrictinfo)
    4252             :         {
    4253         696 :             RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
    4254             : 
    4255         696 :             pull_varattnos((Node *) rinfo->clause, scan_relid, &attrs_used);
    4256             :         }
    4257             : 
    4258             :         /* Now, are any system columns requested from rel? */
    4259        8358 :         for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
    4260             :         {
    4261        7412 :             if (bms_is_member(i - FirstLowInvalidHeapAttributeNumber, attrs_used))
    4262             :             {
    4263         526 :                 scan_plan->fsSystemCol = true;
    4264         526 :                 break;
    4265             :             }
    4266             :         }
    4267             : 
    4268        1472 :         bms_free(attrs_used);
    4269             :     }
    4270             : 
    4271        2024 :     return scan_plan;
    4272             : }
    4273             : 
    4274             : /*
    4275             :  * create_customscan_plan
    4276             :  *
    4277             :  * Transform a CustomPath into a Plan.
    4278             :  */
    4279             : static CustomScan *
    4280           0 : create_customscan_plan(PlannerInfo *root, CustomPath *best_path,
    4281             :                        List *tlist, List *scan_clauses)
    4282             : {
    4283             :     CustomScan *cplan;
    4284           0 :     RelOptInfo *rel = best_path->path.parent;
    4285           0 :     List       *custom_plans = NIL;
    4286             :     ListCell   *lc;
    4287             : 
    4288             :     /* Recursively transform child paths. */
    4289           0 :     foreach(lc, best_path->custom_paths)
    4290             :     {
    4291           0 :         Plan       *plan = create_plan_recurse(root, (Path *) lfirst(lc),
    4292             :                                                CP_EXACT_TLIST);
    4293             : 
    4294           0 :         custom_plans = lappend(custom_plans, plan);
    4295             :     }
    4296             : 
    4297             :     /*
    4298             :      * Sort clauses into the best execution order, although custom-scan
    4299             :      * provider can reorder them again.
    4300             :      */
    4301           0 :     scan_clauses = order_qual_clauses(root, scan_clauses);
    4302             : 
    4303             :     /*
    4304             :      * Invoke custom plan provider to create the Plan node represented by the
    4305             :      * CustomPath.
    4306             :      */
    4307           0 :     cplan = castNode(CustomScan,
    4308             :                      best_path->methods->PlanCustomPath(root,
    4309             :                                                         rel,
    4310             :                                                         best_path,
    4311             :                                                         tlist,
    4312             :                                                         scan_clauses,
    4313             :                                                         custom_plans));
    4314             : 
    4315             :     /*
    4316             :      * Copy cost data from Path to Plan; no need to make custom-plan providers
    4317             :      * do this
    4318             :      */
    4319           0 :     copy_generic_path_info(&cplan->scan.plan, &best_path->path);
    4320             : 
    4321             :     /* Likewise, copy the relids that are represented by this custom scan */
    4322           0 :     cplan->custom_relids = best_path->path.parent->relids;
    4323             : 
    4324             :     /*
    4325             :      * Replace any outer-relation variables with nestloop params in the qual
    4326             :      * and custom_exprs expressions.  We do this last so that the custom-plan
    4327             :      * provider doesn't have to be involved.  (Note that parts of custom_exprs
    4328             :      * could have come from join clauses, so doing this beforehand on the
    4329             :      * scan_clauses wouldn't work.)  We assume custom_scan_tlist contains no
    4330             :      * such variables.
    4331             :      */
    4332           0 :     if (best_path->path.param_info)
    4333             :     {
    4334           0 :         cplan->scan.plan.qual = (List *)
    4335           0 :             replace_nestloop_params(root, (Node *) cplan->scan.plan.qual);
    4336           0 :         cplan->custom_exprs = (List *)
    4337           0 :             replace_nestloop_params(root, (Node *) cplan->custom_exprs);
    4338             :     }
    4339             : 
    4340           0 :     return cplan;
    4341             : }
    4342             : 
    4343             : 
    4344             : /*****************************************************************************
    4345             :  *
    4346             :  *  JOIN METHODS
    4347             :  *
    4348             :  *****************************************************************************/
    4349             : 
    4350             : static NestLoop *
    4351       83802 : create_nestloop_plan(PlannerInfo *root,
    4352             :                      NestPath *best_path)
    4353             : {
    4354             :     NestLoop   *join_plan;
    4355             :     Plan       *outer_plan;
    4356             :     Plan       *inner_plan;
    4357       83802 :     List       *tlist = build_path_tlist(root, &best_path->jpath.path);
    4358       83802 :     List       *joinrestrictclauses = best_path->jpath.joinrestrictinfo;
    4359             :     List       *joinclauses;
    4360             :     List       *otherclauses;
    4361             :     Relids      outerrelids;
    4362             :     List       *nestParams;
    4363       83802 :     Relids      saveOuterRels = root->curOuterRels;
    4364             : 
    4365             :     /*
    4366             :      * If the inner path is parameterized by the topmost parent of the outer
    4367             :      * rel rather than the outer rel itself, fix that.  (Nothing happens here
    4368             :      * if it is not so parameterized.)
    4369             :      */
    4370       83802 :     best_path->jpath.innerjoinpath =
    4371       83802 :         reparameterize_path_by_child(root,
    4372             :                                      best_path->jpath.innerjoinpath,
    4373       83802 :                                      best_path->jpath.outerjoinpath->parent);
    4374             : 
    4375             :     /*
    4376             :      * Failure here probably means that reparameterize_path_by_child() is not
    4377             :      * in sync with path_is_reparameterizable_by_child().
    4378             :      */
    4379             :     Assert(best_path->jpath.innerjoinpath != NULL);
    4380             : 
    4381             :     /* NestLoop can project, so no need to be picky about child tlists */
    4382       83802 :     outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath, 0);
    4383             : 
    4384             :     /* For a nestloop, include outer relids in curOuterRels for inner side */
    4385      167604 :     root->curOuterRels = bms_union(root->curOuterRels,
    4386       83802 :                                    best_path->jpath.outerjoinpath->parent->relids);
    4387             : 
    4388       83802 :     inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath, 0);
    4389             : 
    4390             :     /* Restore curOuterRels */
    4391       83802 :     bms_free(root->curOuterRels);
    4392       83802 :     root->curOuterRels = saveOuterRels;
    4393             : 
    4394             :     /* Sort join qual clauses into best execution order */
    4395       83802 :     joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
    4396             : 
    4397             :     /* Get the join qual clauses (in plain expression form) */
    4398             :     /* Any pseudoconstant clauses are ignored here */
    4399       83802 :     if (IS_OUTER_JOIN(best_path->jpath.jointype))
    4400             :     {
    4401       20342 :         extract_actual_join_clauses(joinrestrictclauses,
    4402       20342 :                                     best_path->jpath.path.parent->relids,
    4403             :                                     &joinclauses, &otherclauses);
    4404             :     }
    4405             :     else
    4406             :     {
    4407             :         /* We can treat all clauses alike for an inner join */
    4408       63460 :         joinclauses = extract_actual_clauses(joinrestrictclauses, false);
    4409       63460 :         otherclauses = NIL;
    4410             :     }
    4411             : 
    4412             :     /* Replace any outer-relation variables with nestloop params */
    4413       83802 :     if (best_path->jpath.path.param_info)
    4414             :     {
    4415         814 :         joinclauses = (List *)
    4416         814 :             replace_nestloop_params(root, (Node *) joinclauses);
    4417         814 :         otherclauses = (List *)
    4418         814 :             replace_nestloop_params(root, (Node *) otherclauses);
    4419             :     }
    4420             : 
    4421             :     /*
    4422             :      * Identify any nestloop parameters that should be supplied by this join
    4423             :      * node, and remove them from root->curOuterParams.
    4424             :      */
    4425       83802 :     outerrelids = best_path->jpath.outerjoinpath->parent->relids;
    4426       83802 :     nestParams = identify_current_nestloop_params(root, outerrelids);
    4427             : 
    4428       83802 :     join_plan = make_nestloop(tlist,
    4429             :                               joinclauses,
    4430             :                               otherclauses,
    4431             :                               nestParams,
    4432             :                               outer_plan,
    4433             :                               inner_plan,
    4434             :                               best_path->jpath.jointype,
    4435       83802 :                               best_path->jpath.inner_unique);
    4436             : 
    4437       83802 :     copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
    4438             : 
    4439       83802 :     return join_plan;
    4440             : }
    4441             : 
    4442             : static MergeJoin *
    4443        7094 : create_mergejoin_plan(PlannerInfo *root,
    4444             :                       MergePath *best_path)
    4445             : {
    4446             :     MergeJoin  *join_plan;
    4447             :     Plan       *outer_plan;
    4448             :     Plan       *inner_plan;
    4449        7094 :     List       *tlist = build_path_tlist(root, &best_path->jpath.path);
    4450             :     List       *joinclauses;
    4451             :     List       *otherclauses;
    4452             :     List       *mergeclauses;
    4453             :     List       *outerpathkeys;
    4454             :     List       *innerpathkeys;
    4455             :     int         nClauses;
    4456             :     Oid        *mergefamilies;
    4457             :     Oid        *mergecollations;
    4458             :     bool       *mergereversals;
    4459             :     bool       *mergenullsfirst;
    4460             :     PathKey    *opathkey;
    4461             :     EquivalenceClass *opeclass;
    4462             :     int         i;
    4463             :     ListCell   *lc;
    4464             :     ListCell   *lop;
    4465             :     ListCell   *lip;
    4466        7094 :     Path       *outer_path = best_path->jpath.outerjoinpath;
    4467        7094 :     Path       *inner_path = best_path->jpath.innerjoinpath;
    4468             : 
    4469             :     /*
    4470             :      * MergeJoin can project, so we don't have to demand exact tlists from the
    4471             :      * inputs.  However, if we're intending to sort an input's result, it's
    4472             :      * best to request a small tlist so we aren't sorting more data than
    4473             :      * necessary.
    4474             :      */
    4475        7094 :     outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
    4476        7094 :                                      (best_path->outersortkeys != NIL) ? CP_SMALL_TLIST : 0);
    4477             : 
    4478        7094 :     inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
    4479        7094 :                                      (best_path->innersortkeys != NIL) ? CP_SMALL_TLIST : 0);
    4480             : 
    4481             :     /* Sort join qual clauses into best execution order */
    4482             :     /* NB: do NOT reorder the mergeclauses */
    4483        7094 :     joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
    4484             : 
    4485             :     /* Get the join qual clauses (in plain expression form) */
    4486             :     /* Any pseudoconstant clauses are ignored here */
    4487        7094 :     if (IS_OUTER_JOIN(best_path->jpath.jointype))
    4488             :     {
    4489        4890 :         extract_actual_join_clauses(joinclauses,
    4490        4890 :                                     best_path->jpath.path.parent->relids,
    4491             :                                     &joinclauses, &otherclauses);
    4492             :     }
    4493             :     else
    4494             :     {
    4495             :         /* We can treat all clauses alike for an inner join */
    4496        2204 :         joinclauses = extract_actual_clauses(joinclauses, false);
    4497        2204 :         otherclauses = NIL;
    4498             :     }
    4499             : 
    4500             :     /*
    4501             :      * Remove the mergeclauses from the list of join qual clauses, leaving the
    4502             :      * list of quals that must be checked as qpquals.
    4503             :      */
    4504        7094 :     mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
    4505        7094 :     joinclauses = list_difference(joinclauses, mergeclauses);
    4506             : 
    4507             :     /*
    4508             :      * Replace any outer-relation variables with nestloop params.  There
    4509             :      * should not be any in the mergeclauses.
    4510             :      */
    4511        7094 :     if (best_path->jpath.path.param_info)
    4512             :     {
    4513           6 :         joinclauses = (List *)
    4514           6 :             replace_nestloop_params(root, (Node *) joinclauses);
    4515           6 :         otherclauses = (List *)
    4516           6 :             replace_nestloop_params(root, (Node *) otherclauses);
    4517             :     }
    4518             : 
    4519             :     /*
    4520             :      * Rearrange mergeclauses, if needed, so that the outer variable is always
    4521             :      * on the left; mark the mergeclause restrictinfos with correct
    4522             :      * outer_is_left status.
    4523             :      */
    4524        7094 :     mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
    4525        7094 :                                         best_path->jpath.outerjoinpath->parent->relids);
    4526             : 
    4527             :     /*
    4528             :      * Create explicit sort nodes for the outer and inner paths if necessary.
    4529             :      */
    4530        7094 :     if (best_path->outersortkeys)
    4531             :     {
    4532        2828 :         Relids      outer_relids = outer_path->parent->relids;
    4533             :         Plan       *sort_plan;
    4534        2828 :         bool        use_incremental_sort = false;
    4535             :         int         presorted_keys;
    4536             : 
    4537             :         /*
    4538             :          * We choose to use incremental sort if it is enabled and there are
    4539             :          * presorted keys; otherwise we use full sort.
    4540             :          */
    4541        2828 :         if (enable_incremental_sort)
    4542             :         {
    4543             :             bool        is_sorted PG_USED_FOR_ASSERTS_ONLY;
    4544             : 
    4545        2828 :             is_sorted = pathkeys_count_contained_in(best_path->outersortkeys,
    4546             :                                                     outer_path->pathkeys,
    4547             :                                                     &presorted_keys);
    4548             :             Assert(!is_sorted);
    4549             : 
    4550        2828 :             if (presorted_keys > 0)
    4551          12 :                 use_incremental_sort = true;
    4552             :         }
    4553             : 
    4554        2828 :         if (!use_incremental_sort)
    4555             :         {
    4556             :             sort_plan = (Plan *)
    4557        2816 :                 make_sort_from_pathkeys(outer_plan,
    4558             :                                         best_path->outersortkeys,
    4559             :                                         outer_relids);
    4560             : 
    4561        2816 :             label_sort_with_costsize(root, (Sort *) sort_plan, -1.0);
    4562             :         }
    4563             :         else
    4564             :         {
    4565             :             sort_plan = (Plan *)
    4566          12 :                 make_incrementalsort_from_pathkeys(outer_plan,
    4567             :                                                    best_path->outersortkeys,
    4568             :                                                    outer_relids,
    4569             :                                                    presorted_keys);
    4570             : 
    4571          12 :             label_incrementalsort_with_costsize(root,
    4572             :                                                 (IncrementalSort *) sort_plan,
    4573             :                                                 best_path->outersortkeys,
    4574             :                                                 -1.0);
    4575             :         }
    4576             : 
    4577        2828 :         outer_plan = sort_plan;
    4578        2828 :         outerpathkeys = best_path->outersortkeys;
    4579             :     }
    4580             :     else
    4581        4266 :         outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
    4582             : 
    4583        7094 :     if (best_path->innersortkeys)
    4584             :     {
    4585             :         /*
    4586             :          * We do not consider incremental sort for inner path, because
    4587             :          * incremental sort does not support mark/restore.
    4588             :          */
    4589             : 
    4590        6574 :         Relids      inner_relids = inner_path->parent->relids;
    4591        6574 :         Sort       *sort = make_sort_from_pathkeys(inner_plan,
    4592             :                                                    best_path->innersortkeys,
    4593             :                                                    inner_relids);
    4594             : 
    4595        6574 :         label_sort_with_costsize(root, sort, -1.0);
    4596        6574 :         inner_plan = (Plan *) sort;
    4597        6574 :         innerpathkeys = best_path->innersortkeys;
    4598             :     }
    4599             :     else
    4600         520 :         innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
    4601             : 
    4602             :     /*
    4603             :      * If specified, add a materialize node to shield the inner plan from the
    4604             :      * need to handle mark/restore.
    4605             :      */
    4606        7094 :     if (best_path->materialize_inner)
    4607             :     {
    4608         152 :         Plan       *matplan = (Plan *) make_material(inner_plan);
    4609             : 
    4610             :         /*
    4611             :          * We assume the materialize will not spill to disk, and therefore
    4612             :          * charge just cpu_operator_cost per tuple.  (Keep this estimate in
    4613             :          * sync with final_cost_mergejoin.)
    4614             :          */
    4615         152 :         copy_plan_costsize(matplan, inner_plan);
    4616         152 :         matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
    4617             : 
    4618         152 :         inner_plan = matplan;
    4619             :     }
    4620             : 
    4621             :     /*
    4622             :      * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
    4623             :      * executor.  The information is in the pathkeys for the two inputs, but
    4624             :      * we need to be careful about the possibility of mergeclauses sharing a
    4625             :      * pathkey, as well as the possibility that the inner pathkeys are not in
    4626             :      * an order matching the mergeclauses.
    4627             :      */
    4628        7094 :     nClauses = list_length(mergeclauses);
    4629             :     Assert(nClauses == list_length(best_path->path_mergeclauses));
    4630        7094 :     mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
    4631        7094 :     mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
    4632        7094 :     mergereversals = (bool *) palloc(nClauses * sizeof(bool));
    4633        7094 :     mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
    4634             : 
    4635        7094 :     opathkey = NULL;
    4636        7094 :     opeclass = NULL;
    4637        7094 :     lop = list_head(outerpathkeys);
    4638        7094 :     lip = list_head(innerpathkeys);
    4639        7094 :     i = 0;
    4640       14950 :     foreach(lc, best_path->path_mergeclauses)
    4641             :     {
    4642        7856 :         RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
    4643             :         EquivalenceClass *oeclass;
    4644             :         EquivalenceClass *ieclass;
    4645        7856 :         PathKey    *ipathkey = NULL;
    4646        7856 :         EquivalenceClass *ipeclass = NULL;
    4647        7856 :         bool        first_inner_match = false;
    4648             : 
    4649             :         /* fetch outer/inner eclass from mergeclause */
    4650        7856 :         if (rinfo->outer_is_left)
    4651             :         {
    4652        6314 :             oeclass = rinfo->left_ec;
    4653        6314 :             ieclass = rinfo->right_ec;
    4654             :         }
    4655             :         else
    4656             :         {
    4657        1542 :             oeclass = rinfo->right_ec;
    4658        1542 :             ieclass = rinfo->left_ec;
    4659             :         }
    4660             :         Assert(oeclass != NULL);
    4661             :         Assert(ieclass != NULL);
    4662             : 
    4663             :         /*
    4664             :          * We must identify the pathkey elements associated with this clause
    4665             :          * by matching the eclasses (which should give a unique match, since
    4666             :          * the pathkey lists should be canonical).  In typical cases the merge
    4667             :          * clauses are one-to-one with the pathkeys, but when dealing with
    4668             :          * partially redundant query conditions, things are more complicated.
    4669             :          *
    4670             :          * lop and lip reference the first as-yet-unmatched pathkey elements.
    4671             :          * If they're NULL then all pathkey elements have been matched.
    4672             :          *
    4673             :          * The ordering of the outer pathkeys should match the mergeclauses,
    4674             :          * by construction (see find_mergeclauses_for_outer_pathkeys()). There
    4675             :          * could be more than one mergeclause for the same outer pathkey, but
    4676             :          * no pathkey may be entirely skipped over.
    4677             :          */
    4678        7856 :         if (oeclass != opeclass)    /* multiple matches are not interesting */
    4679             :         {
    4680             :             /* doesn't match the current opathkey, so must match the next */
    4681        7844 :             if (lop == NULL)
    4682           0 :                 elog(ERROR, "outer pathkeys do not match mergeclauses");
    4683        7844 :             opathkey = (PathKey *) lfirst(lop);
    4684        7844 :             opeclass = opathkey->pk_eclass;
    4685        7844 :             lop = lnext(outerpathkeys, lop);
    4686        7844 :             if (oeclass != opeclass)
    4687           0 :                 elog(ERROR, "outer pathkeys do not match mergeclauses");
    4688             :         }
    4689             : 
    4690             :         /*
    4691             :          * The inner pathkeys likewise should not have skipped-over keys, but
    4692             :          * it's possible for a mergeclause to reference some earlier inner
    4693             :          * pathkey if we had redundant pathkeys.  For example we might have
    4694             :          * mergeclauses like "o.a = i.x AND o.b = i.y AND o.c = i.x".  The
    4695             :          * implied inner ordering is then "ORDER BY x, y, x", but the pathkey
    4696             :          * mechanism drops the second sort by x as redundant, and this code
    4697             :          * must cope.
    4698             :          *
    4699             :          * It's also possible for the implied inner-rel ordering to be like
    4700             :          * "ORDER BY x, y, x DESC".  We still drop the second instance of x as
    4701             :          * redundant; but this means that the sort ordering of a redundant
    4702             :          * inner pathkey should not be considered significant.  So we must
    4703             :          * detect whether this is the first clause matching an inner pathkey.
    4704             :          */
    4705        7856 :         if (lip)
    4706             :         {
    4707        7838 :             ipathkey = (PathKey *) lfirst(lip);
    4708        7838 :             ipeclass = ipathkey->pk_eclass;
    4709        7838 :             if (ieclass == ipeclass)
    4710             :             {
    4711             :                 /* successful first match to this inner pathkey */
    4712        7838 :                 lip = lnext(innerpathkeys, lip);
    4713        7838 :                 first_inner_match = true;
    4714             :             }
    4715             :         }
    4716        7856 :         if (!first_inner_match)
    4717             :         {
    4718             :             /* redundant clause ... must match something before lip */
    4719             :             ListCell   *l2;
    4720             : 
    4721          18 :             foreach(l2, innerpathkeys)
    4722             :             {
    4723          18 :                 if (l2 == lip)
    4724           0 :                     break;
    4725          18 :                 ipathkey = (PathKey *) lfirst(l2);
    4726          18 :                 ipeclass = ipathkey->pk_eclass;
    4727          18 :                 if (ieclass == ipeclass)
    4728          18 :                     break;
    4729             :             }
    4730          18 :             if (ieclass != ipeclass)
    4731           0 :                 elog(ERROR, "inner pathkeys do not match mergeclauses");
    4732             :         }
    4733             : 
    4734             :         /*
    4735             :          * The pathkeys should always match each other as to opfamily and
    4736             :          * collation (which affect equality), but if we're considering a
    4737             :          * redundant inner pathkey, its sort ordering might not match.  In
    4738             :          * such cases we may ignore the inner pathkey's sort ordering and use
    4739             :          * the outer's.  (In effect, we're lying to the executor about the
    4740             :          * sort direction of this inner column, but it does not matter since
    4741             :          * the run-time row comparisons would only reach this column when
    4742             :          * there's equality for the earlier column containing the same eclass.
    4743             :          * There could be only one value in this column for the range of inner
    4744             :          * rows having a given value in the earlier column, so it does not
    4745             :          * matter which way we imagine this column to be ordered.)  But a
    4746             :          * non-redundant inner pathkey had better match outer's ordering too.
    4747             :          */
    4748        7856 :         if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
    4749        7856 :             opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation)
    4750           0 :             elog(ERROR, "left and right pathkeys do not match in mergejoin");
    4751        7856 :         if (first_inner_match &&
    4752        7838 :             (opathkey->pk_strategy != ipathkey->pk_strategy ||
    4753        7838 :              opathkey->pk_nulls_first != ipathkey->pk_nulls_first))
    4754           0 :             elog(ERROR, "left and right pathkeys do not match in mergejoin");
    4755             : 
    4756             :         /* OK, save info for executor */
    4757        7856 :         mergefamilies[i] = opathkey->pk_opfamily;
    4758        7856 :         mergecollations[i] = opathkey->pk_eclass->ec_collation;
    4759        7856 :         mergereversals[i] = (opathkey->pk_strategy == BTGreaterStrategyNumber ? true : false);
    4760        7856 :         mergenullsfirst[i] = opathkey->pk_nulls_first;
    4761        7856 :         i++;
    4762             :     }
    4763             : 
    4764             :     /*
    4765             :      * Note: it is not an error if we have additional pathkey elements (i.e.,
    4766             :      * lop or lip isn't NULL here).  The input paths might be better-sorted
    4767             :      * than we need for the current mergejoin.
    4768             :      */
    4769             : 
    4770             :     /*
    4771             :      * Now we can build the mergejoin node.
    4772             :      */
    4773        7094 :     join_plan = make_mergejoin(tlist,
    4774             :                                joinclauses,
    4775             :                                otherclauses,
    4776             :                                mergeclauses,
    4777             :                                mergefamilies,
    4778             :                                mergecollations,
    4779             :                                mergereversals,
    4780             :                                mergenullsfirst,
    4781             :                                outer_plan,
    4782             :                                inner_plan,
    4783             :                                best_path->jpath.jointype,
    4784        7094 :                                best_path->jpath.inner_unique,
    4785        7094 :                                best_path->skip_mark_restore);
    4786             : 
    4787             :     /* Costs of sort and material steps are included in path cost already */
    4788        7094 :     copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
    4789             : 
    4790        7094 :     return join_plan;
    4791             : }
    4792             : 
    4793             : static HashJoin *
    4794       28878 : create_hashjoin_plan(PlannerInfo *root,
    4795             :                      HashPath *best_path)
    4796             : {
    4797             :     HashJoin   *join_plan;
    4798             :     Hash       *hash_plan;
    4799             :     Plan       *outer_plan;
    4800             :     Plan       *inner_plan;
    4801       28878 :     List       *tlist = build_path_tlist(root, &best_path->jpath.path);
    4802             :     List       *joinclauses;
    4803             :     List       *otherclauses;
    4804             :     List       *hashclauses;
    4805       28878 :     List       *hashoperators = NIL;
    4806       28878 :     List       *hashcollations = NIL;
    4807       28878 :     List       *inner_hashkeys = NIL;
    4808       28878 :     List       *outer_hashkeys = NIL;
    4809       28878 :     Oid         skewTable = InvalidOid;
    4810       28878 :     AttrNumber  skewColumn = InvalidAttrNumber;
    4811       28878 :     bool        skewInherit = false;
    4812             :     ListCell   *lc;
    4813             : 
    4814             :     /*
    4815             :      * HashJoin can project, so we don't have to demand exact tlists from the
    4816             :      * inputs.  However, it's best to request a small tlist from the inner
    4817             :      * side, so that we aren't storing more data than necessary.  Likewise, if
    4818             :      * we anticipate batching, request a small tlist from the outer side so
    4819             :      * that we don't put extra data in the outer batch files.
    4820             :      */
    4821       28878 :     outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
    4822       28878 :                                      (best_path->num_batches > 1) ? CP_SMALL_TLIST : 0);
    4823             : 
    4824       28878 :     inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
    4825             :                                      CP_SMALL_TLIST);
    4826             : 
    4827             :     /* Sort join qual clauses into best execution order */
    4828       28878 :     joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
    4829             :     /* There's no point in sorting the hash clauses ... */
    4830             : 
    4831             :     /* Get the join qual clauses (in plain expression form) */
    4832             :     /* Any pseudoconstant clauses are ignored here */
    4833       28878 :     if (IS_OUTER_JOIN(best_path->jpath.jointype))
    4834             :     {
    4835       10000 :         extract_actual_join_clauses(joinclauses,
    4836       10000 :                                     best_path->jpath.path.parent->relids,
    4837             :                                     &joinclauses, &otherclauses);
    4838             :     }
    4839             :     else
    4840             :     {
    4841             :         /* We can treat all clauses alike for an inner join */
    4842       18878 :         joinclauses = extract_actual_clauses(joinclauses, false);
    4843       18878 :         otherclauses = NIL;
    4844             :     }
    4845             : 
    4846             :     /*
    4847             :      * Remove the hashclauses from the list of join qual clauses, leaving the
    4848             :      * list of quals that must be checked as qpquals.
    4849             :      */
    4850       28878 :     hashclauses = get_actual_clauses(best_path->path_hashclauses);
    4851       28878 :     joinclauses = list_difference(joinclauses, hashclauses);
    4852             : 
    4853             :     /*
    4854             :      * Replace any outer-relation variables with nestloop params.  There
    4855             :      * should not be any in the hashclauses.
    4856             :      */
    4857       28878 :     if (best_path->jpath.path.param_info)
    4858             :     {
    4859         164 :         joinclauses = (List *)
    4860         164 :             replace_nestloop_params(root, (Node *) joinclauses);
    4861         164 :         otherclauses = (List *)
    4862         164 :             replace_nestloop_params(root, (Node *) otherclauses);
    4863             :     }
    4864             : 
    4865             :     /*
    4866             :      * Rearrange hashclauses, if needed, so that the outer variable is always
    4867             :      * on the left.
    4868             :      */
    4869       28878 :     hashclauses = get_switched_clauses(best_path->path_hashclauses,
    4870       28878 :                                        best_path->jpath.outerjoinpath->parent->relids);
    4871             : 
    4872             :     /*
    4873             :      * If there is a single join clause and we can identify the outer variable
    4874             :      * as a simple column reference, supply its identity for possible use in
    4875             :      * skew optimization.  (Note: in principle we could do skew optimization
    4876             :      * with multiple join clauses, but we'd have to be able to determine the
    4877             :      * most common combinations of outer values, which we don't currently have
    4878             :      * enough stats for.)
    4879             :      */
    4880       28878 :     if (list_length(hashclauses) == 1)
    4881             :     {
    4882       26554 :         OpExpr     *clause = (OpExpr *) linitial(hashclauses);
    4883             :         Node       *node;
    4884             : 
    4885             :         Assert(is_opclause(clause));
    4886       26554 :         node = (Node *) linitial(clause->args);
    4887       26554 :         if (IsA(node, RelabelType))
    4888         610 :             node = (Node *) ((RelabelType *) node)->arg;
    4889       26554 :         if (IsA(node, Var))
    4890             :         {
    4891       22860 :             Var        *var = (Var *) node;
    4892             :             RangeTblEntry *rte;
    4893             : 
    4894       22860 :             rte = root->simple_rte_array[var->varno];
    4895       22860 :             if (rte->rtekind == RTE_RELATION)
    4896             :             {
    4897       20250 :                 skewTable = rte->relid;
    4898       20250 :                 skewColumn = var->varattno;
    4899       20250 :                 skewInherit = rte->inh;
    4900             :             }
    4901             :         }
    4902             :     }
    4903             : 
    4904             :     /*
    4905             :      * Collect hash related information. The hashed expressions are
    4906             :      * deconstructed into outer/inner expressions, so they can be computed
    4907             :      * separately (inner expressions are used to build the hashtable via Hash,
    4908             :      * outer expressions to perform lookups of tuples from HashJoin's outer
    4909             :      * plan in the hashtable). Also collect operator information necessary to
    4910             :      * build the hashtable.
    4911             :      */
    4912       60182 :     foreach(lc, hashclauses)
    4913             :     {
    4914       31304 :         OpExpr     *hclause = lfirst_node(OpExpr, lc);
    4915             : 
    4916       31304 :         hashoperators = lappend_oid(hashoperators, hclause->opno);
    4917       31304 :         hashcollations = lappend_oid(hashcollations, hclause->inputcollid);
    4918       31304 :         outer_hashkeys = lappend(outer_hashkeys, linitial(hclause->args));
    4919       31304 :         inner_hashkeys = lappend(inner_hashkeys, lsecond(hclause->args));
    4920             :     }
    4921             : 
    4922             :     /*
    4923             :      * Build the hash node and hash join node.
    4924             :      */
    4925       28878 :     hash_plan = make_hash(inner_plan,
    4926             :                           inner_hashkeys,
    4927             :                           skewTable,
    4928             :                           skewColumn,
    4929             :                           skewInherit);
    4930             : 
    4931             :     /*
    4932             :      * Set Hash node's startup & total costs equal to total cost of input
    4933             :      * plan; this only affects EXPLAIN display not decisions.
    4934             :      */
    4935       28878 :     copy_plan_costsize(&hash_plan->plan, inner_plan);
    4936       28878 :     hash_plan->plan.startup_cost = hash_plan->plan.total_cost;
    4937             : 
    4938             :     /*
    4939             :      * If parallel-aware, the executor will also need an estimate of the total
    4940             :      * number of rows expected from all participants so that it can size the
    4941             :      * shared hash table.
    4942             :      */
    4943       28878 :     if (best_path->jpath.path.parallel_aware)
    4944             :     {
    4945         186 :         hash_plan->plan.parallel_aware = true;
    4946         186 :         hash_plan->rows_total = best_path->inner_rows_total;
    4947             :     }
    4948             : 
    4949       28878 :     join_plan = make_hashjoin(tlist,
    4950             :                               joinclauses,
    4951             :                               otherclauses,
    4952             :                               hashclauses,
    4953             :                               hashoperators,
    4954             :                               hashcollations,
    4955             :                               outer_hashkeys,
    4956             :                               outer_plan,
    4957             :                               (Plan *) hash_plan,
    4958             :                               best_path->jpath.jointype,
    4959       28878 :                               best_path->jpath.inner_unique);
    4960             : 
    4961       28878 :     copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
    4962             : 
    4963       28878 :     return join_plan;
    4964             : }
    4965             : 
    4966             : 
    4967             : /*****************************************************************************
    4968             :  *
    4969             :  *  SUPPORTING ROUTINES
    4970             :  *
    4971             :  *****************************************************************************/
    4972             : 
    4973             : /*
    4974             :  * replace_nestloop_params
    4975             :  *    Replace outer-relation Vars and PlaceHolderVars in the given expression
    4976             :  *    with nestloop Params
    4977             :  *
    4978             :  * All Vars and PlaceHolderVars belonging to the relation(s) identified by
    4979             :  * root->curOuterRels are replaced by Params, and entries are added to
    4980             :  * root->curOuterParams if not already present.
    4981             :  */
    4982             : static Node *
    4983      317290 : replace_nestloop_params(PlannerInfo *root, Node *expr)
    4984             : {
    4985             :     /* No setup needed for tree walk, so away we go */
    4986      317290 :     return replace_nestloop_params_mutator(expr, root);
    4987             : }
    4988             : 
    4989             : static Node *
    4990     1188758 : replace_nestloop_params_mutator(Node *node, PlannerInfo *root)
    4991             : {
    4992     1188758 :     if (node == NULL)
    4993       77284 :         return NULL;
    4994     1111474 :     if (IsA(node, Var))
    4995             :     {
    4996      330388 :         Var        *var = (Var *) node;
    4997             : 
    4998             :         /* Upper-level Vars should be long gone at this point */
    4999             :         Assert(var->varlevelsup == 0);
    5000             :         /* If not to be replaced, we can just return the Var unmodified */
    5001      330388 :         if (IS_SPECIAL_VARNO(var->varno) ||
    5002      330376 :             !bms_is_member(var->varno, root->curOuterRels))
    5003      246948 :             return node;
    5004             :         /* Replace the Var with a nestloop Param */
    5005       83440 :         return (Node *) replace_nestloop_param_var(root, var);
    5006             :     }
    5007      781086 :     if (IsA(node, PlaceHolderVar))
    5008             :     {
    5009         832 :         PlaceHolderVar *phv = (PlaceHolderVar *) node;
    5010             : 
    5011             :         /* Upper-level PlaceHolderVars should be long gone at this point */
    5012             :         Assert(phv->phlevelsup == 0);
    5013             : 
    5014             :         /* Check whether we need to replace the PHV */
    5015         832 :         if (!bms_is_subset(find_placeholder_info(root, phv)->ph_eval_at,
    5016         832 :                            root->curOuterRels))
    5017             :         {
    5018             :             /*
    5019             :              * We can't replace the whole PHV, but we might still need to
    5020             :              * replace Vars or PHVs within its expression, in case it ends up
    5021             :              * actually getting evaluated here.  (It might get evaluated in
    5022             :              * this plan node, or some child node; in the latter case we don't
    5023             :              * really need to process the expression here, but we haven't got
    5024             :              * enough info to tell if that's the case.)  Flat-copy the PHV
    5025             :              * node and then recurse on its expression.
    5026             :              *
    5027             :              * Note that after doing this, we might have different
    5028             :              * representations of the contents of the same PHV in different
    5029             :              * parts of the plan tree.  This is OK because equal() will just
    5030             :              * match on phid/phlevelsup, so setrefs.c will still recognize an
    5031             :              * upper-level reference to a lower-level copy of the same PHV.
    5032             :              */
    5033         574 :             PlaceHolderVar *newphv = makeNode(PlaceHolderVar);
    5034             : 
    5035         574 :             memcpy(newphv, phv, sizeof(PlaceHolderVar));
    5036         574 :             newphv->phexpr = (Expr *)
    5037         574 :                 replace_nestloop_params_mutator((Node *) phv->phexpr,
    5038             :                                                 root);
    5039         574 :             return (Node *) newphv;
    5040             :         }
    5041             :         /* Replace the PlaceHolderVar with a nestloop Param */
    5042         258 :         return (Node *) replace_nestloop_param_placeholdervar(root, phv);
    5043             :     }
    5044      780254 :     return expression_tree_mutator(node, replace_nestloop_params_mutator, root);
    5045             : }
    5046             : 
    5047             : /*
    5048             :  * fix_indexqual_references
    5049             :  *    Adjust indexqual clauses to the form the executor's indexqual
    5050             :  *    machinery needs.
    5051             :  *
    5052             :  * We have three tasks here:
    5053             :  *  * Select the actual qual clauses out of the input IndexClause list,
    5054             :  *    and remove RestrictInfo nodes from the qual clauses.
    5055             :  *  * Replace any outer-relation Var or PHV nodes with nestloop Params.
    5056             :  *    (XXX eventually, that responsibility should go elsewhere?)
    5057             :  *  * Index keys must be represented by Var nodes with varattno set to the
    5058             :  *    index's attribute number, not the attribute number in the original rel.
    5059             :  *
    5060             :  * *stripped_indexquals_p receives a list of the actual qual clauses.
    5061             :  *
    5062             :  * *fixed_indexquals_p receives a list of the adjusted quals.  This is a copy
    5063             :  * that shares no substructure with the original; this is needed in case there
    5064             :  * are subplans in it (we need two separate copies of the subplan tree, or
    5065             :  * things will go awry).
    5066             :  */
    5067             : static void
    5068      166364 : fix_indexqual_references(PlannerInfo *root, IndexPath *index_path,
    5069             :                          List **stripped_indexquals_p, List **fixed_indexquals_p)
    5070             : {
    5071      166364 :     IndexOptInfo *index = index_path->indexinfo;
    5072             :     List       *stripped_indexquals;
    5073             :     List       *fixed_indexquals;
    5074             :     ListCell   *lc;
    5075             : 
    5076      166364 :     stripped_indexquals = fixed_indexquals = NIL;
    5077             : 
    5078      345064 :     foreach(lc, index_path->indexclauses)
    5079             :     {
    5080      178700 :         IndexClause *iclause = lfirst_node(IndexClause, lc);
    5081      178700 :         int         indexcol = iclause->indexcol;
    5082             :         ListCell   *lc2;
    5083             : 
    5084      358444 :         foreach(lc2, iclause->indexquals)
    5085             :         {
    5086      179744 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc2);
    5087      179744 :             Node       *clause = (Node *) rinfo->clause;
    5088             : 
    5089      179744 :             stripped_indexquals = lappend(stripped_indexquals, clause);
    5090      179744 :             clause = fix_indexqual_clause(root, index, indexcol,
    5091             :                                           clause, iclause->indexcols);
    5092      179744 :             fixed_indexquals = lappend(fixed_indexquals, clause);
    5093             :         }
    5094             :     }
    5095             : 
    5096      166364 :     *stripped_indexquals_p = stripped_indexquals;
    5097      166364 :     *fixed_indexquals_p = fixed_indexquals;
    5098      166364 : }
    5099             : 
    5100             : /*
    5101             :  * fix_indexorderby_references
    5102             :  *    Adjust indexorderby clauses to the form the executor's index
    5103             :  *    machinery needs.
    5104             :  *
    5105             :  * This is a simplified version of fix_indexqual_references.  The input is
    5106             :  * bare clauses and a separate indexcol list, instead of IndexClauses.
    5107             :  */
    5108             : static List *
    5109      166364 : fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path)
    5110             : {
    5111      166364 :     IndexOptInfo *index = index_path->indexinfo;
    5112             :     List       *fixed_indexorderbys;
    5113             :     ListCell   *lcc,
    5114             :                *lci;
    5115             : 
    5116      166364 :     fixed_indexorderbys = NIL;
    5117             : 
    5118      166750 :     forboth(lcc, index_path->indexorderbys, lci, index_path->indexorderbycols)
    5119             :     {
    5120         386 :         Node       *clause = (Node *) lfirst(lcc);
    5121         386 :         int         indexcol = lfirst_int(lci);
    5122             : 
    5123         386 :         clause = fix_indexqual_clause(root, index, indexcol, clause, NIL);
    5124         386 :         fixed_indexorderbys = lappend(fixed_indexorderbys, clause);
    5125             :     }
    5126             : 
    5127      166364 :     return fixed_indexorderbys;
    5128             : }
    5129             : 
    5130             : /*
    5131             :  * fix_indexqual_clause
    5132             :  *    Convert a single indexqual clause to the form needed by the executor.
    5133             :  *
    5134             :  * We replace nestloop params here, and replace the index key variables
    5135             :  * or expressions by index Var nodes.
    5136             :  */
    5137             : static Node *
    5138      180130 : fix_indexqual_clause(PlannerInfo *root, IndexOptInfo *index, int indexcol,
    5139             :                      Node *clause, List *indexcolnos)
    5140             : {
    5141             :     /*
    5142             :      * Replace any outer-relation variables with nestloop params.
    5143             :      *
    5144             :      * This also makes a copy of the clause, so it's safe to modify it
    5145             :      * in-place below.
    5146             :      */
    5147      180130 :     clause = replace_nestloop_params(root, clause);
    5148             : 
    5149      180130 :     if (IsA(clause, OpExpr))
    5150             :     {
    5151      177516 :         OpExpr     *op = (OpExpr *) clause;
    5152             : 
    5153             :         /* Replace the indexkey expression with an index Var. */
    5154      177516 :         linitial(op->args) = fix_indexqual_operand(linitial(op->args),
    5155             :                                                    index,
    5156             :                                                    indexcol);
    5157             :     }
    5158        2614 :     else if (IsA(clause, RowCompareExpr))
    5159             :     {
    5160         132 :         RowCompareExpr *rc = (RowCompareExpr *) clause;
    5161             :         ListCell   *lca,
    5162             :                    *lcai;
    5163             : 
    5164             :         /* Replace the indexkey expressions with index Vars. */
    5165             :         Assert(list_length(rc->largs) == list_length(indexcolnos));
    5166         396 :         forboth(lca, rc->largs, lcai, indexcolnos)
    5167             :         {
    5168         264 :             lfirst(lca) = fix_indexqual_operand(lfirst(lca),
    5169             :                                                 index,
    5170             :                                                 lfirst_int(lcai));
    5171             :         }
    5172             :     }
    5173        2482 :     else if (IsA(clause, ScalarArrayOpExpr))
    5174             :     {
    5175        1624 :         ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
    5176             : 
    5177             :         /* Replace the indexkey expression with an index Var. */
    5178        1624 :         linitial(saop->args) = fix_indexqual_operand(linitial(saop->args),
    5179             :                                                      index,
    5180             :                                                      indexcol);
    5181             :     }
    5182         858 :     else if (IsA(clause, NullTest))
    5183             :     {
    5184         858 :         NullTest   *nt = (NullTest *) clause;
    5185             : 
    5186             :         /* Replace the indexkey expression with an index Var. */
    5187         858 :         nt->arg = (Expr *) fix_indexqual_operand((Node *) nt->arg,
    5188             :                                                  index,
    5189             :                                                  indexcol);
    5190             :     }
    5191             :     else
    5192           0 :         elog(ERROR, "unsupported indexqual type: %d",
    5193             :              (int) nodeTag(clause));
    5194             : 
    5195      180130 :     return clause;
    5196             : }
    5197             : 
    5198             : /*
    5199             :  * fix_indexqual_operand
    5200             :  *    Convert an indexqual expression to a Var referencing the index column.
    5201             :  *
    5202             :  * We represent index keys by Var nodes having varno == INDEX_VAR and varattno
    5203             :  * equal to the index's attribute number (index column position).
    5204             :  *
    5205             :  * Most of the code here is just for sanity cross-checking that the given
    5206             :  * expression actually matches the index column it's claimed to.
    5207             :  */
    5208             : static Node *
    5209      180262 : fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol)
    5210             : {
    5211             :     Var        *result;
    5212             :     int         pos;
    5213             :     ListCell   *indexpr_item;
    5214             : 
    5215             :     /*
    5216             :      * Remove any binary-compatible relabeling of the indexkey
    5217             :      */
    5218      180262 :     if (IsA(node, RelabelType))
    5219         626 :         node = (Node *) ((RelabelType *) node)->arg;
    5220             : 
    5221             :     Assert(indexcol >= 0 && indexcol < index->ncolumns);
    5222             : 
    5223      180262 :     if (index->indexkeys[indexcol] != 0)
    5224             :     {
    5225             :         /* It's a simple index column */
    5226      179898 :         if (IsA(node, Var) &&
    5227      179898 :             ((Var *) node)->varno == index->rel->relid &&
    5228      179898 :             ((Var *) node)->varattno == index->indexkeys[indexcol])
    5229             :         {
    5230      179898 :             result = (Var *) copyObject(node);
    5231      179898 :             result->varno = INDEX_VAR;
    5232      179898 :             result->varattno = indexcol + 1;
    5233      179898 :             return (Node *) result;
    5234             :         }
    5235             :         else
    5236           0 :             elog(ERROR, "index key does not match expected index column");
    5237             :     }
    5238             : 
    5239             :     /* It's an index expression, so find and cross-check the expression */
    5240         364 :     indexpr_item = list_head(index->indexprs);
    5241         364 :     for (pos = 0; pos < index->ncolumns; pos++)
    5242             :     {
    5243         364 :         if (index->indexkeys[pos] == 0)
    5244             :         {
    5245         364 :             if (indexpr_item == NULL)
    5246           0 :                 elog(ERROR, "too few entries in indexprs list");
    5247         364 :             if (pos == indexcol)
    5248             :             {
    5249             :                 Node       *indexkey;
    5250             : 
    5251         364 :                 indexkey = (Node *) lfirst(indexpr_item);
    5252         364 :                 if (indexkey && IsA(indexkey, RelabelType))
    5253          10 :                     indexkey = (Node *) ((RelabelType *) indexkey)->arg;
    5254         364 :                 if (equal(node, indexkey))
    5255             :                 {
    5256         364 :                     result = makeVar(INDEX_VAR, indexcol + 1,
    5257         364 :                                      exprType(lfirst(indexpr_item)), -1,
    5258         364 :                                      exprCollation(lfirst(indexpr_item)),
    5259             :                                      0);
    5260         364 :                     return (Node *) result;
    5261             :                 }
    5262             :                 else
    5263           0 :                     elog(ERROR, "index key does not match expected index column");
    5264             :             }
    5265           0 :             indexpr_item = lnext(index->indexprs, indexpr_item);
    5266             :         }
    5267             :     }
    5268             : 
    5269             :     /* Oops... */
    5270           0 :     elog(ERROR, "index key does not match expected index column");
    5271             :     return NULL;                /* keep compiler quiet */
    5272             : }
    5273             : 
    5274             : /*
    5275             :  * get_switched_clauses
    5276             :  *    Given a list of merge or hash joinclauses (as RestrictInfo nodes),
    5277             :  *    extract the bare clauses, and rearrange the elements within the
    5278             :  *    clauses, if needed, so the outer join variable is on the left and
    5279             :  *    the inner is on the right.  The original clause data structure is not
    5280             :  *    touched; a modified list is returned.  We do, however, set the transient
    5281             :  *    outer_is_left field in each RestrictInfo to show which side was which.
    5282             :  */
    5283             : static List *
    5284       35972 : get_switched_clauses(List *clauses, Relids outerrelids)
    5285             : {
    5286       35972 :     List       *t_list = NIL;
    5287             :     ListCell   *l;
    5288             : 
    5289       75132 :     foreach(l, clauses)
    5290             :     {
    5291       39160 :         RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
    5292       39160 :         OpExpr     *clause = (OpExpr *) restrictinfo->clause;
    5293             : 
    5294             :         Assert(is_opclause(clause));
    5295       39160 :         if (bms_is_subset(restrictinfo->right_relids, outerrelids))
    5296             :         {
    5297             :             /*
    5298             :              * Duplicate just enough of the structure to allow commuting the
    5299             :              * clause without changing the original list.  Could use
    5300             :              * copyObject, but a complete deep copy is overkill.
    5301             :              */
    5302       16734 :             OpExpr     *temp = makeNode(OpExpr);
    5303             : 
    5304       16734 :             temp->opno = clause->opno;
    5305       16734 :             temp->opfuncid = InvalidOid;
    5306       16734 :             temp->opresulttype = clause->opresulttype;
    5307       16734 :             temp->opretset = clause->opretset;
    5308       16734 :             temp->opcollid = clause->opcollid;
    5309       16734 :             temp->inputcollid = clause->inputcollid;
    5310       16734 :             temp->args = list_copy(clause->args);
    5311       16734 :             temp->location = clause->location;
    5312             :             /* Commute it --- note this modifies the temp node in-place. */
    5313       16734 :             CommuteOpExpr(temp);
    5314       16734 :             t_list = lappend(t_list, temp);
    5315       16734 :             restrictinfo->outer_is_left = false;
    5316             :         }
    5317             :         else
    5318             :         {
    5319             :             Assert(bms_is_subset(restrictinfo->left_relids, outerrelids));
    5320       22426 :             t_list = lappend(t_list, clause);
    5321       22426 :             restrictinfo->outer_is_left = true;
    5322             :         }
    5323             :     }
    5324       35972 :     return t_list;
    5325             : }
    5326             : 
    5327             : /*
    5328             :  * order_qual_clauses
    5329             :  *      Given a list of qual clauses that will all be evaluated at the same
    5330             :  *      plan node, sort the list into the order we want to check the quals
    5331             :  *      in at runtime.
    5332             :  *
    5333             :  * When security barrier quals are used in the query, we may have quals with
    5334             :  * different security levels in the list.  Quals of lower security_level
    5335             :  * must go before quals of higher security_level, except that we can grant
    5336             :  * exceptions to move up quals that are leakproof.  When security level
    5337             :  * doesn't force the decision, we prefer to order clauses by estimated
    5338             :  * execution cost, cheapest first.
    5339             :  *
    5340             :  * Ideally the order should be driven by a combination of execution cost and
    5341             :  * selectivity, but it's not immediately clear how to account for both,
    5342             :  * and given the uncertainty of the estimates the reliability of the decisions
    5343             :  * would be doubtful anyway.  So we just order by security level then
    5344             :  * estimated per-tuple cost, being careful not to change the order when
    5345             :  * (as is often the case) the estimates are identical.
    5346             :  *
    5347             :  * Although this will work on either bare clauses or RestrictInfos, it's
    5348             :  * much faster to apply it to RestrictInfos, since it can re-use cost
    5349             :  * information that is cached in RestrictInfos.  XXX in the bare-clause
    5350             :  * case, we are also not able to apply security considerations.  That is
    5351             :  * all right for the moment, because the bare-clause case doesn't occur
    5352             :  * anywhere that barrier quals could be present, but it would be better to
    5353             :  * get rid of it.
    5354             :  *
    5355             :  * Note: some callers pass lists that contain entries that will later be
    5356             :  * removed; this is the easiest way to let this routine see RestrictInfos
    5357             :  * instead of bare clauses.  This is another reason why trying to consider
    5358             :  * selectivity in the ordering would likely do the wrong thing.
    5359             :  */
    5360             : static List *
    5361      852764 : order_qual_clauses(PlannerInfo *root, List *clauses)
    5362             : {
    5363             :     typedef struct
    5364             :     {
    5365             :         Node       *clause;
    5366             :         Cost        cost;
    5367             :         Index       security_level;
    5368             :     } QualItem;
    5369      852764 :     int         nitems = list_length(clauses);
    5370             :     QualItem   *items;
    5371             :     ListCell   *lc;
    5372             :     int         i;
    5373             :     List       *result;
    5374             : 
    5375             :     /* No need to work hard for 0 or 1 clause */
    5376      852764 :     if (nitems <= 1)
    5377      791144 :         return clauses;
    5378             : 
    5379             :     /*
    5380             :      * Collect the items and costs into an array.  This is to avoid repeated
    5381             :      * cost_qual_eval work if the inputs aren't RestrictInfos.
    5382             :      */
    5383       61620 :     items = (QualItem *) palloc(nitems * sizeof(QualItem));
    5384       61620 :     i = 0;
    5385      207866 :     foreach(lc, clauses)
    5386             :     {
    5387      146246 :         Node       *clause = (Node *) lfirst(lc);
    5388             :         QualCost    qcost;
    5389             : 
    5390      146246 :         cost_qual_eval_node(&qcost, clause, root);
    5391      146246 :         items[i].clause = clause;
    5392      146246 :         items[i].cost = qcost.per_tuple;
    5393      146246 :         if (IsA(clause, RestrictInfo))
    5394             :         {
    5395      146154 :             RestrictInfo *rinfo = (RestrictInfo *) clause;
    5396             : 
    5397             :             /*
    5398             :              * If a clause is leakproof, it doesn't have to be constrained by
    5399             :              * its nominal security level.  If it's also reasonably cheap
    5400             :              * (here defined as 10X cpu_operator_cost), pretend it has
    5401             :              * security_level 0, which will allow it to go in front of
    5402             :              * more-expensive quals of lower security levels.  Of course, that
    5403             :              * will also force it to go in front of cheaper quals of its own
    5404             :              * security level, which is not so great, but we can alleviate
    5405             :              * that risk by applying the cost limit cutoff.
    5406             :              */
    5407      146154 :             if (rinfo->leakproof && items[i].cost < 10 * cpu_operator_cost)
    5408        1164 :                 items[i].security_level = 0;
    5409             :             else
    5410      144990 :                 items[i].security_level = rinfo->security_level;
    5411             :         }
    5412             :         else
    5413          92 :             items[i].security_level = 0;
    5414      146246 :         i++;
    5415             :     }
    5416             : 
    5417             :     /*
    5418             :      * Sort.  We don't use qsort() because it's not guaranteed stable for
    5419             :      * equal keys.  The expected number of entries is small enough that a
    5420             :      * simple insertion sort should be good enough.
    5421             :      */
    5422      146246 :     for (i = 1; i < nitems; i++)
    5423             :     {
    5424       84626 :         QualItem    newitem = items[i];
    5425             :         int         j;
    5426             : 
    5427             :         /* insert newitem into the already-sorted subarray */
    5428       93972 :         for (j = i; j > 0; j--)
    5429             :         {
    5430       86738 :             QualItem   *olditem = &items[j - 1];
    5431             : 
    5432       86738 :             if (newitem.security_level > olditem->security_level ||
    5433       86018 :                 (newitem.security_level == olditem->security_level &&
    5434       84630 :                  newitem.cost >= olditem->cost))
    5435             :                 break;
    5436        9346 :             items[j] = *olditem;
    5437             :         }
    5438       84626 :         items[j] = newitem;
    5439             :     }
    5440             : 
    5441             :     /* Convert back to a list */
    5442       61620 :     result = NIL;
    5443      207866 :     for (i = 0; i < nitems; i++)
    5444      146246 :         result = lappend(result, items[i].clause);
    5445             : 
    5446       61620 :     return result;
    5447             : }
    5448             : 
    5449             : /*
    5450             :  * Copy cost and size info from a Path node to the Plan node created from it.
    5451             :  * The executor usually won't use this info, but it's needed by EXPLAIN.
    5452             :  * Also copy the parallel-related flags, which the executor *will* use.
    5453             :  */
    5454             : static void
    5455     1043106 : copy_generic_path_info(Plan *dest, Path *src)
    5456             : {
    5457     1043106 :     dest->disabled_nodes = src->disabled_nodes;
    5458     1043106 :     dest->startup_cost = src->startup_cost;
    5459     1043106 :     dest->total_cost = src->total_cost;
    5460     1043106 :     dest->plan_rows = src->rows;
    5461     1043106 :     dest->plan_width = src->pathtarget->width;
    5462     1043106 :     dest->parallel_aware = src->parallel_aware;
    5463     1043106 :     dest->parallel_safe = src->parallel_safe;
    5464     1043106 : }
    5465             : 
    5466             : /*
    5467             :  * Copy cost and size info from a lower plan node to an inserted node.
    5468             :  * (Most callers alter the info after copying it.)
    5469             :  */
    5470             : static void
    5471       38074 : copy_plan_costsize(Plan *dest, Plan *src)
    5472             : {
    5473       38074 :     dest->disabled_nodes = src->disabled_nodes;
    5474       38074 :     dest->startup_cost = src->startup_cost;
    5475       38074 :     dest->total_cost = src->total_cost;
    5476       38074 :     dest->plan_rows = src->plan_rows;
    5477       38074 :     dest->plan_width = src->plan_width;
    5478             :     /* Assume the inserted node is not parallel-aware. */
    5479       38074 :     dest->parallel_aware = false;
    5480             :     /* Assume the inserted node is parallel-safe, if child plan is. */
    5481       38074 :     dest->parallel_safe = src->parallel_safe;
    5482       38074 : }
    5483             : 
    5484             : /*
    5485             :  * Some places in this file build Sort nodes that don't have a directly
    5486             :  * corresponding Path node.  The cost of the sort is, or should have been,
    5487             :  * included in the cost of the Path node we're working from, but since it's
    5488             :  * not split out, we have to re-figure it using cost_sort().  This is just
    5489             :  * to label the Sort node nicely for EXPLAIN.
    5490             :  *
    5491             :  * limit_tuples is as for cost_sort (in particular, pass -1 if no limit)
    5492             :  */
    5493             : static void
    5494        9476 : label_sort_with_costsize(PlannerInfo *root, Sort *plan, double limit_tuples)
    5495             : {
    5496        9476 :     Plan       *lefttree = plan->plan.lefttree;
    5497             :     Path        sort_path;      /* dummy for result of cost_sort */
    5498             : 
    5499             :     Assert(IsA(plan, Sort));
    5500             : 
    5501        9476 :     cost_sort(&sort_path, root, NIL,
    5502             :               plan->plan.disabled_nodes,
    5503             :               lefttree->total_cost,
    5504             :               lefttree->plan_rows,
    5505             :               lefttree->plan_width,
    5506             :               0.0,
    5507             :               work_mem,
    5508             :               limit_tuples);
    5509        9476 :     plan->plan.startup_cost = sort_path.startup_cost;
    5510        9476 :     plan->plan.total_cost = sort_path.total_cost;
    5511        9476 :     plan->plan.plan_rows = lefttree->plan_rows;
    5512        9476 :     plan->plan.plan_width = lefttree->plan_width;
    5513        9476 :     plan->plan.parallel_aware = false;
    5514        9476 :     plan->plan.parallel_safe = lefttree->parallel_safe;
    5515        9476 : }
    5516             : 
    5517             : /*
    5518             :  * Same as label_sort_with_costsize, but labels the IncrementalSort node
    5519             :  * instead.
    5520             :  */
    5521             : static void
    5522          12 : label_incrementalsort_with_costsize(PlannerInfo *root, IncrementalSort *plan,
    5523             :                                     List *pathkeys, double limit_tuples)
    5524             : {
    5525          12 :     Plan       *lefttree = plan->sort.plan.lefttree;
    5526             :     Path        sort_path;      /* dummy for result of cost_incremental_sort */
    5527             : 
    5528             :     Assert(IsA(plan, IncrementalSort));
    5529             : 
    5530          12 :     cost_incremental_sort(&sort_path, root, pathkeys,
    5531             :                           plan->nPresortedCols,
    5532             :                           plan->sort.plan.disabled_nodes,
    5533             :                           lefttree->startup_cost,
    5534             :                           lefttree->total_cost,
    5535             :                           lefttree->plan_rows,
    5536             :                           lefttree->plan_width,
    5537             :                           0.0,
    5538             :                           work_mem,
    5539             :                           limit_tuples);
    5540          12 :     plan->sort.plan.startup_cost = sort_path.startup_cost;
    5541          12 :     plan->sort.plan.total_cost = sort_path.total_cost;
    5542          12 :     plan->sort.plan.plan_rows = lefttree->plan_rows;
    5543          12 :     plan->sort.plan.plan_width = lefttree->plan_width;
    5544          12 :     plan->sort.plan.parallel_aware = false;
    5545          12 :     plan->sort.plan.parallel_safe = lefttree->parallel_safe;
    5546          12 : }
    5547             : 
    5548             : /*
    5549             :  * bitmap_subplan_mark_shared
    5550             :  *   Set isshared flag in bitmap subplan so that it will be created in
    5551             :  *   shared memory.
    5552             :  */
    5553             : static void
    5554          30 : bitmap_subplan_mark_shared(Plan *plan)
    5555             : {
    5556          30 :     if (IsA(plan, BitmapAnd))
    5557           0 :         bitmap_subplan_mark_shared(linitial(((BitmapAnd *) plan)->bitmapplans));
    5558          30 :     else if (IsA(plan, BitmapOr))
    5559             :     {
    5560           0 :         ((BitmapOr *) plan)->isshared = true;
    5561           0 :         bitmap_subplan_mark_shared(linitial(((BitmapOr *) plan)->bitmapplans));
    5562             :     }
    5563          30 :     else if (IsA(plan, BitmapIndexScan))
    5564          30 :         ((BitmapIndexScan *) plan)->isshared = true;
    5565             :     else
    5566           0 :         elog(ERROR, "unrecognized node type: %d", nodeTag(plan));
    5567          30 : }
    5568             : 
    5569             : /*****************************************************************************
    5570             :  *
    5571             :  *  PLAN NODE BUILDING ROUTINES
    5572             :  *
    5573             :  * In general, these functions are not passed the original Path and therefore
    5574             :  * leave it to the caller to fill in the cost/width fields from the Path,
    5575             :  * typically by calling copy_generic_path_info().  This convention is
    5576             :  * somewhat historical, but it does support a few places above where we build
    5577             :  * a plan node without having an exactly corresponding Path node.  Under no
    5578             :  * circumstances should one of these functions do its own cost calculations,
    5579             :  * as that would be redundant with calculations done while building Paths.
    5580             :  *
    5581             :  *****************************************************************************/
    5582             : 
    5583             : static SeqScan *
    5584      191710 : make_seqscan(List *qptlist,
    5585             :              List *qpqual,
    5586             :              Index scanrelid)
    5587             : {
    5588      191710 :     SeqScan    *node = makeNode(SeqScan);
    5589      191710 :     Plan       *plan = &node->scan.plan;
    5590             : 
    5591      191710 :     plan->targetlist = qptlist;
    5592      191710 :     plan->qual = qpqual;
    5593      191710 :     plan->lefttree = NULL;
    5594      191710 :     plan->righttree = NULL;
    5595      191710 :     node->scan.scanrelid = scanrelid;
    5596             : 
    5597      191710 :     return node;
    5598             : }
    5599             : 
    5600             : static SampleScan *
    5601         300 : make_samplescan(List *qptlist,
    5602             :                 List *qpqual,
    5603             :                 Index scanrelid,
    5604             :                 TableSampleClause *tsc)
    5605             : {
    5606         300 :     SampleScan *node = makeNode(SampleScan);
    5607         300 :     Plan       *plan = &node->scan.plan;
    5608             : 
    5609         300 :     plan->targetlist = qptlist;
    5610         300 :     plan->qual = qpqual;
    5611         300 :     plan->lefttree = NULL;
    5612         300 :     plan->righttree = NULL;
    5613         300 :     node->scan.scanrelid = scanrelid;
    5614         300 :     node->tablesample = tsc;
    5615             : 
    5616         300 :     return node;
    5617             : }
    5618             : 
    5619             : static IndexScan *
    5620      151074 : make_indexscan(List *qptlist,
    5621             :                List *qpqual,
    5622             :                Index scanrelid,
    5623             :                Oid indexid,
    5624             :                List *indexqual,
    5625             :                List *indexqualorig,
    5626             :                List *indexorderby,
    5627             :                List *indexorderbyorig,
    5628             :                List *indexorderbyops,
    5629             :                ScanDirection indexscandir)
    5630             : {
    5631      151074 :     IndexScan  *node = makeNode(IndexScan);
    5632      151074 :     Plan       *plan = &node->scan.plan;
    5633             : 
    5634      151074 :     plan->targetlist = qptlist;
    5635      151074 :     plan->qual = qpqual;
    5636      151074 :     plan->lefttree = NULL;
    5637      151074 :     plan->righttree = NULL;
    5638      151074 :     node->scan.scanrelid = scanrelid;
    5639      151074 :     node->indexid = indexid;
    5640      151074 :     node->indexqual = indexqual;
    5641      151074 :     node->indexqualorig = indexqualorig;
    5642      151074 :     node->indexorderby = indexorderby;
    5643      151074 :     node->indexorderbyorig = indexorderbyorig;
    5644      151074 :     node->indexorderbyops = indexorderbyops;
    5645      151074 :     node->indexorderdir = indexscandir;
    5646             : 
    5647      151074 :     return node;
    5648             : }
    5649             : 
    5650             : static IndexOnlyScan *
    5651       15290 : make_indexonlyscan(List *qptlist,
    5652             :                    List *qpqual,
    5653             :                    Index scanrelid,
    5654             :                    Oid indexid,
    5655             :                    List *indexqual,
    5656             :                    List *recheckqual,
    5657             :                    List *indexorderby,
    5658             :                    List *indextlist,
    5659             :                    ScanDirection indexscandir)
    5660             : {
    5661       15290 :     IndexOnlyScan *node = makeNode(IndexOnlyScan);
    5662       15290 :     Plan       *plan = &node->scan.plan;
    5663             : 
    5664       15290 :     plan->targetlist = qptlist;
    5665       15290 :     plan->qual = qpqual;
    5666       15290 :     plan->lefttree = NULL;
    5667       15290 :     plan->righttree = NULL;
    5668       15290 :     node->scan.scanrelid = scanrelid;
    5669       15290 :     node->indexid = indexid;
    5670       15290 :     node->indexqual = indexqual;
    5671       15290 :     node->recheckqual = recheckqual;
    5672       15290 :     node->indexorderby = indexorderby;
    5673       15290 :     node->indextlist = indextlist;
    5674       15290 :     node->indexorderdir = indexscandir;
    5675             : 
    5676       15290 :     return node;
    5677             : }
    5678             : 
    5679             : static BitmapIndexScan *
    5680       20614 : make_bitmap_indexscan(Index scanrelid,
    5681             :                       Oid indexid,
    5682             :                       List *indexqual,
    5683             :                       List *indexqualorig)
    5684             : {
    5685       20614 :     BitmapIndexScan *node = makeNode(BitmapIndexScan);
    5686       20614 :     Plan       *plan = &node->scan.plan;
    5687             : 
    5688       20614 :     plan->targetlist = NIL;      /* not used */
    5689       20614 :     plan->qual = NIL;            /* not used */
    5690       20614 :     plan->lefttree = NULL;
    5691       20614 :     plan->righttree = NULL;
    5692       20614 :     node->scan.scanrelid = scanrelid;
    5693       20614 :     node->indexid = indexid;
    5694       20614 :     node->indexqual = indexqual;
    5695       20614 :     node->indexqualorig = indexqualorig;
    5696             : 
    5697       20614 :     return node;
    5698             : }
    5699             : 
    5700             : static BitmapHeapScan *
    5701       20156 : make_bitmap_heapscan(List *qptlist,
    5702             :                      List *qpqual,
    5703             :                      Plan *lefttree,
    5704             :                      List *bitmapqualorig,
    5705             :                      Index scanrelid)
    5706             : {
    5707       20156 :     BitmapHeapScan *node = makeNode(BitmapHeapScan);
    5708       20156 :     Plan       *plan = &node->scan.plan;
    5709             : 
    5710       20156 :     plan->targetlist = qptlist;
    5711       20156 :     plan->qual = qpqual;
    5712       20156 :     plan->lefttree = lefttree;
    5713       20156 :     plan->righttree = NULL;
    5714       20156 :     node->scan.scanrelid = scanrelid;
    5715       20156 :     node->bitmapqualorig = bitmapqualorig;
    5716             : 
    5717       20156 :     return node;
    5718             : }
    5719             : 
    5720             : static TidScan *
    5721         700 : make_tidscan(List *qptlist,
    5722             :              List *qpqual,
    5723             :              Index scanrelid,
    5724             :              List *tidquals)
    5725             : {
    5726         700 :     TidScan    *node = makeNode(TidScan);
    5727         700 :     Plan       *plan = &node->scan.plan;
    5728             : 
    5729         700 :     plan->targetlist = qptlist;
    5730         700 :     plan->qual = qpqual;
    5731         700 :     plan->lefttree = NULL;
    5732         700 :     plan->righttree = NULL;
    5733         700 :     node->scan.scanrelid = scanrelid;
    5734         700 :     node->tidquals = tidquals;
    5735             : 
    5736         700 :     return node;
    5737             : }
    5738             : 
    5739             : static TidRangeScan *
    5740         202 : make_tidrangescan(List *qptlist,
    5741             :                   List *qpqual,
    5742             :                   Index scanrelid,
    5743             :                   List *tidrangequals)
    5744             : {
    5745         202 :     TidRangeScan *node = makeNode(TidRangeScan);
    5746         202 :     Plan       *plan = &node->scan.plan;
    5747             : 
    5748         202 :     plan->targetlist = qptlist;
    5749         202 :     plan->qual = qpqual;
    5750         202 :     plan->lefttree = NULL;
    5751         202 :     plan->righttree = NULL;
    5752         202 :     node->scan.scanrelid = scanrelid;
    5753         202 :     node->tidrangequals = tidrangequals;
    5754             : 
    5755         202 :     return node;
    5756             : }
    5757             : 
    5758             : static SubqueryScan *
    5759       22574 : make_subqueryscan(List *qptlist,
    5760             :                   List *qpqual,
    5761             :                   Index scanrelid,
    5762             :                   Plan *subplan)
    5763             : {
    5764       22574 :     SubqueryScan *node = makeNode(SubqueryScan);
    5765       22574 :     Plan       *plan = &node->scan.plan;
    5766             : 
    5767       22574 :     plan->targetlist = qptlist;
    5768       22574 :     plan->qual = qpqual;
    5769       22574 :     plan->lefttree = NULL;
    5770       22574 :     plan->righttree = NULL;
    5771       22574 :     node->scan.scanrelid = scanrelid;
    5772       22574 :     node->subplan = subplan;
    5773       22574 :     node->scanstatus = SUBQUERY_SCAN_UNKNOWN;
    5774             : 
    5775       22574 :     return node;
    5776             : }
    5777             : 
    5778             : static FunctionScan *
    5779       44176 : make_functionscan(List *qptlist,
    5780             :                   List *qpqual,
    5781             :                   Index scanrelid,
    5782             :                   List *functions,
    5783             :                   bool funcordinality)
    5784             : {
    5785       44176 :     FunctionScan *node = makeNode(FunctionScan);
    5786       44176 :     Plan       *plan = &node->scan.plan;
    5787             : 
    5788       44176 :     plan->targetlist = qptlist;
    5789       44176 :     plan->qual = qpqual;
    5790       44176 :     plan->lefttree = NULL;
    5791       44176 :     plan->righttree = NULL;
    5792       44176 :     node->scan.scanrelid = scanrelid;
    5793       44176 :     node->functions = functions;
    5794       44176 :     node->funcordinality = funcordinality;
    5795             : 
    5796       44176 :     return node;
    5797             : }
    5798             : 
    5799             : static TableFuncScan *
    5800         626 : make_tablefuncscan(List *qptlist,
    5801             :                    List *qpqual,
    5802             :                    Index scanrelid,
    5803             :                    TableFunc *tablefunc)
    5804             : {
    5805         626 :     TableFuncScan *node = makeNode(TableFuncScan);
    5806         626 :     Plan       *plan = &node->scan.plan;
    5807             : 
    5808         626 :     plan->targetlist = qptlist;
    5809         626 :     plan->qual = qpqual;
    5810         626 :     plan->lefttree = NULL;
    5811         626 :     plan->righttree = NULL;
    5812         626 :     node->scan.scanrelid = scanrelid;
    5813         626 :     node->tablefunc = tablefunc;
    5814             : 
    5815         626 :     return node;
    5816             : }
    5817             : 
    5818             : static ValuesScan *
    5819        7980 : make_valuesscan(List *qptlist,
    5820             :                 List *qpqual,
    5821             :                 Index scanrelid,
    5822             :                 List *values_lists)
    5823             : {
    5824        7980 :     ValuesScan *node = makeNode(ValuesScan);
    5825        7980 :     Plan       *plan = &node->scan.plan;
    5826             : 
    5827        7980 :     plan->targetlist = qptlist;
    5828        7980 :     plan->qual = qpqual;
    5829        7980 :     plan->lefttree = NULL;
    5830        7980 :     plan->righttree = NULL;
    5831        7980 :     node->scan.scanrelid = scanrelid;
    5832        7980 :     node->values_lists = values_lists;
    5833             : 
    5834        7980 :     return node;
    5835             : }
    5836             : 
    5837             : static CteScan *
    5838        3186 : make_ctescan(List *qptlist,
    5839             :              List *qpqual,
    5840             :              Index scanrelid,
    5841             :              int ctePlanId,
    5842             :              int cteParam)
    5843             : {
    5844        3186 :     CteScan    *node = makeNode(CteScan);
    5845        3186 :     Plan       *plan = &node->scan.plan;
    5846             : 
    5847        3186 :     plan->targetlist = qptlist;
    5848        3186 :     plan->qual = qpqual;
    5849        3186 :     plan->lefttree = NULL;
    5850        3186 :     plan->righttree = NULL;
    5851        3186 :     node->scan.scanrelid = scanrelid;
    5852        3186 :     node->ctePlanId = ctePlanId;
    5853        3186 :     node->cteParam = cteParam;
    5854             : 
    5855        3186 :     return node;
    5856             : }
    5857             : 
    5858             : static NamedTuplestoreScan *
    5859         438 : make_namedtuplestorescan(List *qptlist,
    5860             :                          List *qpqual,
    5861             :                          Index scanrelid,
    5862             :                          char *enrname)
    5863             : {
    5864         438 :     NamedTuplestoreScan *node = makeNode(NamedTuplestoreScan);
    5865         438 :     Plan       *plan = &node->scan.plan;
    5866             : 
    5867             :     /* cost should be inserted by caller */
    5868         438 :     plan->targetlist = qptlist;
    5869         438 :     plan->qual = qpqual;
    5870         438 :     plan->lefttree = NULL;
    5871         438 :     plan->righttree = NULL;
    5872         438 :     node->scan.scanrelid = scanrelid;
    5873         438 :     node->enrname = enrname;
    5874             : 
    5875         438 :     return node;
    5876             : }
    5877             : 
    5878             : static WorkTableScan *
    5879         816 : make_worktablescan(List *qptlist,
    5880             :                    List *qpqual,
    5881             :                    Index scanrelid,
    5882             :                    int wtParam)
    5883             : {
    5884         816 :     WorkTableScan *node = makeNode(WorkTableScan);
    5885         816 :     Plan       *plan = &node->scan.plan;
    5886             : 
    5887         816 :     plan->targetlist = qptlist;
    5888         816 :     plan->qual = qpqual;
    5889         816 :     plan->lefttree = NULL;
    5890         816 :     plan->righttree = NULL;
    5891         816 :     node->scan.scanrelid = scanrelid;
    5892         816 :     node->wtParam = wtParam;
    5893             : 
    5894         816 :     return node;
    5895             : }
    5896             : 
    5897             : ForeignScan *
    5898        2024 : make_foreignscan(List *qptlist,
    5899             :                  List *qpqual,
    5900             :                  Index scanrelid,
    5901             :                  List *fdw_exprs,
    5902             :                  List *fdw_private,
    5903             :                  List *fdw_scan_tlist,
    5904             :                  List *fdw_recheck_quals,
    5905             :                  Plan *outer_plan)
    5906             : {
    5907        2024 :     ForeignScan *node = makeNode(ForeignScan);
    5908        2024 :     Plan       *plan = &node->scan.plan;
    5909             : 
    5910             :     /* cost will be filled in by create_foreignscan_plan */
    5911        2024 :     plan->targetlist = qptlist;
    5912        2024 :     plan->qual = qpqual;
    5913        2024 :     plan->lefttree = outer_plan;
    5914        2024 :     plan->righttree = NULL;
    5915        2024 :     node->scan.scanrelid = scanrelid;
    5916             : 
    5917             :     /* these may be overridden by the FDW's PlanDirectModify callback. */
    5918        2024 :     node->operation = CMD_SELECT;
    5919        2024 :     node->resultRelation = 0;
    5920             : 
    5921             :     /* checkAsUser, fs_server will be filled in by create_foreignscan_plan */
    5922        2024 :     node->checkAsUser = InvalidOid;
    5923        2024 :     node->fs_server = InvalidOid;
    5924        2024 :     node->fdw_exprs = fdw_exprs;
    5925        2024 :     node->fdw_private = fdw_private;
    5926        2024 :     node->fdw_scan_tlist = fdw_scan_tlist;
    5927        2024 :     node->fdw_recheck_quals = fdw_recheck_quals;
    5928             :     /* fs_relids, fs_base_relids will be filled by create_foreignscan_plan */
    5929        2024 :     node->fs_relids = NULL;
    5930        2024 :     node->fs_base_relids = NULL;
    5931             :     /* fsSystemCol will be filled in by create_foreignscan_plan */
    5932        2024 :     node->fsSystemCol = false;
    5933             : 
    5934        2024 :     return node;
    5935             : }
    5936             : 
    5937             : static RecursiveUnion *
    5938         816 : make_recursive_union(List *tlist,
    5939             :                      Plan *lefttree,
    5940             :                      Plan *righttree,
    5941             :                      int wtParam,
    5942             :                      List *distinctList,
    5943             :                      long numGroups)
    5944             : {
    5945         816 :     RecursiveUnion *node = makeNode(RecursiveUnion);
    5946         816 :     Plan       *plan = &node->plan;
    5947         816 :     int         numCols = list_length(distinctList);
    5948             : 
    5949         816 :     plan->targetlist = tlist;
    5950         816 :     plan->qual = NIL;
    5951         816 :     plan->lefttree = lefttree;
    5952         816 :     plan->righttree = righttree;
    5953         816 :     node->wtParam = wtParam;
    5954             : 
    5955             :     /*
    5956             :      * convert SortGroupClause list into arrays of attr indexes and equality
    5957             :      * operators, as wanted by executor
    5958             :      */
    5959         816 :     node->numCols = numCols;
    5960         816 :     if (numCols > 0)
    5961             :     {
    5962         364 :         int         keyno = 0;
    5963             :         AttrNumber *dupColIdx;
    5964             :         Oid        *dupOperators;
    5965             :         Oid        *dupCollations;
    5966             :         ListCell   *slitem;
    5967             : 
    5968         364 :         dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
    5969         364 :         dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
    5970         364 :         dupCollations = (Oid *) palloc(sizeof(Oid) * numCols);
    5971             : 
    5972        1384 :         foreach(slitem, distinctList)
    5973             :         {
    5974        1020 :             SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
    5975        1020 :             TargetEntry *tle = get_sortgroupclause_tle(sortcl,
    5976             :                                                        plan->targetlist);
    5977             : 
    5978        1020 :             dupColIdx[keyno] = tle->resno;
    5979        1020 :             dupOperators[keyno] = sortcl->eqop;
    5980        1020 :             dupCollations[keyno] = exprCollation((Node *) tle->expr);
    5981             :             Assert(OidIsValid(dupOperators[keyno]));
    5982        1020 :             keyno++;
    5983             :         }
    5984         364 :         node->dupColIdx = dupColIdx;
    5985         364 :         node->dupOperators = dupOperators;
    5986         364 :         node->dupCollations = dupCollations;
    5987             :     }
    5988         816 :     node->numGroups = numGroups;
    5989             : 
    5990         816 :     return node;
    5991             : }
    5992             : 
    5993             : static BitmapAnd *
    5994         152 : make_bitmap_and(List *bitmapplans)
    5995             : {
    5996         152 :     BitmapAnd  *node = makeNode(BitmapAnd);
    5997         152 :     Plan       *plan = &node->plan;
    5998             : 
    5999         152 :     plan->targetlist = NIL;
    6000         152 :     plan->qual = NIL;
    6001         152 :     plan->lefttree = NULL;
    6002         152 :     plan->righttree = NULL;
    6003         152 :     node->bitmapplans = bitmapplans;
    6004             : 
    6005         152 :     return node;
    6006             : }
    6007             : 
    6008             : static BitmapOr *
    6009         300 : make_bitmap_or(List *bitmapplans)
    6010             : {
    6011         300 :     BitmapOr   *node = makeNode(BitmapOr);
    6012         300 :     Plan       *plan = &node->plan;
    6013             : 
    6014         300 :     plan->targetlist = NIL;
    6015         300 :     plan->qual = NIL;
    6016         300 :     plan->lefttree = NULL;
    6017         300 :     plan->righttree = NULL;
    6018         300 :     node->bitmapplans = bitmapplans;
    6019             : 
    6020         300 :     return node;
    6021             : }
    6022             : 
    6023             : static NestLoop *
    6024       83802 : make_nestloop(List *tlist,
    6025             :               List *joinclauses,
    6026             :               List *otherclauses,
    6027             :               List *nestParams,
    6028             :               Plan *lefttree,
    6029             :               Plan *righttree,
    6030             :               JoinType jointype,
    6031             :               bool inner_unique)
    6032             : {
    6033       83802 :     NestLoop   *node = makeNode(NestLoop);
    6034       83802 :     Plan       *plan = &node->join.plan;
    6035             : 
    6036       83802 :     plan->targetlist = tlist;
    6037       83802 :     plan->qual = otherclauses;
    6038       83802 :     plan->lefttree = lefttree;
    6039       83802 :     plan->righttree = righttree;
    6040       83802 :     node->join.jointype = jointype;
    6041       83802 :     node->join.inner_unique = inner_unique;
    6042       83802 :     node->join.joinqual = joinclauses;
    6043       83802 :     node->nestParams = nestParams;
    6044             : 
    6045       83802 :     return node;
    6046             : }
    6047             : 
    6048             : static HashJoin *
    6049       28878 : make_hashjoin(List *tlist,
    6050             :               List *joinclauses,
    6051             :               List *otherclauses,
    6052             :               List *hashclauses,
    6053             :               List *hashoperators,
    6054             :               List *hashcollations,
    6055             :               List *hashkeys,
    6056             :               Plan *lefttree,
    6057             :               Plan *righttree,
    6058             :               JoinType jointype,
    6059             :               bool inner_unique)
    6060             : {
    6061       28878 :     HashJoin   *node = makeNode(HashJoin);
    6062       28878 :     Plan       *plan = &node->join.plan;
    6063             : 
    6064       28878 :     plan->targetlist = tlist;
    6065       28878 :     plan->qual = otherclauses;
    6066       28878 :     plan->lefttree = lefttree;
    6067       28878 :     plan->righttree = righttree;
    6068       28878 :     node->hashclauses = hashclauses;
    6069       28878 :     node->hashoperators = hashoperators;
    6070       28878 :     node->hashcollations = hashcollations;
    6071       28878 :     node->hashkeys = hashkeys;
    6072       28878 :     node->join.jointype = jointype;
    6073       28878 :     node->join.inner_unique = inner_unique;
    6074       28878 :     node->join.joinqual = joinclauses;
    6075             : 
    6076       28878 :     return node;
    6077             : }
    6078             : 
    6079             : static Hash *
    6080       28878 : make_hash(Plan *lefttree,
    6081             :           List *hashkeys,
    6082             :           Oid skewTable,
    6083             :           AttrNumber skewColumn,
    6084             :           bool skewInherit)
    6085             : {
    6086       28878 :     Hash       *node = makeNode(Hash);
    6087       28878 :     Plan       *plan = &node->plan;
    6088             : 
    6089       28878 :     plan->targetlist = lefttree->targetlist;
    6090       28878 :     plan->qual = NIL;
    6091       28878 :     plan->lefttree = lefttree;
    6092       28878 :     plan->righttree = NULL;
    6093             : 
    6094       28878 :     node->hashkeys = hashkeys;
    6095       28878 :     node->skewTable = skewTable;
    6096       28878 :     node->skewColumn = skewColumn;
    6097       28878 :     node->skewInherit = skewInherit;
    6098             : 
    6099       28878 :     return node;
    6100             : }
    6101             : 
    6102             : static MergeJoin *
    6103        7094 : make_mergejoin(List *tlist,
    6104             :                List *joinclauses,
    6105             :                List *otherclauses,
    6106             :                List *mergeclauses,
    6107             :                Oid *mergefamilies,
    6108             :                Oid *mergecollations,
    6109             :                bool *mergereversals,
    6110             :                bool *mergenullsfirst,
    6111             :                Plan *lefttree,
    6112             :                Plan *righttree,
    6113             :                JoinType jointype,
    6114             :                bool inner_unique,
    6115             :                bool skip_mark_restore)
    6116             : {
    6117        7094 :     MergeJoin  *node = makeNode(MergeJoin);
    6118        7094 :     Plan       *plan = &node->join.plan;
    6119             : 
    6120        7094 :     plan->targetlist = tlist;
    6121        7094 :     plan->qual = otherclauses;
    6122        7094 :     plan->lefttree = lefttree;
    6123        7094 :     plan->righttree = righttree;
    6124        7094 :     node->skip_mark_restore = skip_mark_restore;
    6125        7094 :     node->mergeclauses = mergeclauses;
    6126        7094 :     node->mergeFamilies = mergefamilies;
    6127        7094 :     node->mergeCollations = mergecollations;
    6128        7094 :     node->mergeReversals = mergereversals;
    6129        7094 :     node->mergeNullsFirst = mergenullsfirst;
    6130        7094 :     node->join.jointype = jointype;
    6131        7094 :     node->join.inner_unique = inner_unique;
    6132        7094 :     node->join.joinqual = joinclauses;
    6133             : 
    6134        7094 :     return node;
    6135             : }
    6136             : 
    6137             : /*
    6138             :  * make_sort --- basic routine to build a Sort plan node
    6139             :  *
    6140             :  * Caller must have built the sortColIdx, sortOperators, collations, and
    6141             :  * nullsFirst arrays already.
    6142             :  */
    6143             : static Sort *
    6144       68882 : make_sort(Plan *lefttree, int numCols,
    6145             :           AttrNumber *sortColIdx, Oid *sortOperators,
    6146             :           Oid *collations, bool *nullsFirst)
    6147             : {
    6148             :     Sort       *node;
    6149             :     Plan       *plan;
    6150             : 
    6151       68882 :     node = makeNode(Sort);
    6152             : 
    6153       68882 :     plan = &node->plan;
    6154       68882 :     plan->targetlist = lefttree->targetlist;
    6155       68882 :     plan->disabled_nodes = lefttree->disabled_nodes + (enable_sort == false);
    6156       68882 :     plan->qual = NIL;
    6157       68882 :     plan->lefttree = lefttree;
    6158       68882 :     plan->righttree = NULL;
    6159       68882 :     node->numCols = numCols;
    6160       68882 :     node->sortColIdx = sortColIdx;
    6161       68882 :     node->sortOperators = sortOperators;
    6162       68882 :     node->collations = collations;
    6163       68882 :     node->nullsFirst = nullsFirst;
    6164             : 
    6165       68882 :     return node;
    6166             : }
    6167             : 
    6168             : /*
    6169             :  * make_incrementalsort --- basic routine to build an IncrementalSort plan node
    6170             :  *
    6171             :  * Caller must have built the sortColIdx, sortOperators, collations, and
    6172             :  * nullsFirst arrays already.
    6173             :  */
    6174             : static IncrementalSort *
    6175         770 : make_incrementalsort(Plan *lefttree, int numCols, int nPresortedCols,
    6176             :                      AttrNumber *sortColIdx, Oid *sortOperators,
    6177             :                      Oid *collations, bool *nullsFirst)
    6178             : {
    6179             :     IncrementalSort *node;
    6180             :     Plan       *plan;
    6181             : 
    6182         770 :     node = makeNode(IncrementalSort);
    6183             : 
    6184         770 :     plan = &node->sort.plan;
    6185         770 :     plan->targetlist = lefttree->targetlist;
    6186         770 :     plan->qual = NIL;
    6187         770 :     plan->lefttree = lefttree;
    6188         770 :     plan->righttree = NULL;
    6189         770 :     node->nPresortedCols = nPresortedCols;
    6190         770 :     node->sort.numCols = numCols;
    6191         770 :     node->sort.sortColIdx = sortColIdx;
    6192         770 :     node->sort.sortOperators = sortOperators;
    6193         770 :     node->sort.collations = collations;
    6194         770 :     node->sort.nullsFirst = nullsFirst;
    6195             : 
    6196         770 :     return node;
    6197             : }
    6198             : 
    6199             : /*
    6200             :  * prepare_sort_from_pathkeys
    6201             :  *    Prepare to sort according to given pathkeys
    6202             :  *
    6203             :  * This is used to set up for Sort, MergeAppend, and Gather Merge nodes.  It
    6204             :  * calculates the executor's representation of the sort key information, and
    6205             :  * adjusts the plan targetlist if needed to add resjunk sort columns.
    6206             :  *
    6207             :  * Input parameters:
    6208             :  *    'lefttree' is the plan node which yields input tuples
    6209             :  *    'pathkeys' is the list of pathkeys by which the result is to be sorted
    6210             :  *    'relids' identifies the child relation being sorted, if any
    6211             :  *    'reqColIdx' is NULL or an array of required sort key column numbers
    6212             :  *    'adjust_tlist_in_place' is true if lefttree must be modified in-place
    6213             :  *
    6214             :  * We must convert the pathkey information into arrays of sort key column
    6215             :  * numbers, sort operator OIDs, collation OIDs, and nulls-first flags,
    6216             :  * which is the representation the executor wants.  These are returned into
    6217             :  * the output parameters *p_numsortkeys etc.
    6218             :  *
    6219             :  * When looking for matches to an EquivalenceClass's members, we will only
    6220             :  * consider child EC members if they belong to given 'relids'.  This protects
    6221             :  * against possible incorrect matches to child expressions that contain no
    6222             :  * Vars.
    6223             :  *
    6224             :  * If reqColIdx isn't NULL then it contains sort key column numbers that
    6225             :  * we should match.  This is used when making child plans for a MergeAppend;
    6226             :  * it's an error if we can't match the columns.
    6227             :  *
    6228             :  * If the pathkeys include expressions that aren't simple Vars, we will
    6229             :  * usually need to add resjunk items to the input plan's targetlist to
    6230             :  * compute these expressions, since a Sort or MergeAppend node itself won't
    6231             :  * do any such calculations.  If the input plan type isn't one that can do
    6232             :  * projections, this means adding a Result node just to do the projection.
    6233             :  * However, the caller can pass adjust_tlist_in_place = true to force the
    6234             :  * lefttree tlist to be modified in-place regardless of whether the node type
    6235             :  * can project --- we use this for fixing the tlist of MergeAppend itself.
    6236             :  *
    6237             :  * Returns the node which is to be the input to the Sort (either lefttree,
    6238             :  * or a Result stacked atop lefttree).
    6239             :  */
    6240             : static Plan *
    6241       72544 : prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
    6242             :                            Relids relids,
    6243             :                            const AttrNumber *reqColIdx,
    6244             :                            bool adjust_tlist_in_place,
    6245             :                            int *p_numsortkeys,
    6246             :                            AttrNumber **p_sortColIdx,
    6247             :                            Oid **p_sortOperators,
    6248             :                            Oid **p_collations,
    6249             :                            bool **p_nullsFirst)
    6250             : {
    6251       72544 :     List       *tlist = lefttree->targetlist;
    6252             :     ListCell   *i;
    6253             :     int         numsortkeys;
    6254             :     AttrNumber *sortColIdx;
    6255             :     Oid        *sortOperators;
    6256             :     Oid        *collations;
    6257             :     bool       *nullsFirst;
    6258             : 
    6259             :     /*
    6260             :      * We will need at most list_length(pathkeys) sort columns; possibly less
    6261             :      */
    6262       72544 :     numsortkeys = list_length(pathkeys);
    6263       72544 :     sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
    6264       72544 :     sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
    6265       72544 :     collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
    6266       72544 :     nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
    6267             : 
    6268       72544 :     numsortkeys = 0;
    6269             : 
    6270      182200 :     foreach(i, pathkeys)
    6271             :     {
    6272      109656 :         PathKey    *pathkey = (PathKey *) lfirst(i);
    6273      109656 :         EquivalenceClass *ec = pathkey->pk_eclass;
    6274             :         EquivalenceMember *em;
    6275      109656 :         TargetEntry *tle = NULL;
    6276      109656 :         Oid         pk_datatype = InvalidOid;
    6277             :         Oid         sortop;
    6278             :         ListCell   *j;
    6279             : 
    6280      109656 :         if (ec->ec_has_volatile)
    6281             :         {
    6282             :             /*
    6283             :              * If the pathkey's EquivalenceClass is volatile, then it must
    6284             :              * have come from an ORDER BY clause, and we have to match it to
    6285             :              * that same targetlist entry.
    6286             :              */
    6287         168 :             if (ec->ec_sortref == 0) /* can't happen */
    6288           0 :                 elog(ERROR, "volatile EquivalenceClass has no sortref");
    6289         168 :             tle = get_sortgroupref_tle(ec->ec_sortref, tlist);
    6290             :             Assert(tle);
    6291             :             Assert(list_length(ec->ec_members) == 1);
    6292         168 :             pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
    6293             :         }
    6294      109488 :         else if (reqColIdx != NULL)
    6295             :         {
    6296             :             /*
    6297             :              * If we are given a sort column number to match, only consider
    6298             :              * the single TLE at that position.  It's possible that there is
    6299             :              * no such TLE, in which case fall through and generate a resjunk
    6300             :              * targetentry (we assume this must have happened in the parent
    6301             :              * plan as well).  If there is a TLE but it doesn't match the
    6302             :              * pathkey's EC, we do the same, which is probably the wrong thing
    6303             :              * but we'll leave it to caller to complain about the mismatch.
    6304             :              */
    6305        2896 :             tle = get_tle_by_resno(tlist, reqColIdx[numsortkeys]);
    6306        2896 :             if (tle)
    6307             :             {
    6308        2776 :                 em = find_ec_member_matching_expr(ec, tle->expr, relids);
    6309        2776 :                 if (em)
    6310             :                 {
    6311             :                     /* found expr at right place in tlist */
    6312        2776 :                     pk_datatype = em->em_datatype;
    6313             :                 }
    6314             :                 else
    6315           0 :                     tle = NULL;
    6316             :             }
    6317             :         }
    6318             :         else
    6319             :         {
    6320             :             /*
    6321             :              * Otherwise, we can sort by any non-constant expression listed in
    6322             :              * the pathkey's EquivalenceClass.  For now, we take the first
    6323             :              * tlist item found in the EC. If there's no match, we'll generate
    6324             :              * a resjunk entry using the first EC member that is an expression
    6325             :              * in the input's vars.
    6326             :              *
    6327             :              * XXX if we have a choice, is there any way of figuring out which
    6328             :              * might be cheapest to execute?  (For example, int4lt is likely
    6329             :              * much cheaper to execute than numericlt, but both might appear
    6330             :              * in the same equivalence class...)  Not clear that we ever will
    6331             :              * have an interesting choice in practice, so it may not matter.
    6332             :              */
    6333      287376 :             foreach(j, tlist)
    6334             :             {
    6335      287144 :                 tle = (TargetEntry *) lfirst(j);
    6336      287144 :                 em = find_ec_member_matching_expr(ec, tle->expr, relids);
    6337      287144 :                 if (em)
    6338             :                 {
    6339             :                     /* found expr already in tlist */
    6340      106360 :                     pk_datatype = em->em_datatype;
    6341      106360 :                     break;
    6342             :                 }
    6343      180784 :                 tle = NULL;
    6344             :             }
    6345             :         }
    6346             : 
    6347      109656 :         if (!tle)
    6348             :         {
    6349             :             /*
    6350             :              * No matching tlist item; look for a computable expression.
    6351             :              */
    6352         352 :             em = find_computable_ec_member(NULL, ec, tlist, relids, false);
    6353         352 :             if (!em)
    6354           0 :                 elog(ERROR, "could not find pathkey item to sort");
    6355         352 :             pk_datatype = em->em_datatype;
    6356             : 
    6357             :             /*
    6358             :              * Do we need to insert a Result node?
    6359             :              */
    6360         352 :             if (!adjust_tlist_in_place &&
    6361         316 :                 !is_projection_capable_plan(lefttree))
    6362             :             {
    6363             :                 /* copy needed so we don't modify input's tlist below */
    6364          26 :                 tlist = copyObject(tlist);
    6365          26 :                 lefttree = inject_projection_plan(lefttree, tlist,
    6366          26 :                                                   lefttree->parallel_safe);
    6367             :             }
    6368             : 
    6369             :             /* Don't bother testing is_projection_capable_plan again */
    6370         352 :             adjust_tlist_in_place = true;
    6371             : 
    6372             :             /*
    6373             :              * Add resjunk entry to input's tlist
    6374             :              */
    6375         352 :             tle = makeTargetEntry(copyObject(em->em_expr),
    6376         352 :                                   list_length(tlist) + 1,
    6377             :                                   NULL,
    6378             :                                   true);
    6379         352 :             tlist = lappend(tlist, tle);
    6380         352 :             lefttree->targetlist = tlist;    /* just in case NIL before */
    6381             :         }
    6382             : 
    6383             :         /*
    6384             :          * Look up the correct sort operator from the PathKey's slightly
    6385             :          * abstracted representation.
    6386             :          */
    6387      109656 :         sortop = get_opfamily_member(pathkey->pk_opfamily,
    6388             :                                      pk_datatype,
    6389             :                                      pk_datatype,
    6390      109656 :                                      pathkey->pk_strategy);
    6391      109656 :         if (!OidIsValid(sortop))    /* should not happen */
    6392           0 :             elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
    6393             :                  pathkey->pk_strategy, pk_datatype, pk_datatype,
    6394             :                  pathkey->pk_opfamily);
    6395             : 
    6396             :         /* Add the column to the sort arrays */
    6397      109656 :         sortColIdx[numsortkeys] = tle->resno;
    6398      109656 :         sortOperators[numsortkeys] = sortop;
    6399      109656 :         collations[numsortkeys] = ec->ec_collation;
    6400      109656 :         nullsFirst[numsortkeys] = pathkey->pk_nulls_first;
    6401      109656 :         numsortkeys++;
    6402             :     }
    6403             : 
    6404             :     /* Return results */
    6405       72544 :     *p_numsortkeys = numsortkeys;
    6406       72544 :     *p_sortColIdx = sortColIdx;
    6407       72544 :     *p_sortOperators = sortOperators;
    6408       72544 :     *p_collations = collations;
    6409       72544 :     *p_nullsFirst = nullsFirst;
    6410             : 
    6411       72544 :     return lefttree;
    6412             : }
    6413             : 
    6414             : /*
    6415             :  * make_sort_from_pathkeys
    6416             :  *    Create sort plan to sort according to given pathkeys
    6417             :  *
    6418             :  *    'lefttree' is the node which yields input tuples
    6419             :  *    'pathkeys' is the list of pathkeys by which the result is to be sorted
    6420             :  *    'relids' is the set of relations required by prepare_sort_from_pathkeys()
    6421             :  */
    6422             : static Sort *
    6423       68568 : make_sort_from_pathkeys(Plan *lefttree, List *pathkeys, Relids relids)
    6424             : {
    6425             :     int         numsortkeys;
    6426             :     AttrNumber *sortColIdx;
    6427             :     Oid        *sortOperators;
    6428             :     Oid        *collations;
    6429             :     bool       *nullsFirst;
    6430             : 
    6431             :     /* Compute sort column info, and adjust lefttree as needed */
    6432       68568 :     lefttree = prepare_sort_from_pathkeys(lefttree, pathkeys,
    6433             :                                           relids,
    6434             :                                           NULL,
    6435             :                                           false,
    6436             :                                           &numsortkeys,
    6437             :                                           &sortColIdx,
    6438             :                                           &sortOperators,
    6439             :                                           &collations,
    6440             :                                           &nullsFirst);
    6441             : 
    6442             :     /* Now build the Sort node */
    6443       68568 :     return make_sort(lefttree, numsortkeys,
    6444             :                      sortColIdx, sortOperators,
    6445             :                      collations, nullsFirst);
    6446             : }
    6447             : 
    6448             : /*
    6449             :  * make_incrementalsort_from_pathkeys
    6450             :  *    Create sort plan to sort according to given pathkeys
    6451             :  *
    6452             :  *    'lefttree' is the node which yields input tuples
    6453             :  *    'pathkeys' is the list of pathkeys by which the result is to be sorted
    6454             :  *    'relids' is the set of relations required by prepare_sort_from_pathkeys()
    6455             :  *    'nPresortedCols' is the number of presorted columns in input tuples
    6456             :  */
    6457             : static IncrementalSort *
    6458         770 : make_incrementalsort_from_pathkeys(Plan *lefttree, List *pathkeys,
    6459             :                                    Relids relids, int nPresortedCols)
    6460             : {
    6461             :     int         numsortkeys;
    6462             :     AttrNumber *sortColIdx;
    6463             :     Oid        *sortOperators;
    6464             :     Oid        *collations;
    6465             :     bool       *nullsFirst;
    6466             : 
    6467             :     /* Compute sort column info, and adjust lefttree as needed */
    6468         770 :     lefttree = prepare_sort_from_pathkeys(lefttree, pathkeys,
    6469             :                                           relids,
    6470             :                                           NULL,
    6471             :                                           false,
    6472             :                                           &numsortkeys,
    6473             :                                           &sortColIdx,
    6474             :                                           &sortOperators,
    6475             :                                           &collations,
    6476             :                                           &nullsFirst);
    6477             : 
    6478             :     /* Now build the Sort node */
    6479         770 :     return make_incrementalsort(lefttree, numsortkeys, nPresortedCols,
    6480             :                                 sortColIdx, sortOperators,
    6481             :                                 collations, nullsFirst);
    6482             : }
    6483             : 
    6484             : /*
    6485             :  * make_sort_from_sortclauses
    6486             :  *    Create sort plan to sort according to given sortclauses
    6487             :  *
    6488             :  *    'sortcls' is a list of SortGroupClauses
    6489             :  *    'lefttree' is the node which yields input tuples
    6490             :  */
    6491             : Sort *
    6492           2 : make_sort_from_sortclauses(List *sortcls, Plan *lefttree)
    6493             : {
    6494           2 :     List       *sub_tlist = lefttree->targetlist;
    6495             :     ListCell   *l;
    6496             :     int         numsortkeys;
    6497             :     AttrNumber *sortColIdx;
    6498             :     Oid        *sortOperators;
    6499             :     Oid        *collations;
    6500             :     bool       *nullsFirst;
    6501             : 
    6502             :     /* Convert list-ish representation to arrays wanted by executor */
    6503           2 :     numsortkeys = list_length(sortcls);
    6504           2 :     sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
    6505           2 :     sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
    6506           2 :     collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
    6507           2 :     nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
    6508             : 
    6509           2 :     numsortkeys = 0;
    6510           4 :     foreach(l, sortcls)
    6511             :     {
    6512           2 :         SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
    6513           2 :         TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
    6514             : 
    6515           2 :         sortColIdx[numsortkeys] = tle->resno;
    6516           2 :         sortOperators[numsortkeys] = sortcl->sortop;
    6517           2 :         collations[numsortkeys] = exprCollation((Node *) tle->expr);
    6518           2 :         nullsFirst[numsortkeys] = sortcl->nulls_first;
    6519           2 :         numsortkeys++;
    6520             :     }
    6521             : 
    6522           2 :     return make_sort(lefttree, numsortkeys,
    6523             :                      sortColIdx, sortOperators,
    6524             :                      collations, nullsFirst);
    6525             : }
    6526             : 
    6527             : /*
    6528             :  * make_sort_from_groupcols
    6529             :  *    Create sort plan to sort based on grouping columns
    6530             :  *
    6531             :  * 'groupcls' is the list of SortGroupClauses
    6532             :  * 'grpColIdx' gives the column numbers to use
    6533             :  *
    6534             :  * This might look like it could be merged with make_sort_from_sortclauses,
    6535             :  * but presently we *must* use the grpColIdx[] array to locate sort columns,
    6536             :  * because the child plan's tlist is not marked with ressortgroupref info
    6537             :  * appropriate to the grouping node.  So, only the sort ordering info
    6538             :  * is used from the SortGroupClause entries.
    6539             :  */
    6540             : static Sort *
    6541         228 : make_sort_from_groupcols(List *groupcls,
    6542             :                          AttrNumber *grpColIdx,
    6543             :                          Plan *lefttree)
    6544             : {
    6545         228 :     List       *sub_tlist = lefttree->targetlist;
    6546             :     ListCell   *l;
    6547             :     int         numsortkeys;
    6548             :     AttrNumber *sortColIdx;
    6549             :     Oid        *sortOperators;
    6550             :     Oid        *collations;
    6551             :     bool       *nullsFirst;
    6552             : 
    6553             :     /* Convert list-ish representation to arrays wanted by executor */
    6554         228 :     numsortkeys = list_length(groupcls);
    6555         228 :     sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
    6556         228 :     sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
    6557         228 :     collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
    6558         228 :     nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
    6559             : 
    6560         228 :     numsortkeys = 0;
    6561         546 :     foreach(l, groupcls)
    6562             :     {
    6563         318 :         SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
    6564         318 :         TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[numsortkeys]);
    6565             : 
    6566         318 :         if (!tle)
    6567           0 :             elog(ERROR, "could not retrieve tle for sort-from-groupcols");
    6568             : 
    6569         318 :         sortColIdx[numsortkeys] = tle->resno;
    6570         318 :         sortOperators[numsortkeys] = grpcl->sortop;
    6571         318 :         collations[numsortkeys] = exprCollation((Node *) tle->expr);
    6572         318 :         nullsFirst[numsortkeys] = grpcl->nulls_first;
    6573         318 :         numsortkeys++;
    6574             :     }
    6575             : 
    6576         228 :     return make_sort(lefttree, numsortkeys,
    6577             :                      sortColIdx, sortOperators,
    6578             :                      collations, nullsFirst);
    6579             : }
    6580             : 
    6581             : static Material *
    6582        3882 : make_material(Plan *lefttree)
    6583             : {
    6584        3882 :     Material   *node = makeNode(Material);
    6585        3882 :     Plan       *plan = &node->plan;
    6586             : 
    6587        3882 :     plan->targetlist = lefttree->targetlist;
    6588        3882 :     plan->qual = NIL;
    6589        3882 :     plan->lefttree = lefttree;
    6590        3882 :     plan->righttree = NULL;
    6591             : 
    6592        3882 :     return node;
    6593             : }
    6594             : 
    6595             : /*
    6596             :  * materialize_finished_plan: stick a Material node atop a completed plan
    6597             :  *
    6598             :  * There are a couple of places where we want to attach a Material node
    6599             :  * after completion of create_plan(), without any MaterialPath path.
    6600             :  * Those places should probably be refactored someday to do this on the
    6601             :  * Path representation, but it's not worth the trouble yet.
    6602             :  */
    6603             : Plan *
    6604          72 : materialize_finished_plan(Plan *subplan)
    6605             : {
    6606             :     Plan       *matplan;
    6607             :     Path        matpath;        /* dummy for result of cost_material */
    6608             :     Cost        initplan_cost;
    6609             :     bool        unsafe_initplans;
    6610             : 
    6611          72 :     matplan = (Plan *) make_material(subplan);
    6612             : 
    6613             :     /*
    6614             :      * XXX horrid kluge: if there are any initPlans attached to the subplan,
    6615             :      * move them up to the Material node, which is now effectively the top
    6616             :      * plan node in its query level.  This prevents failure in
    6617             :      * SS_finalize_plan(), which see for comments.
    6618             :      */
    6619          72 :     matplan->initPlan = subplan->initPlan;
    6620          72 :     subplan->initPlan = NIL;
    6621             : 
    6622             :     /* Move the initplans' cost delta, as well */
    6623          72 :     SS_compute_initplan_cost(matplan->initPlan,
    6624             :                              &initplan_cost, &unsafe_initplans);
    6625          72 :     subplan->startup_cost -= initplan_cost;
    6626          72 :     subplan->total_cost -= initplan_cost;
    6627             : 
    6628             :     /* Set cost data */
    6629          72 :     cost_material(&matpath,
    6630             :                   subplan->disabled_nodes,
    6631             :                   subplan->startup_cost,
    6632             :                   subplan->total_cost,
    6633             :                   subplan->plan_rows,
    6634             :                   subplan->plan_width);
    6635          72 :     matplan->disabled_nodes = subplan->disabled_nodes;
    6636          72 :     matplan->startup_cost = matpath.startup_cost + initplan_cost;
    6637          72 :     matplan->total_cost = matpath.total_cost + initplan_cost;
    6638          72 :     matplan->plan_rows = subplan->plan_rows;
    6639          72 :     matplan->plan_width = subplan->plan_width;
    6640          72 :     matplan->parallel_aware = false;
    6641          72 :     matplan->parallel_safe = subplan->parallel_safe;
    6642             : 
    6643          72 :     return matplan;
    6644             : }
    6645             : 
    6646             : static Memoize *
    6647        1374 : make_memoize(Plan *lefttree, Oid *hashoperators, Oid *collations,
    6648             :              List *param_exprs, bool singlerow, bool binary_mode,
    6649             :              uint32 est_entries, Bitmapset *keyparamids)
    6650             : {
    6651        1374 :     Memoize    *node = makeNode(Memoize);
    6652        1374 :     Plan       *plan = &node->plan;
    6653             : 
    6654        1374 :     plan->targetlist = lefttree->targetlist;
    6655        1374 :     plan->qual = NIL;
    6656        1374 :     plan->lefttree = lefttree;
    6657        1374 :     plan->righttree = NULL;
    6658             : 
    6659        1374 :     node->numKeys = list_length(param_exprs);
    6660        1374 :     node->hashOperators = hashoperators;
    6661        1374 :     node->collations = collations;
    6662        1374 :     node->param_exprs = param_exprs;
    6663        1374 :     node->singlerow = singlerow;
    6664        1374 :     node->binary_mode = binary_mode;
    6665        1374 :     node->est_entries = est_entries;
    6666        1374 :     node->keyparamids = keyparamids;
    6667             : 
    6668        1374 :     return node;
    6669             : }
    6670             : 
    6671             : Agg *
    6672       40350 : make_agg(List *tlist, List *qual,
    6673             :          AggStrategy aggstrategy, AggSplit aggsplit,
    6674             :          int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, Oid *grpCollations,
    6675             :          List *groupingSets, List *chain, double dNumGroups,
    6676             :          Size transitionSpace, Plan *lefttree)
    6677             : {
    6678       40350 :     Agg        *node = makeNode(Agg);
    6679       40350 :     Plan       *plan = &node->plan;
    6680             :     long        numGroups;
    6681             : 
    6682             :     /* Reduce to long, but 'ware overflow! */
    6683       40350 :     numGroups = clamp_cardinality_to_long(dNumGroups);
    6684             : 
    6685       40350 :     node->aggstrategy = aggstrategy;
    6686       40350 :     node->aggsplit = aggsplit;
    6687       40350 :     node->numCols = numGroupCols;
    6688       40350 :     node->grpColIdx = grpColIdx;
    6689       40350 :     node->grpOperators = grpOperators;
    6690       40350 :     node->grpCollations = grpCollations;
    6691       40350 :     node->numGroups = numGroups;
    6692       40350 :     node->transitionSpace = transitionSpace;
    6693       40350 :     node->aggParams = NULL;      /* SS_finalize_plan() will fill this */
    6694       40350 :     node->groupingSets = groupingSets;
    6695       40350 :     node->chain = chain;
    6696             : 
    6697       40350 :     plan->qual = qual;
    6698       40350 :     plan->targetlist = tlist;
    6699       40350 :     plan->lefttree = lefttree;
    6700       40350 :     plan->righttree = NULL;
    6701             : 
    6702       40350 :     return node;
    6703             : }
    6704             : 
    6705             : static WindowAgg *
    6706        2486 : make_windowagg(List *tlist, Index winref,
    6707             :                int partNumCols, AttrNumber *partColIdx, Oid *partOperators, Oid *partCollations,
    6708             :                int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators, Oid *ordCollations,
    6709             :                int frameOptions, Node *startOffset, Node *endOffset,
    6710             :                Oid startInRangeFunc, Oid endInRangeFunc,
    6711             :                Oid inRangeColl, bool inRangeAsc, bool inRangeNullsFirst,
    6712             :                List *runCondition, List *qual, bool topWindow, Plan *lefttree)
    6713             : {
    6714        2486 :     WindowAgg  *node = makeNode(WindowAgg);
    6715        2486 :     Plan       *plan = &node->plan;
    6716             : 
    6717        2486 :     node->winref = winref;
    6718        2486 :     node->partNumCols = partNumCols;
    6719        2486 :     node->partColIdx = partColIdx;
    6720        2486 :     node->partOperators = partOperators;
    6721        2486 :     node->partCollations = partCollations;
    6722        2486 :     node->ordNumCols = ordNumCols;
    6723        2486 :     node->ordColIdx = ordColIdx;
    6724        2486 :     node->ordOperators = ordOperators;
    6725        2486 :     node->ordCollations = ordCollations;
    6726        2486 :     node->frameOptions = frameOptions;
    6727        2486 :     node->startOffset = startOffset;
    6728        2486 :     node->endOffset = endOffset;
    6729        2486 :     node->runCondition = runCondition;
    6730             :     /* a duplicate of the above for EXPLAIN */
    6731        2486 :     node->runConditionOrig = runCondition;
    6732        2486 :     node->startInRangeFunc = startInRangeFunc;
    6733        2486 :     node->endInRangeFunc = endInRangeFunc;
    6734        2486 :     node->inRangeColl = inRangeColl;
    6735        2486 :     node->inRangeAsc = inRangeAsc;
    6736        2486 :     node->inRangeNullsFirst = inRangeNullsFirst;
    6737        2486 :     node->topWindow = topWindow;
    6738             : 
    6739        2486 :     plan->targetlist = tlist;
    6740        2486 :     plan->lefttree = lefttree;
    6741        2486 :     plan->righttree = NULL;
    6742        2486 :     plan->qual = qual;
    6743             : 
    6744        2486 :     return node;
    6745             : }
    6746             : 
    6747             : static Group *
    6748         246 : make_group(List *tlist,
    6749             :            List *qual,
    6750             :            int numGroupCols,
    6751             :            AttrNumber *grpColIdx,
    6752             :            Oid *grpOperators,
    6753             :            Oid *grpCollations,
    6754             :            Plan *lefttree)
    6755             : {
    6756         246 :     Group      *node = makeNode(Group);
    6757         246 :     Plan       *plan = &node->plan;
    6758             : 
    6759         246 :     node->numCols = numGroupCols;
    6760         246 :     node->grpColIdx = grpColIdx;
    6761         246 :     node->grpOperators = grpOperators;
    6762         246 :     node->grpCollations = grpCollations;
    6763             : 
    6764         246 :     plan->qual = qual;
    6765         246 :     plan->targetlist = tlist;
    6766         246 :     plan->lefttree = lefttree;
    6767         246 :     plan->righttree = NULL;
    6768             : 
    6769         246 :     return node;
    6770             : }
    6771             : 
    6772             : /*
    6773             :  * distinctList is a list of SortGroupClauses, identifying the targetlist items
    6774             :  * that should be considered by the Unique filter.  The input path must
    6775             :  * already be sorted accordingly.
    6776             :  */
    6777             : static Unique *
    6778           2 : make_unique_from_sortclauses(Plan *lefttree, List *distinctList)
    6779             : {
    6780           2 :     Unique     *node = makeNode(Unique);
    6781           2 :     Plan       *plan = &node->plan;
    6782           2 :     int         numCols = list_length(distinctList);
    6783           2 :     int         keyno = 0;
    6784             :     AttrNumber *uniqColIdx;
    6785             :     Oid        *uniqOperators;
    6786             :     Oid        *uniqCollations;
    6787             :     ListCell   *slitem;
    6788             : 
    6789           2 :     plan->targetlist = lefttree->targetlist;
    6790           2 :     plan->qual = NIL;
    6791           2 :     plan->lefttree = lefttree;
    6792           2 :     plan->righttree = NULL;
    6793             : 
    6794             :     /*
    6795             :      * convert SortGroupClause list into arrays of attr indexes and equality
    6796             :      * operators, as wanted by executor
    6797             :      */
    6798             :     Assert(numCols > 0);
    6799           2 :     uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
    6800           2 :     uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
    6801           2 :     uniqCollations = (Oid *) palloc(sizeof(Oid) * numCols);
    6802             : 
    6803           4 :     foreach(slitem, distinctList)
    6804             :     {
    6805           2 :         SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
    6806           2 :         TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
    6807             : 
    6808           2 :         uniqColIdx[keyno] = tle->resno;
    6809           2 :         uniqOperators[keyno] = sortcl->eqop;
    6810           2 :         uniqCollations[keyno] = exprCollation((Node *) tle->expr);
    6811             :         Assert(OidIsValid(uniqOperators[keyno]));
    6812           2 :         keyno++;
    6813             :     }
    6814             : 
    6815           2 :     node->numCols = numCols;
    6816           2 :     node->uniqColIdx = uniqColIdx;
    6817           2 :     node->uniqOperators = uniqOperators;
    6818           2 :     node->uniqCollations = uniqCollations;
    6819             : 
    6820           2 :     return node;
    6821             : }
    6822             : 
    6823             : /*
    6824             :  * as above, but use pathkeys to identify the sort columns and semantics
    6825             :  */
    6826             : static Unique *
    6827        5048 : make_unique_from_pathkeys(Plan *lefttree, List *pathkeys, int numCols)
    6828             : {
    6829        5048 :     Unique     *node = makeNode(Unique);
    6830        5048 :     Plan       *plan = &node->plan;
    6831        5048 :     int         keyno = 0;
    6832             :     AttrNumber *uniqColIdx;
    6833             :     Oid        *uniqOperators;
    6834             :     Oid        *uniqCollations;
    6835             :     ListCell   *lc;
    6836             : 
    6837        5048 :     plan->targetlist = lefttree->targetlist;
    6838        5048 :     plan->qual = NIL;
    6839        5048 :     plan->lefttree = lefttree;
    6840        5048 :     plan->righttree = NULL;
    6841             : 
    6842             :     /*
    6843             :      * Convert pathkeys list into arrays of attr indexes and equality
    6844             :      * operators, as wanted by executor.  This has a lot in common with
    6845             :      * prepare_sort_from_pathkeys ... maybe unify sometime?
    6846             :      */
    6847             :     Assert(numCols >= 0 && numCols <= list_length(pathkeys));
    6848        5048 :     uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
    6849        5048 :     uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
    6850        5048 :     uniqCollations = (Oid *) palloc(sizeof(Oid) * numCols);
    6851             : 
    6852       16684 :     foreach(lc, pathkeys)
    6853             :     {
    6854       11678 :         PathKey    *pathkey = (PathKey *) lfirst(lc);
    6855       11678 :         EquivalenceClass *ec = pathkey->pk_eclass;
    6856             :         EquivalenceMember *em;
    6857       11678 :         TargetEntry *tle = NULL;
    6858       11678 :         Oid         pk_datatype = InvalidOid;
    6859             :         Oid         eqop;
    6860             :         ListCell   *j;
    6861             : 
    6862             :         /* Ignore pathkeys beyond the specified number of columns */
    6863       11678 :         if (keyno >= numCols)
    6864          42 :             break;
    6865             : 
    6866       11636 :         if (ec->ec_has_volatile)
    6867             :         {
    6868             :             /*
    6869             :              * If the pathkey's EquivalenceClass is volatile, then it must
    6870             :              * have come from an ORDER BY clause, and we have to match it to
    6871             :              * that same targetlist entry.
    6872             :              */
    6873          30 :             if (ec->ec_sortref == 0) /* can't happen */
    6874           0 :                 elog(ERROR, "volatile EquivalenceClass has no sortref");
    6875          30 :             tle = get_sortgroupref_tle(ec->ec_sortref, plan->targetlist);
    6876             :             Assert(tle);
    6877             :             Assert(list_length(ec->ec_members) == 1);
    6878          30 :             pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
    6879             :         }
    6880             :         else
    6881             :         {
    6882             :             /*
    6883             :              * Otherwise, we can use any non-constant expression listed in the
    6884             :              * pathkey's EquivalenceClass.  For now, we take the first tlist
    6885             :              * item found in the EC.
    6886             :              */
    6887       22578 :             foreach(j, plan->targetlist)
    6888             :             {
    6889       22578 :                 tle = (TargetEntry *) lfirst(j);
    6890       22578 :                 em = find_ec_member_matching_expr(ec, tle->expr, NULL);
    6891       22578 :                 if (em)
    6892             :                 {
    6893             :                     /* found expr already in tlist */
    6894       11606 :                     pk_datatype = em->em_datatype;
    6895       11606 :                     break;
    6896             :                 }
    6897       10972 :                 tle = NULL;
    6898             :             }
    6899             :         }
    6900             : 
    6901       11636 :         if (!tle)
    6902           0 :             elog(ERROR, "could not find pathkey item to sort");
    6903             : 
    6904             :         /*
    6905             :          * Look up the correct equality operator from the PathKey's slightly
    6906             :          * abstracted representation.
    6907             :          */
    6908       11636 :         eqop = get_opfamily_member(pathkey->pk_opfamily,
    6909             :                                    pk_datatype,
    6910             :                                    pk_datatype,
    6911             :                                    BTEqualStrategyNumber);
    6912       11636 :         if (!OidIsValid(eqop))  /* should not happen */
    6913           0 :             elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
    6914             :                  BTEqualStrategyNumber, pk_datatype, pk_datatype,
    6915             :                  pathkey->pk_opfamily);
    6916             : 
    6917       11636 :         uniqColIdx[keyno] = tle->resno;
    6918       11636 :         uniqOperators[keyno] = eqop;
    6919       11636 :         uniqCollations[keyno] = ec->ec_collation;
    6920             : 
    6921       11636 :         keyno++;
    6922             :     }
    6923             : 
    6924        5048 :     node->numCols = numCols;
    6925        5048 :     node->uniqColIdx = uniqColIdx;
    6926        5048 :     node->uniqOperators = uniqOperators;
    6927        5048 :     node->uniqCollations = uniqCollations;
    6928             : 
    6929        5048 :     return node;
    6930             : }
    6931             : 
    6932             : static Gather *
    6933         934 : make_gather(List *qptlist,
    6934             :             List *qpqual,
    6935             :             int nworkers,
    6936             :             int rescan_param,
    6937             :             bool single_copy,
    6938             :             Plan *subplan)
    6939             : {
    6940         934 :     Gather     *node = makeNode(Gather);
    6941         934 :     Plan       *plan = &node->plan;
    6942             : 
    6943         934 :     plan->targetlist = qptlist;
    6944         934 :     plan->qual = qpqual;
    6945         934 :     plan->lefttree = subplan;
    6946         934 :     plan->righttree = NULL;
    6947         934 :     node->num_workers = nworkers;
    6948         934 :     node->rescan_param = rescan_param;
    6949         934 :     node->single_copy = single_copy;
    6950         934 :     node->invisible = false;
    6951         934 :     node->initParam = NULL;
    6952             : 
    6953         934 :     return node;
    6954             : }
    6955             : 
    6956             : /*
    6957             :  * groupList is a list of SortGroupClauses, identifying the targetlist
    6958             :  * items that should be considered by the SetOp filter.  The input plans must
    6959             :  * already be sorted accordingly, if we're doing SETOP_SORTED mode.
    6960             :  */
    6961             : static SetOp *
    6962         680 : make_setop(SetOpCmd cmd, SetOpStrategy strategy,
    6963             :            List *tlist, Plan *lefttree, Plan *righttree,
    6964             :            List *groupList, long numGroups)
    6965             : {
    6966         680 :     SetOp      *node = makeNode(SetOp);
    6967         680 :     Plan       *plan = &node->plan;
    6968         680 :     int         numCols = list_length(groupList);
    6969         680 :     int         keyno = 0;
    6970             :     AttrNumber *cmpColIdx;
    6971             :     Oid        *cmpOperators;
    6972             :     Oid        *cmpCollations;
    6973             :     bool       *cmpNullsFirst;
    6974             :     ListCell   *slitem;
    6975             : 
    6976         680 :     plan->targetlist = tlist;
    6977         680 :     plan->qual = NIL;
    6978         680 :     plan->lefttree = lefttree;
    6979         680 :     plan->righttree = righttree;
    6980             : 
    6981             :     /*
    6982             :      * convert SortGroupClause list into arrays of attr indexes and comparison
    6983             :      * operators, as wanted by executor
    6984             :      */
    6985         680 :     cmpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
    6986         680 :     cmpOperators = (Oid *) palloc(sizeof(Oid) * numCols);
    6987         680 :     cmpCollations = (Oid *) palloc(sizeof(Oid) * numCols);
    6988         680 :     cmpNullsFirst = (bool *) palloc(sizeof(bool) * numCols);
    6989             : 
    6990        3666 :     foreach(slitem, groupList)
    6991             :     {
    6992        2986 :         SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
    6993        2986 :         TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
    6994             : 
    6995        2986 :         cmpColIdx[keyno] = tle->resno;
    6996        2986 :         if (strategy == SETOP_HASHED)
    6997        1084 :             cmpOperators[keyno] = sortcl->eqop;
    6998             :         else
    6999        1902 :             cmpOperators[keyno] = sortcl->sortop;
    7000             :         Assert(OidIsValid(cmpOperators[keyno]));
    7001        2986 :         cmpCollations[keyno] = exprCollation((Node *) tle->expr);
    7002        2986 :         cmpNullsFirst[keyno] = sortcl->nulls_first;
    7003        2986 :         keyno++;
    7004             :     }
    7005             : 
    7006         680 :     node->cmd = cmd;
    7007         680 :     node->strategy = strategy;
    7008         680 :     node->numCols = numCols;
    7009         680 :     node->cmpColIdx = cmpColIdx;
    7010         680 :     node->cmpOperators = cmpOperators;
    7011         680 :     node->cmpCollations = cmpCollations;
    7012         680 :     node->cmpNullsFirst = cmpNullsFirst;
    7013         680 :     node->numGroups = numGroups;
    7014             : 
    7015         680 :     return node;
    7016             : }
    7017             : 
    7018             : /*
    7019             :  * make_lockrows
    7020             :  *    Build a LockRows plan node
    7021             :  */
    7022             : static LockRows *
    7023        7846 : make_lockrows(Plan *lefttree, List *rowMarks, int epqParam)
    7024             : {
    7025        7846 :     LockRows   *node = makeNode(LockRows);
    7026        7846 :     Plan       *plan = &node->plan;
    7027             : 
    7028        7846 :     plan->targetlist = lefttree->targetlist;
    7029        7846 :     plan->qual = NIL;
    7030        7846 :     plan->lefttree = lefttree;
    7031        7846 :     plan->righttree = NULL;
    7032             : 
    7033        7846 :     node->rowMarks = rowMarks;
    7034        7846 :     node->epqParam = epqParam;
    7035             : 
    7036        7846 :     return node;
    7037             : }
    7038             : 
    7039             : /*
    7040             :  * make_limit
    7041             :  *    Build a Limit plan node
    7042             :  */
    7043             : Limit *
    7044        4560 : make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount,
    7045             :            LimitOption limitOption, int uniqNumCols, AttrNumber *uniqColIdx,
    7046             :            Oid *uniqOperators, Oid *uniqCollations)
    7047             : {
    7048        4560 :     Limit      *node = makeNode(Limit);
    7049        4560 :     Plan       *plan = &node->plan;
    7050             : 
    7051        4560 :     plan->targetlist = lefttree->targetlist;
    7052        4560 :     plan->qual = NIL;
    7053        4560 :     plan->lefttree = lefttree;
    7054        4560 :     plan->righttree = NULL;
    7055             : 
    7056        4560 :     node->limitOffset = limitOffset;
    7057        4560 :     node->limitCount = limitCount;
    7058        4560 :     node->limitOption = limitOption;
    7059        4560 :     node->uniqNumCols = uniqNumCols;
    7060        4560 :     node->uniqColIdx = uniqColIdx;
    7061        4560 :     node->uniqOperators = uniqOperators;
    7062        4560 :     node->uniqCollations = uniqCollations;
    7063             : 
    7064        4560 :     return node;
    7065             : }
    7066             : 
    7067             : /*
    7068             :  * make_result
    7069             :  *    Build a Result plan node
    7070             :  */
    7071             : static Result *
    7072      224812 : make_result(List *tlist,
    7073             :             Node *resconstantqual,
    7074             :             Plan *subplan)
    7075             : {
    7076      224812 :     Result     *node = makeNode(Result);
    7077      224812 :     Plan       *plan = &node->plan;
    7078             : 
    7079      224812 :     plan->targetlist = tlist;
    7080      224812 :     plan->qual = NIL;
    7081      224812 :     plan->lefttree = subplan;
    7082      224812 :     plan->righttree = NULL;
    7083      224812 :     node->resconstantqual = resconstantqual;
    7084             : 
    7085      224812 :     return node;
    7086             : }
    7087             : 
    7088             : /*
    7089             :  * make_project_set
    7090             :  *    Build a ProjectSet plan node
    7091             :  */
    7092             : static ProjectSet *
    7093        8734 : make_project_set(List *tlist,
    7094             :                  Plan *subplan)
    7095             : {
    7096        8734 :     ProjectSet *node = makeNode(ProjectSet);
    7097        8734 :     Plan       *plan = &node->plan;
    7098             : 
    7099        8734 :     plan->targetlist = tlist;
    7100        8734 :     plan->qual = NIL;
    7101        8734 :     plan->lefttree = subplan;
    7102        8734 :     plan->righttree = NULL;
    7103             : 
    7104        8734 :     return node;
    7105             : }
    7106             : 
    7107             : /*
    7108             :  * make_modifytable
    7109             :  *    Build a ModifyTable plan node
    7110             :  */
    7111             : static ModifyTable *
    7112       90912 : make_modifytable(PlannerInfo *root, Plan *subplan,
    7113             :                  CmdType operation, bool canSetTag,
    7114             :                  Index nominalRelation, Index rootRelation,
    7115             :                  bool partColsUpdated,
    7116             :                  List *resultRelations,
    7117             :                  List *updateColnosLists,
    7118             :                  List *withCheckOptionLists, List *returningLists,
    7119             :                  List *rowMarks, OnConflictExpr *onconflict,
    7120             :                  List *mergeActionLists, List *mergeJoinConditions,
    7121             :                  int epqParam)
    7122             : {
    7123       90912 :     ModifyTable *node = makeNode(ModifyTable);
    7124       90912 :     bool        returning_old_or_new = false;
    7125       90912 :     bool        returning_old_or_new_valid = false;
    7126             :     List       *fdw_private_list;
    7127             :     Bitmapset  *direct_modify_plans;
    7128             :     ListCell   *lc;
    7129             :     int         i;
    7130             : 
    7131             :     Assert(operation == CMD_MERGE ||
    7132             :            (operation == CMD_UPDATE ?
    7133             :             list_length(resultRelations) == list_length(updateColnosLists) :
    7134             :             updateColnosLists == NIL));
    7135             :     Assert(withCheckOptionLists == NIL ||
    7136             :            list_length(resultRelations) == list_length(withCheckOptionLists));
    7137             :     Assert(returningLists == NIL ||
    7138             :            list_length(resultRelations) == list_length(returningLists));
    7139             : 
    7140       90912 :     node->plan.lefttree = subplan;
    7141       90912 :     node->plan.righttree = NULL;
    7142       90912 :     node->plan.qual = NIL;
    7143             :     /* setrefs.c will fill in the targetlist, if needed */
    7144       90912 :     node->plan.targetlist = NIL;
    7145             : 
    7146       90912 :     node->operation = operation;
    7147       90912 :     node->canSetTag = canSetTag;
    7148       90912 :     node->nominalRelation = nominalRelation;
    7149       90912 :     node->rootRelation = rootRelation;
    7150       90912 :     node->partColsUpdated = partColsUpdated;
    7151       90912 :     node->resultRelations = resultRelations;
    7152       90912 :     if (!onconflict)
    7153             :     {
    7154       89098 :         node->onConflictAction = ONCONFLICT_NONE;
    7155       89098 :         node->onConflictSet = NIL;
    7156       89098 :         node->onConflictCols = NIL;
    7157       89098 :         node->onConflictWhere = NULL;
    7158       89098 :         node->arbiterIndexes = NIL;
    7159       89098 :         node->exclRelRTI = 0;
    7160       89098 :         node->exclRelTlist = NIL;
    7161             :     }
    7162             :     else
    7163             :     {
    7164        1814 :         node->onConflictAction = onconflict->action;
    7165             : 
    7166             :         /*
    7167             :          * Here we convert the ON CONFLICT UPDATE tlist, if any, to the
    7168             :          * executor's convention of having consecutive resno's.  The actual
    7169             :          * target column numbers are saved in node->onConflictCols.  (This
    7170             :          * could be done earlier, but there seems no need to.)
    7171             :          */
    7172        1814 :         node->onConflictSet = onconflict->onConflictSet;
    7173        1814 :         node->onConflictCols =
    7174        1814 :             extract_update_targetlist_colnos(node->onConflictSet);
    7175        1814 :         node->onConflictWhere = onconflict->onConflictWhere;
    7176             : 
    7177             :         /*
    7178             :          * If a set of unique index inference elements was provided (an
    7179             :          * INSERT...ON CONFLICT "inference specification"), then infer
    7180             :          * appropriate unique indexes (or throw an error if none are
    7181             :          * available).
    7182             :          */
    7183        1814 :         node->arbiterIndexes = infer_arbiter_indexes(root);
    7184             : 
    7185        1422 :         node->exclRelRTI = onconflict->exclRelIndex;
    7186        1422 :         node->exclRelTlist = onconflict->exclRelTlist;
    7187             :     }
    7188       90520 :     node->updateColnosLists = updateColnosLists;
    7189       90520 :     node->withCheckOptionLists = withCheckOptionLists;
    7190       90520 :     node->returningOldAlias = root->parse->returningOldAlias;
    7191       90520 :     node->returningNewAlias = root->parse->returningNewAlias;
    7192       90520 :     node->returningLists = returningLists;
    7193       90520 :     node->rowMarks = rowMarks;
    7194       90520 :     node->mergeActionLists = mergeActionLists;
    7195       90520 :     node->mergeJoinConditions = mergeJoinConditions;
    7196       90520 :     node->epqParam = epqParam;
    7197             : 
    7198             :     /*
    7199             :      * For each result relation that is a foreign table, allow the FDW to
    7200             :      * construct private plan data, and accumulate it all into a list.
    7201             :      */
    7202       90520 :     fdw_private_list = NIL;
    7203       90520 :     direct_modify_plans = NULL;
    7204       90520 :     i = 0;
    7205      183398 :     foreach(lc, resultRelations)
    7206             :     {
    7207       92882 :         Index       rti = lfirst_int(lc);
    7208             :         FdwRoutine *fdwroutine;
    7209             :         List       *fdw_private;
    7210             :         bool        direct_modify;
    7211             : 
    7212             :         /*
    7213             :          * If possible, we want to get the FdwRoutine from our RelOptInfo for
    7214             :          * the table.  But sometimes we don't have a RelOptInfo and must get
    7215             :          * it the hard way.  (In INSERT, the target relation is not scanned,
    7216             :          * so it's not a baserel; and there are also corner cases for
    7217             :          * updatable views where the target rel isn't a baserel.)
    7218             :          */
    7219       92882 :         if (rti < root->simple_rel_array_size &&
    7220       92882 :             root->simple_rel_array[rti] != NULL)
    7221       21522 :         {
    7222       21522 :             RelOptInfo *resultRel = root->simple_rel_array[rti];
    7223             : 
    7224       21522 :             fdwroutine = resultRel->fdwroutine;
    7225             :         }
    7226             :         else
    7227             :         {
    7228       71360 :             RangeTblEntry *rte = planner_rt_fetch(rti, root);
    7229             : 
    7230       71360 :             if (rte->rtekind == RTE_RELATION &&
    7231       71360 :                 rte->relkind == RELKIND_FOREIGN_TABLE)
    7232             :             {
    7233             :                 /* Check if the access to foreign tables is restricted */
    7234         178 :                 if (unlikely((restrict_nonsystem_relation_kind & RESTRICT_RELKIND_FOREIGN_TABLE) != 0))
    7235             :                 {
    7236             :                     /* there must not be built-in foreign tables */
    7237             :                     Assert(rte->relid >= FirstNormalObjectId);
    7238           2 :                     ereport(ERROR,
    7239             :                             (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    7240             :                              errmsg("access to non-system foreign table is restricted")));
    7241             :                 }
    7242             : 
    7243         176 :                 fdwroutine = GetFdwRoutineByRelId(rte->relid);
    7244             :             }
    7245             :             else
    7246       71182 :                 fdwroutine = NULL;
    7247             :         }
    7248             : 
    7249             :         /*
    7250             :          * MERGE is not currently supported for foreign tables.  We already
    7251             :          * checked that when the table mentioned in the query is foreign; but
    7252             :          * we can still get here if a partitioned table has a foreign table as
    7253             :          * partition.  Disallow that now, to avoid an uglier error message
    7254             :          * later.
    7255             :          */
    7256       92880 :         if (operation == CMD_MERGE && fdwroutine != NULL)
    7257             :         {
    7258           2 :             RangeTblEntry *rte = planner_rt_fetch(rti, root);
    7259             : 
    7260           2 :             ereport(ERROR,
    7261             :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    7262             :                     errmsg("cannot execute MERGE on relation \"%s\"",
    7263             :                            get_rel_name(rte->relid)),
    7264             :                     errdetail_relkind_not_supported(rte->relkind));
    7265             :         }
    7266             : 
    7267             :         /*
    7268             :          * Try to modify the foreign table directly if (1) the FDW provides
    7269             :          * callback functions needed for that and (2) there are no local
    7270             :          * structures that need to be run for each modified row: row-level
    7271             :          * triggers on the foreign table, stored generated columns, WITH CHECK
    7272             :          * OPTIONs from parent views, or Vars returning OLD/NEW in the
    7273             :          * RETURNING list.
    7274             :          */
    7275       92878 :         direct_modify = false;
    7276       92878 :         if (fdwroutine != NULL &&
    7277         540 :             fdwroutine->PlanDirectModify != NULL &&
    7278         530 :             fdwroutine->BeginDirectModify != NULL &&
    7279         530 :             fdwroutine->IterateDirectModify != NULL &&
    7280         530 :             fdwroutine->EndDirectModify != NULL &&
    7281         498 :             withCheckOptionLists == NIL &&
    7282         498 :             !has_row_triggers(root, rti, operation) &&
    7283         420 :             !has_stored_generated_columns(root, rti))
    7284             :         {
    7285             :             /* returning_old_or_new is the same for all result relations */
    7286         402 :             if (!returning_old_or_new_valid)
    7287             :             {
    7288             :                 returning_old_or_new =
    7289         386 :                     contain_vars_returning_old_or_new((Node *)
    7290         386 :                                                       root->parse->returningList);
    7291         386 :                 returning_old_or_new_valid = true;
    7292             :             }
    7293         402 :             if (!returning_old_or_new)
    7294         388 :                 direct_modify = fdwroutine->PlanDirectModify(root, node, rti, i);
    7295             :         }
    7296       92878 :         if (direct_modify)
    7297         208 :             direct_modify_plans = bms_add_member(direct_modify_plans, i);
    7298             : 
    7299       92878 :         if (!direct_modify &&
    7300         332 :             fdwroutine != NULL &&
    7301         332 :             fdwroutine->PlanForeignModify != NULL)
    7302         322 :             fdw_private = fdwroutine->PlanForeignModify(root, node, rti, i);
    7303             :         else
    7304       92556 :             fdw_private = NIL;
    7305       92878 :         fdw_private_list = lappend(fdw_private_list, fdw_private);
    7306       92878 :         i++;
    7307             :     }
    7308       90516 :     node->fdwPrivLists = fdw_private_list;
    7309       90516 :     node->fdwDirectModifyPlans = direct_modify_plans;
    7310             : 
    7311       90516 :     return node;
    7312             : }
    7313             : 
    7314             : /*
    7315             :  * is_projection_capable_path
    7316             :  *      Check whether a given Path node is able to do projection.
    7317             :  */
    7318             : bool
    7319      719558 : is_projection_capable_path(Path *path)
    7320             : {
    7321             :     /* Most plan types can project, so just list the ones that can't */
    7322      719558 :     switch (path->pathtype)
    7323             :     {
    7324         970 :         case T_Hash:
    7325             :         case T_Material:
    7326             :         case T_Memoize:
    7327             :         case T_Sort:
    7328             :         case T_IncrementalSort:
    7329             :         case T_Unique:
    7330             :         case T_SetOp:
    7331             :         case T_LockRows:
    7332             :         case T_Limit:
    7333             :         case T_ModifyTable:
    7334             :         case T_MergeAppend:
    7335             :         case T_RecursiveUnion:
    7336         970 :             return false;
    7337           0 :         case T_CustomScan:
    7338           0 :             if (castNode(CustomPath, path)->flags & CUSTOMPATH_SUPPORT_PROJECTION)
    7339           0 :                 return true;
    7340           0 :             return false;
    7341        1942 :         case T_Append:
    7342             : 
    7343             :             /*
    7344             :              * Append can't project, but if an AppendPath is being used to
    7345             :              * represent a dummy path, what will actually be generated is a
    7346             :              * Result which can project.
    7347             :              */
    7348        1942 :             return IS_DUMMY_APPEND(path);
    7349        3142 :         case T_ProjectSet:
    7350             : 
    7351             :             /*
    7352             :              * Although ProjectSet certainly projects, say "no" because we
    7353             :              * don't want the planner to randomly replace its tlist with
    7354             :              * something else; the SRFs have to stay at top level.  This might
    7355             :              * get relaxed later.
    7356             :              */
    7357        3142 :             return false;
    7358      713504 :         default:
    7359      713504 :             break;
    7360             :     }
    7361      713504 :     return true;
    7362             : }
    7363             : 
    7364             : /*
    7365             :  * is_projection_capable_plan
    7366             :  *      Check whether a given Plan node is able to do projection.
    7367             :  */
    7368             : bool
    7369         446 : is_projection_capable_plan(Plan *plan)
    7370             : {
    7371             :     /* Most plan types can project, so just list the ones that can't */
    7372         446 :     switch (nodeTag(plan))
    7373             :     {
    7374          36 :         case T_Hash:
    7375             :         case T_Material:
    7376             :         case T_Memoize:
    7377             :         case T_Sort:
    7378             :         case T_Unique:
    7379             :         case T_SetOp:
    7380             :         case T_LockRows:
    7381             :         case T_Limit:
    7382             :         case T_ModifyTable:
    7383             :         case T_Append:
    7384             :         case T_MergeAppend:
    7385             :         case T_RecursiveUnion:
    7386          36 :             return false;
    7387           0 :         case T_CustomScan:
    7388           0 :             if (((CustomScan *) plan)->flags & CUSTOMPATH_SUPPORT_PROJECTION)
    7389           0 :                 return true;
    7390           0 :             return false;
    7391           0 :         case T_ProjectSet:
    7392             : 
    7393             :             /*
    7394             :              * Although ProjectSet certainly projects, say "no" because we
    7395             :              * don't want the planner to randomly replace its tlist with
    7396             :              * something else; the SRFs have to stay at top level.  This might
    7397             :              * get relaxed later.
    7398             :              */
    7399           0 :             return false;
    7400         410 :         default:
    7401         410 :             break;
    7402             :     }
    7403         410 :     return true;
    7404             : }

Generated by: LCOV version 1.14