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