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