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