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