LCOV - code coverage report
Current view: top level - src/backend/optimizer/plan - createplan.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 2192 2305 95.1 %
Date: 2025-08-31 15:18:31 Functions: 111 113 98.2 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.16