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