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