LCOV - code coverage report
Current view: top level - src/backend/optimizer/plan - createplan.c (source / functions) Coverage Total Hit
Test: Code coverage Lines: 91.2 % 3340 3047
Test Date: 2026-01-26 10:56:24 Functions: 96.5 % 114 110
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 64.9 % 1363 884

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

Generated by: LCOV version 2.3.2-1