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: a2387c32f2f8a1643c7d71b951587e6bcb2d4744 vs 371a302eecdc82274b0ae2967d18fd726a0aa6a1 Lines: 95.3 % 2408 2296 17 95 1 54 2241 5 123
Current Date: 2025-10-26 12:31:50 -0700 Functions: 98.2 % 114 112 1 1 16 96 5
Baseline: lcov-20251027-010456-baseline Branches: 74.1 % 1277 946 6 7 318 1 22 923
Baseline Date: 2025-10-26 11:01:32 +1300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 100.0 % 144 144 54 90
(360..) days: 95.1 % 2264 2152 17 95 1 2151
Function coverage date bins:
(30,360] days: 100.0 % 6 6 4 2
(360..) days: 98.1 % 108 106 1 1 12 94
Branch coverage date bins:
(30,360] days: 83.8 % 74 62 6 6 22 40
(360..) days: 73.5 % 1203 884 7 312 1 883

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

Generated by: LCOV version 2.4-beta