LCOV - code coverage report
Current view: top level - src/backend/optimizer/plan - createplan.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 2015 2107 95.6 %
Date: 2019-07-19 13:07:20 Functions: 106 107 99.1 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13