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