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