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