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