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