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

Generated by: LCOV version 1.13