LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/plan - createplan.c (source / functions) Coverage Total Hit UNC LBC UBC GBC GNC CBC DUB DCB
Current: bed3ffbf9d952be6c7d739d068cdce44c046dfb7 vs 574581b50ac9c63dd9e4abebb731a3b67e5b50f6 Lines: 95.4 % 2411 2299 17 95 1 76 2222 5 143
Current Date: 2026-05-05 10:23:31 +0900 Functions: 98.2 % 114 112 1 1 24 88 5
Baseline: lcov-20260505-025707-baseline Branches: 74.2 % 1277 947 6 7 317 2 22 923 24 50
Baseline Date: 2026-05-05 10:27:06 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 109 109 76 33
(360..) days: 95.1 % 2301 2189 17 95 1 2188
Function coverage date bins:
(30,360] days: 100.0 % 4 4 4
(360..) days: 98.2 % 110 108 1 1 20 88
Branch coverage date bins:
(30,360] days: 83.9 % 56 47 6 3 22 25
(360..) days: 73.7 % 1221 900 7 314 2 898

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

Generated by: LCOV version 2.5.0-beta