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