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