LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/plan - createplan.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC EUB ECB DUB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 95.8 % 2407 2306 2 20 54 25 21 1068 21 1196 53 1070 2 20
Current Date: 2023-04-08 15:15:32 Functions: 99.1 % 114 113 1 103 1 9 1 103
Baseline: 15
Baseline Date: 2023-04-08 15:09:40
Legend: Lines: hit not hit

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

Generated by: LCOV version v1.16-55-g56c0a2a