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

Generated by: LCOV version 1.13