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