1 /*-------------------------------------------------------------------------
4 * Routines to create the desired plan for processing a query.
5 * Planning is complete, we just need to convert the selected
8 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
13 * src/backend/optimizer/plan/createplan.c
15 *-------------------------------------------------------------------------
22 #include "access/stratnum.h"
23 #include "access/sysattr.h"
24 #include "catalog/pg_class.h"
25 #include "foreign/fdwapi.h"
26 #include "miscadmin.h"
27 #include "nodes/extensible.h"
28 #include "nodes/makefuncs.h"
29 #include "nodes/nodeFuncs.h"
30 #include "optimizer/clauses.h"
31 #include "optimizer/cost.h"
32 #include "optimizer/paths.h"
33 #include "optimizer/placeholder.h"
34 #include "optimizer/plancat.h"
35 #include "optimizer/planmain.h"
36 #include "optimizer/planner.h"
37 #include "optimizer/predtest.h"
38 #include "optimizer/restrictinfo.h"
39 #include "optimizer/subselect.h"
40 #include "optimizer/tlist.h"
41 #include "optimizer/var.h"
42 #include "parser/parse_clause.h"
43 #include "parser/parsetree.h"
44 #include "utils/lsyscache.h"
48 * Flag bits that can appear in the flags argument of create_plan_recurse().
49 * These can be OR-ed together.
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.
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.
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.
66 #define CP_EXACT_TLIST 0x0001 /* Plan must return specified tlist */
67 #define CP_SMALL_TLIST 0x0002 /* Prefer narrower tlists */
68 #define CP_LABEL_TLIST 0x0004 /* tlist must contain sortgrouprefs */
71 static Plan *create_plan_recurse(PlannerInfo *root, Path *best_path,
73 static Plan *create_scan_plan(PlannerInfo *root, Path *best_path,
75 static List *build_path_tlist(PlannerInfo *root, Path *path);
76 static bool use_physical_tlist(PlannerInfo *root, Path *path, int flags);
77 static List *get_gating_quals(PlannerInfo *root, List *quals);
78 static Plan *create_gating_plan(PlannerInfo *root, Path *path, Plan *plan,
80 static Plan *create_join_plan(PlannerInfo *root, JoinPath *best_path);
81 static Plan *create_append_plan(PlannerInfo *root, AppendPath *best_path);
82 static Plan *create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path);
83 static Result *create_result_plan(PlannerInfo *root, ResultPath *best_path);
84 static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path,
86 static Plan *create_unique_plan(PlannerInfo *root, UniquePath *best_path,
88 static Gather *create_gather_plan(PlannerInfo *root, GatherPath *best_path);
89 static Plan *create_projection_plan(PlannerInfo *root, ProjectionPath *best_path);
90 static Plan *inject_projection_plan(Plan *subplan, List *tlist);
91 static Sort *create_sort_plan(PlannerInfo *root, SortPath *best_path, int flags);
92 static Group *create_group_plan(PlannerInfo *root, GroupPath *best_path);
93 static Unique *create_upper_unique_plan(PlannerInfo *root, UpperUniquePath *best_path,
95 static Agg *create_agg_plan(PlannerInfo *root, AggPath *best_path);
96 static Plan *create_groupingsets_plan(PlannerInfo *root, GroupingSetsPath *best_path);
97 static Result *create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path);
98 static WindowAgg *create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path);
99 static SetOp *create_setop_plan(PlannerInfo *root, SetOpPath *best_path,
101 static RecursiveUnion *create_recursiveunion_plan(PlannerInfo *root, RecursiveUnionPath *best_path);
102 static void get_column_info_for_window(PlannerInfo *root, WindowClause *wc,
104 int numSortCols, AttrNumber *sortColIdx,
106 AttrNumber **partColIdx,
109 AttrNumber **ordColIdx,
111 static LockRows *create_lockrows_plan(PlannerInfo *root, LockRowsPath *best_path,
113 static ModifyTable *create_modifytable_plan(PlannerInfo *root, ModifyTablePath *best_path);
114 static Limit *create_limit_plan(PlannerInfo *root, LimitPath *best_path,
116 static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path,
117 List *tlist, List *scan_clauses);
118 static SampleScan *create_samplescan_plan(PlannerInfo *root, Path *best_path,
119 List *tlist, List *scan_clauses);
120 static Scan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path,
121 List *tlist, List *scan_clauses, bool indexonly);
122 static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
123 BitmapHeapPath *best_path,
124 List *tlist, List *scan_clauses);
125 static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
126 List **qual, List **indexqual, List **indexECs);
127 static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
128 List *tlist, List *scan_clauses);
129 static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root,
130 SubqueryScanPath *best_path,
131 List *tlist, List *scan_clauses);
132 static FunctionScan *create_functionscan_plan(PlannerInfo *root, Path *best_path,
133 List *tlist, List *scan_clauses);
134 static ValuesScan *create_valuesscan_plan(PlannerInfo *root, Path *best_path,
135 List *tlist, List *scan_clauses);
136 static CteScan *create_ctescan_plan(PlannerInfo *root, Path *best_path,
137 List *tlist, List *scan_clauses);
138 static WorkTableScan *create_worktablescan_plan(PlannerInfo *root, Path *best_path,
139 List *tlist, List *scan_clauses);
140 static ForeignScan *create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
141 List *tlist, List *scan_clauses);
142 static CustomScan *create_customscan_plan(PlannerInfo *root,
143 CustomPath *best_path,
144 List *tlist, List *scan_clauses);
145 static NestLoop *create_nestloop_plan(PlannerInfo *root, NestPath *best_path);
146 static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path);
147 static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path);
148 static Node *replace_nestloop_params(PlannerInfo *root, Node *expr);
149 static Node *replace_nestloop_params_mutator(Node *node, PlannerInfo *root);
150 static void process_subquery_nestloop_params(PlannerInfo *root,
151 List *subplan_params);
152 static List *fix_indexqual_references(PlannerInfo *root, IndexPath *index_path);
153 static List *fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path);
154 static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol);
155 static List *get_switched_clauses(List *clauses, Relids outerrelids);
156 static List *order_qual_clauses(PlannerInfo *root, List *clauses);
157 static void copy_generic_path_info(Plan *dest, Path *src);
158 static void copy_plan_costsize(Plan *dest, Plan *src);
159 static void label_sort_with_costsize(PlannerInfo *root, Sort *plan,
160 double limit_tuples);
161 static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
162 static SampleScan *make_samplescan(List *qptlist, List *qpqual, Index scanrelid,
163 TableSampleClause *tsc);
164 static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
165 Oid indexid, List *indexqual, List *indexqualorig,
166 List *indexorderby, List *indexorderbyorig,
167 List *indexorderbyops,
168 ScanDirection indexscandir);
169 static IndexOnlyScan *make_indexonlyscan(List *qptlist, List *qpqual,
170 Index scanrelid, Oid indexid,
171 List *indexqual, List *indexorderby,
173 ScanDirection indexscandir);
174 static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid,
176 List *indexqualorig);
177 static BitmapHeapScan *make_bitmap_heapscan(List *qptlist,
180 List *bitmapqualorig,
182 static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
184 static SubqueryScan *make_subqueryscan(List *qptlist,
188 static FunctionScan *make_functionscan(List *qptlist, List *qpqual,
189 Index scanrelid, List *functions, bool funcordinality);
190 static ValuesScan *make_valuesscan(List *qptlist, List *qpqual,
191 Index scanrelid, List *values_lists);
192 static CteScan *make_ctescan(List *qptlist, List *qpqual,
193 Index scanrelid, int ctePlanId, int cteParam);
194 static WorkTableScan *make_worktablescan(List *qptlist, List *qpqual,
195 Index scanrelid, int wtParam);
196 static Append *make_append(List *appendplans, List *tlist);
197 static RecursiveUnion *make_recursive_union(List *tlist,
203 static BitmapAnd *make_bitmap_and(List *bitmapplans);
204 static BitmapOr *make_bitmap_or(List *bitmapplans);
205 static NestLoop *make_nestloop(List *tlist,
206 List *joinclauses, List *otherclauses, List *nestParams,
207 Plan *lefttree, Plan *righttree,
209 static HashJoin *make_hashjoin(List *tlist,
210 List *joinclauses, List *otherclauses,
212 Plan *lefttree, Plan *righttree,
214 static Hash *make_hash(Plan *lefttree,
216 AttrNumber skewColumn,
219 int32 skewColTypmod);
220 static MergeJoin *make_mergejoin(List *tlist,
221 List *joinclauses, List *otherclauses,
224 Oid *mergecollations,
225 int *mergestrategies,
226 bool *mergenullsfirst,
227 Plan *lefttree, Plan *righttree,
229 static Sort *make_sort(Plan *lefttree, int numCols,
230 AttrNumber *sortColIdx, Oid *sortOperators,
231 Oid *collations, bool *nullsFirst);
232 static Plan *prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
234 const AttrNumber *reqColIdx,
235 bool adjust_tlist_in_place,
237 AttrNumber **p_sortColIdx,
238 Oid **p_sortOperators,
240 bool **p_nullsFirst);
241 static EquivalenceMember *find_ec_member_for_tle(EquivalenceClass *ec,
244 static Sort *make_sort_from_pathkeys(Plan *lefttree, List *pathkeys);
245 static Sort *make_sort_from_groupcols(List *groupcls,
246 AttrNumber *grpColIdx,
248 static Material *make_material(Plan *lefttree);
249 static WindowAgg *make_windowagg(List *tlist, Index winref,
250 int partNumCols, AttrNumber *partColIdx, Oid *partOperators,
251 int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators,
252 int frameOptions, Node *startOffset, Node *endOffset,
254 static Group *make_group(List *tlist, List *qual, int numGroupCols,
255 AttrNumber *grpColIdx, Oid *grpOperators,
257 static Unique *make_unique_from_sortclauses(Plan *lefttree, List *distinctList);
258 static Unique *make_unique_from_pathkeys(Plan *lefttree,
259 List *pathkeys, int numCols);
260 static Gather *make_gather(List *qptlist, List *qpqual,
261 int nworkers, bool single_copy, Plan *subplan);
262 static SetOp *make_setop(SetOpCmd cmd, SetOpStrategy strategy, Plan *lefttree,
263 List *distinctList, AttrNumber flagColIdx, int firstFlag,
265 static LockRows *make_lockrows(Plan *lefttree, List *rowMarks, int epqParam);
266 static Result *make_result(List *tlist, Node *resconstantqual, Plan *subplan);
267 static ModifyTable *make_modifytable(PlannerInfo *root,
268 CmdType operation, bool canSetTag,
269 Index nominalRelation,
270 List *resultRelations, List *subplans,
271 List *withCheckOptionLists, List *returningLists,
272 List *rowMarks, OnConflictExpr *onconflict, int epqParam);
277 * Creates the access plan for a query by recursively processing the
278 * desired tree of pathnodes, starting at the node 'best_path'. For
279 * every pathnode found, we create a corresponding plan node containing
280 * appropriate id, target list, and qualification information.
282 * The tlists and quals in the plan tree are still in planner format,
283 * ie, Vars still correspond to the parser's numbering. This will be
284 * fixed later by setrefs.c.
286 * best_path is the best access path
288 * Returns a Plan tree.
291 create_plan(PlannerInfo *root, Path *best_path)
295 /* plan_params should not be in use in current query level */
296 Assert(root->plan_params == NIL);
298 /* Initialize this module's private workspace in PlannerInfo */
299 root->curOuterRels = NULL;
300 root->curOuterParams = NIL;
302 /* Recursively process the path tree, demanding the correct tlist result */
303 plan = create_plan_recurse(root, best_path, CP_EXACT_TLIST);
306 * Make sure the topmost plan node's targetlist exposes the original
307 * column names and other decorative info. Targetlists generated within
308 * the planner don't bother with that stuff, but we must have it on the
309 * top-level tlist seen at execution time. However, ModifyTable plan
310 * nodes don't have a tlist matching the querytree targetlist.
312 if (!IsA(plan, ModifyTable))
313 apply_tlist_labeling(plan->targetlist, root->processed_tlist);
316 * Attach any initPlans created in this query level to the topmost plan
317 * node. (In principle the initplans could go in any plan node at or
318 * above where they're referenced, but there seems no reason to put them
319 * any lower than the topmost node for the query level. Also, see
320 * comments for SS_finalize_plan before you try to change this.)
322 SS_attach_initplans(root, plan);
324 /* Check we successfully assigned all NestLoopParams to plan nodes */
325 if (root->curOuterParams != NIL)
326 elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
329 * Reset plan_params to ensure param IDs used for nestloop params are not
332 root->plan_params = NIL;
338 * create_plan_recurse
339 * Recursive guts of create_plan().
342 create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
346 switch (best_path->pathtype)
351 case T_IndexOnlyScan:
352 case T_BitmapHeapScan:
358 case T_WorkTableScan:
361 plan = create_scan_plan(root, best_path, flags);
366 plan = create_join_plan(root,
367 (JoinPath *) best_path);
370 plan = create_append_plan(root,
371 (AppendPath *) best_path);
374 plan = create_merge_append_plan(root,
375 (MergeAppendPath *) best_path);
378 if (IsA(best_path, ProjectionPath))
380 plan = create_projection_plan(root,
381 (ProjectionPath *) best_path);
383 else if (IsA(best_path, MinMaxAggPath))
385 plan = (Plan *) create_minmaxagg_plan(root,
386 (MinMaxAggPath *) best_path);
390 Assert(IsA(best_path, ResultPath));
391 plan = (Plan *) create_result_plan(root,
392 (ResultPath *) best_path);
396 plan = (Plan *) create_material_plan(root,
397 (MaterialPath *) best_path,
401 if (IsA(best_path, UpperUniquePath))
403 plan = (Plan *) create_upper_unique_plan(root,
404 (UpperUniquePath *) best_path,
409 Assert(IsA(best_path, UniquePath));
410 plan = create_unique_plan(root,
411 (UniquePath *) best_path,
416 plan = (Plan *) create_gather_plan(root,
417 (GatherPath *) best_path);
420 plan = (Plan *) create_sort_plan(root,
421 (SortPath *) best_path,
425 plan = (Plan *) create_group_plan(root,
426 (GroupPath *) best_path);
429 if (IsA(best_path, GroupingSetsPath))
430 plan = create_groupingsets_plan(root,
431 (GroupingSetsPath *) best_path);
434 Assert(IsA(best_path, AggPath));
435 plan = (Plan *) create_agg_plan(root,
436 (AggPath *) best_path);
440 plan = (Plan *) create_windowagg_plan(root,
441 (WindowAggPath *) best_path);
444 plan = (Plan *) create_setop_plan(root,
445 (SetOpPath *) best_path,
448 case T_RecursiveUnion:
449 plan = (Plan *) create_recursiveunion_plan(root,
450 (RecursiveUnionPath *) best_path);
453 plan = (Plan *) create_lockrows_plan(root,
454 (LockRowsPath *) best_path,
458 plan = (Plan *) create_modifytable_plan(root,
459 (ModifyTablePath *) best_path);
462 plan = (Plan *) create_limit_plan(root,
463 (LimitPath *) best_path,
467 elog(ERROR, "unrecognized node type: %d",
468 (int) best_path->pathtype);
469 plan = NULL; /* keep compiler quiet */
478 * Create a scan plan for the parent relation of 'best_path'.
481 create_scan_plan(PlannerInfo *root, Path *best_path, int flags)
483 RelOptInfo *rel = best_path->parent;
485 List *gating_clauses;
490 * Extract the relevant restriction clauses from the parent relation. The
491 * executor must apply all these restrictions during the scan, except for
492 * pseudoconstants which we'll take care of below.
494 * If this is a plain indexscan or index-only scan, we need not consider
495 * restriction clauses that are implied by the index's predicate, so use
496 * indrestrictinfo not baserestrictinfo. Note that we can't do that for
497 * bitmap indexscans, since there's not necessarily a single index
498 * involved; but it doesn't matter since create_bitmap_scan_plan() will be
499 * able to get rid of such clauses anyway via predicate proof.
501 switch (best_path->pathtype)
504 case T_IndexOnlyScan:
505 Assert(IsA(best_path, IndexPath));
506 scan_clauses = ((IndexPath *) best_path)->indexinfo->indrestrictinfo;
509 scan_clauses = rel->baserestrictinfo;
514 * If this is a parameterized scan, we also need to enforce all the join
515 * clauses available from the outer relation(s).
517 * For paranoia's sake, don't modify the stored baserestrictinfo list.
519 if (best_path->param_info)
520 scan_clauses = list_concat(list_copy(scan_clauses),
521 best_path->param_info->ppi_clauses);
524 * Detect whether we have any pseudoconstant quals to deal with. Then, if
525 * we'll need a gating Result node, it will be able to project, so there
526 * are no requirements on the child's tlist.
528 gating_clauses = get_gating_quals(root, scan_clauses);
533 * For table scans, rather than using the relation targetlist (which is
534 * only those Vars actually needed by the query), we prefer to generate a
535 * tlist containing all Vars in order. This will allow the executor to
536 * optimize away projection of the table tuples, if possible.
538 if (use_physical_tlist(root, best_path, flags))
540 if (best_path->pathtype == T_IndexOnlyScan)
542 /* For index-only scan, the preferred tlist is the index's */
543 tlist = copyObject(((IndexPath *) best_path)->indexinfo->indextlist);
546 * Transfer any sortgroupref data to the replacement tlist, unless
547 * we don't care because the gating Result will handle it.
550 apply_pathtarget_labeling_to_tlist(tlist, best_path->pathtarget);
554 tlist = build_physical_tlist(root, rel);
557 /* Failed because of dropped cols, so use regular method */
558 tlist = build_path_tlist(root, best_path);
562 /* As above, transfer sortgroupref data to replacement tlist */
564 apply_pathtarget_labeling_to_tlist(tlist, best_path->pathtarget);
570 tlist = build_path_tlist(root, best_path);
573 switch (best_path->pathtype)
576 plan = (Plan *) create_seqscan_plan(root,
583 plan = (Plan *) create_samplescan_plan(root,
590 plan = (Plan *) create_indexscan_plan(root,
591 (IndexPath *) best_path,
597 case T_IndexOnlyScan:
598 plan = (Plan *) create_indexscan_plan(root,
599 (IndexPath *) best_path,
605 case T_BitmapHeapScan:
606 plan = (Plan *) create_bitmap_scan_plan(root,
607 (BitmapHeapPath *) best_path,
613 plan = (Plan *) create_tidscan_plan(root,
614 (TidPath *) best_path,
620 plan = (Plan *) create_subqueryscan_plan(root,
621 (SubqueryScanPath *) best_path,
627 plan = (Plan *) create_functionscan_plan(root,
634 plan = (Plan *) create_valuesscan_plan(root,
641 plan = (Plan *) create_ctescan_plan(root,
647 case T_WorkTableScan:
648 plan = (Plan *) create_worktablescan_plan(root,
655 plan = (Plan *) create_foreignscan_plan(root,
656 (ForeignPath *) best_path,
662 plan = (Plan *) create_customscan_plan(root,
663 (CustomPath *) best_path,
669 elog(ERROR, "unrecognized node type: %d",
670 (int) best_path->pathtype);
671 plan = NULL; /* keep compiler quiet */
676 * If there are any pseudoconstant clauses attached to this node, insert a
677 * gating Result node that evaluates the pseudoconstants as one-time
681 plan = create_gating_plan(root, best_path, plan, gating_clauses);
687 * Build a target list (ie, a list of TargetEntry) for the Path's output.
689 * This is almost just make_tlist_from_pathtarget(), but we also have to
690 * deal with replacing nestloop params.
693 build_path_tlist(PlannerInfo *root, Path *path)
696 Index *sortgrouprefs = path->pathtarget->sortgrouprefs;
700 foreach(v, path->pathtarget->exprs)
702 Node *node = (Node *) lfirst(v);
706 * If it's a parameterized path, there might be lateral references in
707 * the tlist, which need to be replaced with Params. There's no need
708 * to remake the TargetEntry nodes, so apply this to each list item
711 if (path->param_info)
712 node = replace_nestloop_params(root, node);
714 tle = makeTargetEntry((Expr *) node,
719 tle->ressortgroupref = sortgrouprefs[resno - 1];
721 tlist = lappend(tlist, tle);
729 * Decide whether to use a tlist matching relation structure,
730 * rather than only those Vars actually referenced.
733 use_physical_tlist(PlannerInfo *root, Path *path, int flags)
735 RelOptInfo *rel = path->parent;
740 * Forget it if either exact tlist or small tlist is demanded.
742 if (flags & (CP_EXACT_TLIST | CP_SMALL_TLIST))
746 * We can do this for real relation scans, subquery scans, function scans,
747 * values scans, and CTE scans (but not for, eg, joins).
749 if (rel->rtekind != RTE_RELATION &&
750 rel->rtekind != RTE_SUBQUERY &&
751 rel->rtekind != RTE_FUNCTION &&
752 rel->rtekind != RTE_VALUES &&
753 rel->rtekind != RTE_CTE)
757 * Can't do it with inheritance cases either (mainly because Append
758 * doesn't project; this test may be unnecessary now that
759 * create_append_plan instructs its children to return an exact tlist).
761 if (rel->reloptkind != RELOPT_BASEREL)
765 * Can't do it if any system columns or whole-row Vars are requested.
766 * (This could possibly be fixed but would take some fragile assumptions
767 * in setrefs.c, I think.)
769 for (i = rel->min_attr; i <= 0; i++)
771 if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
776 * Can't do it if the rel is required to emit any placeholder expressions,
779 foreach(lc, root->placeholder_list)
781 PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
783 if (bms_nonempty_difference(phinfo->ph_needed, rel->relids) &&
784 bms_is_subset(phinfo->ph_eval_at, rel->relids))
789 * Also, can't do it if CP_LABEL_TLIST is specified and path is requested
790 * to emit any sort/group columns that are not simple Vars. (If they are
791 * simple Vars, they should appear in the physical tlist, and
792 * apply_pathtarget_labeling_to_tlist will take care of getting them
793 * labeled again.) We also have to check that no two sort/group columns
794 * are the same Var, else that element of the physical tlist would need
795 * conflicting ressortgroupref labels.
797 if ((flags & CP_LABEL_TLIST) && path->pathtarget->sortgrouprefs)
799 Bitmapset *sortgroupatts = NULL;
802 foreach(lc, path->pathtarget->exprs)
804 Expr *expr = (Expr *) lfirst(lc);
806 if (path->pathtarget->sortgrouprefs[i])
808 if (expr && IsA(expr, Var))
810 int attno = ((Var *) expr)->varattno;
812 attno -= FirstLowInvalidHeapAttributeNumber;
813 if (bms_is_member(attno, sortgroupatts))
815 sortgroupatts = bms_add_member(sortgroupatts, attno);
829 * See if there are pseudoconstant quals in a node's quals list
831 * If the node's quals list includes any pseudoconstant quals,
832 * return just those quals.
835 get_gating_quals(PlannerInfo *root, List *quals)
837 /* No need to look if we know there are no pseudoconstants */
838 if (!root->hasPseudoConstantQuals)
841 /* Sort into desirable execution order while still in RestrictInfo form */
842 quals = order_qual_clauses(root, quals);
844 /* Pull out any pseudoconstant quals from the RestrictInfo list */
845 return extract_actual_clauses(quals, true);
850 * Deal with pseudoconstant qual clauses
852 * Add a gating Result node atop the already-built plan.
855 create_gating_plan(PlannerInfo *root, Path *path, Plan *plan,
860 Assert(gating_quals);
863 * Since we need a Result node anyway, always return the path's requested
864 * tlist; that's never a wrong choice, even if the parent node didn't ask
865 * for CP_EXACT_TLIST.
867 gplan = (Plan *) make_result(build_path_tlist(root, path),
868 (Node *) gating_quals,
872 * Notice that we don't change cost or size estimates when doing gating.
873 * The costs of qual eval were already included in the subplan's cost.
874 * Leaving the size alone amounts to assuming that the gating qual will
875 * succeed, which is the conservative estimate for planning upper queries.
876 * We certainly don't want to assume the output size is zero (unless the
877 * gating qual is actually constant FALSE, and that case is dealt with in
878 * clausesel.c). Interpolating between the two cases is silly, because it
879 * doesn't reflect what will really happen at runtime, and besides which
880 * in most cases we have only a very bad idea of the probability of the
881 * gating qual being true.
883 copy_plan_costsize(gplan, plan);
890 * Create a join plan for 'best_path' and (recursively) plans for its
891 * inner and outer paths.
894 create_join_plan(PlannerInfo *root, JoinPath *best_path)
897 List *gating_clauses;
899 switch (best_path->path.pathtype)
902 plan = (Plan *) create_mergejoin_plan(root,
903 (MergePath *) best_path);
906 plan = (Plan *) create_hashjoin_plan(root,
907 (HashPath *) best_path);
910 plan = (Plan *) create_nestloop_plan(root,
911 (NestPath *) best_path);
914 elog(ERROR, "unrecognized node type: %d",
915 (int) best_path->path.pathtype);
916 plan = NULL; /* keep compiler quiet */
921 * If there are any pseudoconstant clauses attached to this node, insert a
922 * gating Result node that evaluates the pseudoconstants as one-time
925 gating_clauses = get_gating_quals(root, best_path->joinrestrictinfo);
927 plan = create_gating_plan(root, (Path *) best_path, plan,
933 * * Expensive function pullups may have pulled local predicates * into
934 * this path node. Put them in the qpqual of the plan node. * JMH,
937 if (get_loc_restrictinfo(best_path) != NIL)
938 set_qpqual((Plan) plan,
939 list_concat(get_qpqual((Plan) plan),
940 get_actual_clauses(get_loc_restrictinfo(best_path))));
948 * Create an Append plan for 'best_path' and (recursively) plans
951 * Returns a Plan node.
954 create_append_plan(PlannerInfo *root, AppendPath *best_path)
957 List *tlist = build_path_tlist(root, &best_path->path);
958 List *subplans = NIL;
962 * The subpaths list could be empty, if every child was proven empty by
963 * constraint exclusion. In that case generate a dummy plan that returns
966 * Note that an AppendPath with no members is also generated in certain
967 * cases where there was no appending construct at all, but we know the
968 * relation is empty (see set_dummy_rel_pathlist).
970 if (best_path->subpaths == NIL)
972 /* Generate a Result plan with constant-FALSE gating qual */
975 plan = (Plan *) make_result(tlist,
976 (Node *) list_make1(makeBoolConst(false,
980 copy_generic_path_info(plan, (Path *) best_path);
985 /* Build the plan for each child */
986 foreach(subpaths, best_path->subpaths)
988 Path *subpath = (Path *) lfirst(subpaths);
991 /* Must insist that all children return the same tlist */
992 subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
994 subplans = lappend(subplans, subplan);
998 * XXX ideally, if there's just one child, we'd not bother to generate an
999 * Append node but just return the single child. At the moment this does
1000 * not work because the varno of the child scan plan won't match the
1001 * parent-rel Vars it'll be asked to emit.
1004 plan = make_append(subplans, tlist);
1006 copy_generic_path_info(&plan->plan, (Path *) best_path);
1008 return (Plan *) plan;
1012 * create_merge_append_plan
1013 * Create a MergeAppend plan for 'best_path' and (recursively) plans
1016 * Returns a Plan node.
1019 create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path)
1021 MergeAppend *node = makeNode(MergeAppend);
1022 Plan *plan = &node->plan;
1023 List *tlist = build_path_tlist(root, &best_path->path);
1024 List *pathkeys = best_path->path.pathkeys;
1025 List *subplans = NIL;
1029 * We don't have the actual creation of the MergeAppend node split out
1030 * into a separate make_xxx function. This is because we want to run
1031 * prepare_sort_from_pathkeys on it before we do so on the individual
1032 * child plans, to make cross-checking the sort info easier.
1034 copy_generic_path_info(plan, (Path *) best_path);
1035 plan->targetlist = tlist;
1037 plan->lefttree = NULL;
1038 plan->righttree = NULL;
1040 /* Compute sort column info, and adjust MergeAppend's tlist as needed */
1041 (void) prepare_sort_from_pathkeys(plan, pathkeys,
1042 best_path->path.parent->relids,
1047 &node->sortOperators,
1052 * Now prepare the child plans. We must apply prepare_sort_from_pathkeys
1053 * even to subplans that don't need an explicit sort, to make sure they
1054 * are returning the same sort key columns the MergeAppend expects.
1056 foreach(subpaths, best_path->subpaths)
1058 Path *subpath = (Path *) lfirst(subpaths);
1061 AttrNumber *sortColIdx;
1066 /* Build the child plan */
1067 /* Must insist that all children return the same tlist */
1068 subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
1070 /* Compute sort column info, and adjust subplan's tlist as needed */
1071 subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
1072 subpath->parent->relids,
1082 * Check that we got the same sort key information. We just Assert
1083 * that the sortops match, since those depend only on the pathkeys;
1084 * but it seems like a good idea to check the sort column numbers
1085 * explicitly, to ensure the tlists really do match up.
1087 Assert(numsortkeys == node->numCols);
1088 if (memcmp(sortColIdx, node->sortColIdx,
1089 numsortkeys * sizeof(AttrNumber)) != 0)
1090 elog(ERROR, "MergeAppend child's targetlist doesn't match MergeAppend");
1091 Assert(memcmp(sortOperators, node->sortOperators,
1092 numsortkeys * sizeof(Oid)) == 0);
1093 Assert(memcmp(collations, node->collations,
1094 numsortkeys * sizeof(Oid)) == 0);
1095 Assert(memcmp(nullsFirst, node->nullsFirst,
1096 numsortkeys * sizeof(bool)) == 0);
1098 /* Now, insert a Sort node if subplan isn't sufficiently ordered */
1099 if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
1101 Sort *sort = make_sort(subplan, numsortkeys,
1102 sortColIdx, sortOperators,
1103 collations, nullsFirst);
1105 label_sort_with_costsize(root, sort, best_path->limit_tuples);
1106 subplan = (Plan *) sort;
1109 subplans = lappend(subplans, subplan);
1112 node->mergeplans = subplans;
1114 return (Plan *) node;
1118 * create_result_plan
1119 * Create a Result plan for 'best_path'.
1120 * This is only used for degenerate cases, such as a query with an empty
1123 * Returns a Plan node.
1126 create_result_plan(PlannerInfo *root, ResultPath *best_path)
1132 tlist = build_path_tlist(root, &best_path->path);
1134 /* best_path->quals is just bare clauses */
1135 quals = order_qual_clauses(root, best_path->quals);
1137 plan = make_result(tlist, (Node *) quals, NULL);
1139 copy_generic_path_info(&plan->plan, (Path *) best_path);
1145 * create_material_plan
1146 * Create a Material plan for 'best_path' and (recursively) plans
1149 * Returns a Plan node.
1152 create_material_plan(PlannerInfo *root, MaterialPath *best_path, int flags)
1158 * We don't want any excess columns in the materialized tuples, so request
1159 * a smaller tlist. Otherwise, since Material doesn't project, tlist
1160 * requirements pass through.
1162 subplan = create_plan_recurse(root, best_path->subpath,
1163 flags | CP_SMALL_TLIST);
1165 plan = make_material(subplan);
1167 copy_generic_path_info(&plan->plan, (Path *) best_path);
1173 * create_unique_plan
1174 * Create a Unique plan for 'best_path' and (recursively) plans
1177 * Returns a Plan node.
1180 create_unique_plan(PlannerInfo *root, UniquePath *best_path, int flags)
1190 AttrNumber *groupColIdx;
1194 /* Unique doesn't project, so tlist requirements pass through */
1195 subplan = create_plan_recurse(root, best_path->subpath, flags);
1197 /* Done if we don't need to do any actual unique-ifying */
1198 if (best_path->umethod == UNIQUE_PATH_NOOP)
1202 * As constructed, the subplan has a "flat" tlist containing just the Vars
1203 * needed here and at upper levels. The values we are supposed to
1204 * unique-ify may be expressions in these variables. We have to add any
1205 * such expressions to the subplan's tlist.
1207 * The subplan may have a "physical" tlist if it is a simple scan plan. If
1208 * we're going to sort, this should be reduced to the regular tlist, so
1209 * that we don't sort more data than we need to. For hashing, the tlist
1210 * should be left as-is if we don't need to add any expressions; but if we
1211 * do have to add expressions, then a projection step will be needed at
1212 * runtime anyway, so we may as well remove unneeded items. Therefore
1213 * newtlist starts from build_path_tlist() not just a copy of the
1214 * subplan's tlist; and we don't install it into the subplan unless we are
1215 * sorting or stuff has to be added.
1217 in_operators = best_path->in_operators;
1218 uniq_exprs = best_path->uniq_exprs;
1220 /* initialize modified subplan tlist as just the "required" vars */
1221 newtlist = build_path_tlist(root, &best_path->path);
1222 nextresno = list_length(newtlist) + 1;
1225 foreach(l, uniq_exprs)
1227 Node *uniqexpr = lfirst(l);
1230 tle = tlist_member(uniqexpr, newtlist);
1233 tle = makeTargetEntry((Expr *) uniqexpr,
1237 newtlist = lappend(newtlist, tle);
1243 if (newitems || best_path->umethod == UNIQUE_PATH_SORT)
1246 * If the top plan node can't do projections and its existing target
1247 * list isn't already what we need, we need to add a Result node to
1250 if (!is_projection_capable_plan(subplan) &&
1251 !tlist_same_exprs(newtlist, subplan->targetlist))
1252 subplan = inject_projection_plan(subplan, newtlist);
1254 subplan->targetlist = newtlist;
1258 * Build control information showing which subplan output columns are to
1259 * be examined by the grouping step. Unfortunately we can't merge this
1260 * with the previous loop, since we didn't then know which version of the
1261 * subplan tlist we'd end up using.
1263 newtlist = subplan->targetlist;
1264 numGroupCols = list_length(uniq_exprs);
1265 groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber));
1268 foreach(l, uniq_exprs)
1270 Node *uniqexpr = lfirst(l);
1273 tle = tlist_member(uniqexpr, newtlist);
1274 if (!tle) /* shouldn't happen */
1275 elog(ERROR, "failed to find unique expression in subplan tlist");
1276 groupColIdx[groupColPos++] = tle->resno;
1279 if (best_path->umethod == UNIQUE_PATH_HASH)
1281 Oid *groupOperators;
1284 * Get the hashable equality operators for the Agg node to use.
1285 * Normally these are the same as the IN clause operators, but if
1286 * those are cross-type operators then the equality operators are the
1287 * ones for the IN clause operators' RHS datatype.
1289 groupOperators = (Oid *) palloc(numGroupCols * sizeof(Oid));
1291 foreach(l, in_operators)
1293 Oid in_oper = lfirst_oid(l);
1296 if (!get_compatible_hash_operators(in_oper, NULL, &eq_oper))
1297 elog(ERROR, "could not find compatible hash operator for operator %u",
1299 groupOperators[groupColPos++] = eq_oper;
1303 * Since the Agg node is going to project anyway, we can give it the
1304 * minimum output tlist, without any stuff we might have added to the
1307 plan = (Plan *) make_agg(build_path_tlist(root, &best_path->path),
1316 best_path->path.rows,
1321 List *sortList = NIL;
1324 /* Create an ORDER BY list to sort the input compatibly */
1326 foreach(l, in_operators)
1328 Oid in_oper = lfirst_oid(l);
1332 SortGroupClause *sortcl;
1334 sortop = get_ordering_op_for_equality_op(in_oper, false);
1335 if (!OidIsValid(sortop)) /* shouldn't happen */
1336 elog(ERROR, "could not find ordering operator for equality operator %u",
1340 * The Unique node will need equality operators. Normally these
1341 * are the same as the IN clause operators, but if those are
1342 * cross-type operators then the equality operators are the ones
1343 * for the IN clause operators' RHS datatype.
1345 eqop = get_equality_op_for_ordering_op(sortop, NULL);
1346 if (!OidIsValid(eqop)) /* shouldn't happen */
1347 elog(ERROR, "could not find equality operator for ordering operator %u",
1350 tle = get_tle_by_resno(subplan->targetlist,
1351 groupColIdx[groupColPos]);
1352 Assert(tle != NULL);
1354 sortcl = makeNode(SortGroupClause);
1355 sortcl->tleSortGroupRef = assignSortGroupRef(tle,
1356 subplan->targetlist);
1357 sortcl->eqop = eqop;
1358 sortcl->sortop = sortop;
1359 sortcl->nulls_first = false;
1360 sortcl->hashable = false; /* no need to make this accurate */
1361 sortList = lappend(sortList, sortcl);
1364 sort = make_sort_from_sortclauses(sortList, subplan);
1365 label_sort_with_costsize(root, sort, -1.0);
1366 plan = (Plan *) make_unique_from_sortclauses((Plan *) sort, sortList);
1369 /* Copy cost data from Path to Plan */
1370 copy_generic_path_info(plan, &best_path->path);
1376 * create_gather_plan
1378 * Create a Gather plan for 'best_path' and (recursively) plans
1382 create_gather_plan(PlannerInfo *root, GatherPath *best_path)
1384 Gather *gather_plan;
1389 * Although the Gather node can project, we prefer to push down such work
1390 * to its child node, so demand an exact tlist from the child.
1392 subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
1394 tlist = build_path_tlist(root, &best_path->path);
1396 gather_plan = make_gather(tlist,
1398 best_path->path.parallel_workers,
1399 best_path->single_copy,
1402 copy_generic_path_info(&gather_plan->plan, &best_path->path);
1404 /* use parallel mode for parallel plans. */
1405 root->glob->parallelModeNeeded = true;
1411 * create_projection_plan
1413 * Create a plan tree to do a projection step and (recursively) plans
1414 * for its subpaths. We may need a Result node for the projection,
1415 * but sometimes we can just let the subplan do the work.
1418 create_projection_plan(PlannerInfo *root, ProjectionPath *best_path)
1424 /* Since we intend to project, we don't need to constrain child tlist */
1425 subplan = create_plan_recurse(root, best_path->subpath, 0);
1427 tlist = build_path_tlist(root, &best_path->path);
1430 * We might not really need a Result node here, either because the subplan
1431 * can project or because it's returning the right list of expressions
1432 * anyway. Usually create_projection_path will have detected that and set
1433 * dummypp if we don't need a Result; but its decision can't be final,
1434 * because some createplan.c routines change the tlists of their nodes.
1435 * (An example is that create_merge_append_plan might add resjunk sort
1436 * columns to a MergeAppend.) So we have to recheck here. If we do
1437 * arrive at a different answer than create_projection_path did, we'll
1438 * have made slightly wrong cost estimates; but label the plan with the
1439 * cost estimates we actually used, not "corrected" ones. (XXX this could
1440 * be cleaned up if we moved more of the sortcolumn setup logic into Path
1441 * creation, but that would add expense to creating Paths we might end up
1444 if (is_projection_capable_path(best_path->subpath) ||
1445 tlist_same_exprs(tlist, subplan->targetlist))
1447 /* Don't need a separate Result, just assign tlist to subplan */
1449 plan->targetlist = tlist;
1451 /* Label plan with the estimated costs we actually used */
1452 plan->startup_cost = best_path->path.startup_cost;
1453 plan->total_cost = best_path->path.total_cost;
1454 plan->plan_rows = best_path->path.rows;
1455 plan->plan_width = best_path->path.pathtarget->width;
1456 /* ... but be careful not to munge subplan's parallel-aware flag */
1460 /* We need a Result node */
1461 plan = (Plan *) make_result(tlist, NULL, subplan);
1463 copy_generic_path_info(plan, (Path *) best_path);
1470 * inject_projection_plan
1471 * Insert a Result node to do a projection step.
1473 * This is used in a few places where we decide on-the-fly that we need a
1474 * projection step as part of the tree generated for some Path node.
1475 * We should try to get rid of this in favor of doing it more honestly.
1478 inject_projection_plan(Plan *subplan, List *tlist)
1482 plan = (Plan *) make_result(tlist, NULL, subplan);
1485 * In principle, we should charge tlist eval cost plus cpu_per_tuple per
1486 * row for the Result node. But the former has probably been factored in
1487 * already and the latter was not accounted for during Path construction,
1488 * so being formally correct might just make the EXPLAIN output look less
1489 * consistent not more so. Hence, just copy the subplan's cost.
1491 copy_plan_costsize(plan, subplan);
1499 * Create a Sort plan for 'best_path' and (recursively) plans
1503 create_sort_plan(PlannerInfo *root, SortPath *best_path, int flags)
1509 * We don't want any excess columns in the sorted tuples, so request a
1510 * smaller tlist. Otherwise, since Sort doesn't project, tlist
1511 * requirements pass through.
1513 subplan = create_plan_recurse(root, best_path->subpath,
1514 flags | CP_SMALL_TLIST);
1516 plan = make_sort_from_pathkeys(subplan, best_path->path.pathkeys);
1518 copy_generic_path_info(&plan->plan, (Path *) best_path);
1526 * Create a Group plan for 'best_path' and (recursively) plans
1530 create_group_plan(PlannerInfo *root, GroupPath *best_path)
1538 * Group can project, so no need to be terribly picky about child tlist,
1539 * but we do need grouping columns to be available
1541 subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
1543 tlist = build_path_tlist(root, &best_path->path);
1545 quals = order_qual_clauses(root, best_path->qual);
1547 plan = make_group(tlist,
1549 list_length(best_path->groupClause),
1550 extract_grouping_cols(best_path->groupClause,
1551 subplan->targetlist),
1552 extract_grouping_ops(best_path->groupClause),
1555 copy_generic_path_info(&plan->plan, (Path *) best_path);
1561 * create_upper_unique_plan
1563 * Create a Unique plan for 'best_path' and (recursively) plans
1567 create_upper_unique_plan(PlannerInfo *root, UpperUniquePath *best_path, int flags)
1573 * Unique doesn't project, so tlist requirements pass through; moreover we
1574 * need grouping columns to be labeled.
1576 subplan = create_plan_recurse(root, best_path->subpath,
1577 flags | CP_LABEL_TLIST);
1579 plan = make_unique_from_pathkeys(subplan,
1580 best_path->path.pathkeys,
1581 best_path->numkeys);
1583 copy_generic_path_info(&plan->plan, (Path *) best_path);
1591 * Create an Agg plan for 'best_path' and (recursively) plans
1595 create_agg_plan(PlannerInfo *root, AggPath *best_path)
1603 * Agg can project, so no need to be terribly picky about child tlist, but
1604 * we do need grouping columns to be available
1606 subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
1608 tlist = build_path_tlist(root, &best_path->path);
1610 quals = order_qual_clauses(root, best_path->qual);
1612 plan = make_agg(tlist, quals,
1613 best_path->aggstrategy,
1614 best_path->aggsplit,
1615 list_length(best_path->groupClause),
1616 extract_grouping_cols(best_path->groupClause,
1617 subplan->targetlist),
1618 extract_grouping_ops(best_path->groupClause),
1621 best_path->numGroups,
1624 copy_generic_path_info(&plan->plan, (Path *) best_path);
1630 * Given a groupclause for a collection of grouping sets, produce the
1631 * corresponding groupColIdx.
1633 * root->grouping_map maps the tleSortGroupRef to the actual column position in
1634 * the input tuple. So we get the ref from the entries in the groupclause and
1635 * look them up there.
1638 remap_groupColIdx(PlannerInfo *root, List *groupClause)
1640 AttrNumber *grouping_map = root->grouping_map;
1641 AttrNumber *new_grpColIdx;
1645 Assert(grouping_map);
1647 new_grpColIdx = palloc0(sizeof(AttrNumber) * list_length(groupClause));
1650 foreach(lc, groupClause)
1652 SortGroupClause *clause = lfirst(lc);
1654 new_grpColIdx[i++] = grouping_map[clause->tleSortGroupRef];
1657 return new_grpColIdx;
1661 * create_groupingsets_plan
1662 * Create a plan for 'best_path' and (recursively) plans
1665 * What we emit is an Agg plan with some vestigial Agg and Sort nodes
1666 * hanging off the side. The top Agg implements the last grouping set
1667 * specified in the GroupingSetsPath, and any additional grouping sets
1668 * each give rise to a subsidiary Agg and Sort node in the top Agg's
1669 * "chain" list. These nodes don't participate in the plan directly,
1670 * but they are a convenient way to represent the required data for
1673 * Returns a Plan node.
1676 create_groupingsets_plan(PlannerInfo *root, GroupingSetsPath *best_path)
1680 List *rollup_groupclauses = best_path->rollup_groupclauses;
1681 List *rollup_lists = best_path->rollup_lists;
1682 AttrNumber *grouping_map;
1688 /* Shouldn't get here without grouping sets */
1689 Assert(root->parse->groupingSets);
1690 Assert(rollup_lists != NIL);
1691 Assert(list_length(rollup_lists) == list_length(rollup_groupclauses));
1694 * Agg can project, so no need to be terribly picky about child tlist, but
1695 * we do need grouping columns to be available
1697 subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
1700 * Compute the mapping from tleSortGroupRef to column index in the child's
1701 * tlist. First, identify max SortGroupRef in groupClause, for array
1705 foreach(lc, root->parse->groupClause)
1707 SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
1709 if (gc->tleSortGroupRef > maxref)
1710 maxref = gc->tleSortGroupRef;
1713 grouping_map = (AttrNumber *) palloc0((maxref + 1) * sizeof(AttrNumber));
1715 /* Now look up the column numbers in the child's tlist */
1716 foreach(lc, root->parse->groupClause)
1718 SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
1719 TargetEntry *tle = get_sortgroupclause_tle(gc, subplan->targetlist);
1721 grouping_map[gc->tleSortGroupRef] = tle->resno;
1725 * During setrefs.c, we'll need the grouping_map to fix up the cols lists
1726 * in GroupingFunc nodes. Save it for setrefs.c to use.
1728 * This doesn't work if we're in an inheritance subtree (see notes in
1729 * create_modifytable_plan). Fortunately we can't be because there would
1730 * never be grouping in an UPDATE/DELETE; but let's Assert that.
1732 Assert(!root->hasInheritedTarget);
1733 Assert(root->grouping_map == NULL);
1734 root->grouping_map = grouping_map;
1737 * Generate the side nodes that describe the other sort and group
1738 * operations besides the top one. Note that we don't worry about putting
1739 * accurate cost estimates in the side nodes; only the topmost Agg node's
1740 * costs will be shown by EXPLAIN.
1743 if (list_length(rollup_groupclauses) > 1)
1745 forboth(lc, rollup_groupclauses, lc2, rollup_lists)
1747 List *groupClause = (List *) lfirst(lc);
1748 List *gsets = (List *) lfirst(lc2);
1749 AttrNumber *new_grpColIdx;
1753 /* We want to iterate over all but the last rollup list elements */
1754 if (lnext(lc) == NULL)
1757 new_grpColIdx = remap_groupColIdx(root, groupClause);
1759 sort_plan = (Plan *)
1760 make_sort_from_groupcols(groupClause,
1764 agg_plan = (Plan *) make_agg(NIL,
1768 list_length((List *) linitial(gsets)),
1770 extract_grouping_ops(groupClause),
1773 0, /* numGroups not needed */
1777 * Nuke stuff we don't need to avoid bloating debug output.
1779 sort_plan->targetlist = NIL;
1780 sort_plan->lefttree = NULL;
1782 chain = lappend(chain, agg_plan);
1787 * Now make the final Agg node
1790 List *groupClause = (List *) llast(rollup_groupclauses);
1791 List *gsets = (List *) llast(rollup_lists);
1792 AttrNumber *top_grpColIdx;
1795 top_grpColIdx = remap_groupColIdx(root, groupClause);
1797 numGroupCols = list_length((List *) linitial(gsets));
1799 plan = make_agg(build_path_tlist(root, &best_path->path),
1801 (numGroupCols > 0) ? AGG_SORTED : AGG_PLAIN,
1805 extract_grouping_ops(groupClause),
1808 0, /* numGroups not needed */
1811 /* Copy cost data from Path to Plan */
1812 copy_generic_path_info(&plan->plan, &best_path->path);
1815 return (Plan *) plan;
1819 * create_minmaxagg_plan
1821 * Create a Result plan for 'best_path' and (recursively) plans
1825 create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
1831 /* Prepare an InitPlan for each aggregate's subquery. */
1832 foreach(lc, best_path->mmaggregates)
1834 MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
1835 PlannerInfo *subroot = mminfo->subroot;
1836 Query *subparse = subroot->parse;
1840 * Generate the plan for the subquery. We already have a Path, but we
1841 * have to convert it to a Plan and attach a LIMIT node above it.
1842 * Since we are entering a different planner context (subroot),
1843 * recurse to create_plan not create_plan_recurse.
1845 plan = create_plan(subroot, mminfo->path);
1847 plan = (Plan *) make_limit(plan,
1848 subparse->limitOffset,
1849 subparse->limitCount);
1851 /* Must apply correct cost/width data to Limit node */
1852 plan->startup_cost = mminfo->path->startup_cost;
1853 plan->total_cost = mminfo->pathcost;
1854 plan->plan_rows = 1;
1855 plan->plan_width = mminfo->path->pathtarget->width;
1856 plan->parallel_aware = false;
1858 /* Convert the plan into an InitPlan in the outer query. */
1859 SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
1862 /* Generate the output plan --- basically just a Result */
1863 tlist = build_path_tlist(root, &best_path->path);
1865 plan = make_result(tlist, (Node *) best_path->quals, NULL);
1867 copy_generic_path_info(&plan->plan, (Path *) best_path);
1870 * During setrefs.c, we'll need to replace references to the Agg nodes
1871 * with InitPlan output params. (We can't just do that locally in the
1872 * MinMaxAgg node, because path nodes above here may have Agg references
1873 * as well.) Save the mmaggregates list to tell setrefs.c to do that.
1875 * This doesn't work if we're in an inheritance subtree (see notes in
1876 * create_modifytable_plan). Fortunately we can't be because there would
1877 * never be aggregates in an UPDATE/DELETE; but let's Assert that.
1879 Assert(!root->hasInheritedTarget);
1880 Assert(root->minmax_aggs == NIL);
1881 root->minmax_aggs = best_path->mmaggregates;
1887 * create_windowagg_plan
1889 * Create a WindowAgg plan for 'best_path' and (recursively) plans
1893 create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path)
1896 WindowClause *wc = best_path->winclause;
1900 AttrNumber *sortColIdx;
1905 AttrNumber *partColIdx;
1908 AttrNumber *ordColIdx;
1912 * WindowAgg can project, so no need to be terribly picky about child
1913 * tlist, but we do need grouping columns to be available
1915 subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
1917 tlist = build_path_tlist(root, &best_path->path);
1920 * We shouldn't need to actually sort, but it's convenient to use
1921 * prepare_sort_from_pathkeys to identify the input's sort columns.
1923 subplan = prepare_sort_from_pathkeys(subplan,
1924 best_path->winpathkeys,
1934 /* Now deconstruct that into partition and ordering portions */
1935 get_column_info_for_window(root,
1937 subplan->targetlist,
1947 /* And finally we can make the WindowAgg node */
1948 plan = make_windowagg(tlist,
1961 copy_generic_path_info(&plan->plan, (Path *) best_path);
1967 * get_column_info_for_window
1968 * Get the partitioning/ordering column numbers and equality operators
1969 * for a WindowAgg node.
1971 * This depends on the behavior of planner.c's make_pathkeys_for_window!
1973 * We are given the target WindowClause and an array of the input column
1974 * numbers associated with the resulting pathkeys. In the easy case, there
1975 * are the same number of pathkey columns as partitioning + ordering columns
1976 * and we just have to copy some data around. However, it's possible that
1977 * some of the original partitioning + ordering columns were eliminated as
1978 * redundant during the transformation to pathkeys. (This can happen even
1979 * though the parser gets rid of obvious duplicates. A typical scenario is a
1980 * window specification "PARTITION BY x ORDER BY y" coupled with a clause
1981 * "WHERE x = y" that causes the two sort columns to be recognized as
1982 * redundant.) In that unusual case, we have to work a lot harder to
1983 * determine which keys are significant.
1985 * The method used here is a bit brute-force: add the sort columns to a list
1986 * one at a time and note when the resulting pathkey list gets longer. But
1987 * it's a sufficiently uncommon case that a faster way doesn't seem worth
1988 * the amount of code refactoring that'd be needed.
1991 get_column_info_for_window(PlannerInfo *root, WindowClause *wc, List *tlist,
1992 int numSortCols, AttrNumber *sortColIdx,
1994 AttrNumber **partColIdx,
1995 Oid **partOperators,
1997 AttrNumber **ordColIdx,
2000 int numPart = list_length(wc->partitionClause);
2001 int numOrder = list_length(wc->orderClause);
2003 if (numSortCols == numPart + numOrder)
2006 *partNumCols = numPart;
2007 *partColIdx = sortColIdx;
2008 *partOperators = extract_grouping_ops(wc->partitionClause);
2009 *ordNumCols = numOrder;
2010 *ordColIdx = sortColIdx + numPart;
2011 *ordOperators = extract_grouping_ops(wc->orderClause);
2020 /* first, allocate what's certainly enough space for the arrays */
2022 *partColIdx = (AttrNumber *) palloc(numPart * sizeof(AttrNumber));
2023 *partOperators = (Oid *) palloc(numPart * sizeof(Oid));
2025 *ordColIdx = (AttrNumber *) palloc(numOrder * sizeof(AttrNumber));
2026 *ordOperators = (Oid *) palloc(numOrder * sizeof(Oid));
2030 foreach(lc, wc->partitionClause)
2032 SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
2035 sortclauses = lappend(sortclauses, sgc);
2036 new_pathkeys = make_pathkeys_for_sortclauses(root,
2039 if (list_length(new_pathkeys) > list_length(pathkeys))
2041 /* this sort clause is actually significant */
2042 (*partColIdx)[*partNumCols] = sortColIdx[scidx++];
2043 (*partOperators)[*partNumCols] = sgc->eqop;
2045 pathkeys = new_pathkeys;
2048 foreach(lc, wc->orderClause)
2050 SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
2053 sortclauses = lappend(sortclauses, sgc);
2054 new_pathkeys = make_pathkeys_for_sortclauses(root,
2057 if (list_length(new_pathkeys) > list_length(pathkeys))
2059 /* this sort clause is actually significant */
2060 (*ordColIdx)[*ordNumCols] = sortColIdx[scidx++];
2061 (*ordOperators)[*ordNumCols] = sgc->eqop;
2063 pathkeys = new_pathkeys;
2066 /* complain if we didn't eat exactly the right number of sort cols */
2067 if (scidx != numSortCols)
2068 elog(ERROR, "failed to deconstruct sort operators into partitioning/ordering operators");
2075 * Create a SetOp plan for 'best_path' and (recursively) plans
2079 create_setop_plan(PlannerInfo *root, SetOpPath *best_path, int flags)
2086 * SetOp doesn't project, so tlist requirements pass through; moreover we
2087 * need grouping columns to be labeled.
2089 subplan = create_plan_recurse(root, best_path->subpath,
2090 flags | CP_LABEL_TLIST);
2092 /* Convert numGroups to long int --- but 'ware overflow! */
2093 numGroups = (long) Min(best_path->numGroups, (double) LONG_MAX);
2095 plan = make_setop(best_path->cmd,
2096 best_path->strategy,
2098 best_path->distinctList,
2099 best_path->flagColIdx,
2100 best_path->firstFlag,
2103 copy_generic_path_info(&plan->plan, (Path *) best_path);
2109 * create_recursiveunion_plan
2111 * Create a RecursiveUnion plan for 'best_path' and (recursively) plans
2114 static RecursiveUnion *
2115 create_recursiveunion_plan(PlannerInfo *root, RecursiveUnionPath *best_path)
2117 RecursiveUnion *plan;
2123 /* Need both children to produce same tlist, so force it */
2124 leftplan = create_plan_recurse(root, best_path->leftpath, CP_EXACT_TLIST);
2125 rightplan = create_plan_recurse(root, best_path->rightpath, CP_EXACT_TLIST);
2127 tlist = build_path_tlist(root, &best_path->path);
2129 /* Convert numGroups to long int --- but 'ware overflow! */
2130 numGroups = (long) Min(best_path->numGroups, (double) LONG_MAX);
2132 plan = make_recursive_union(tlist,
2136 best_path->distinctList,
2139 copy_generic_path_info(&plan->plan, (Path *) best_path);
2145 * create_lockrows_plan
2147 * Create a LockRows plan for 'best_path' and (recursively) plans
2151 create_lockrows_plan(PlannerInfo *root, LockRowsPath *best_path,
2157 /* LockRows doesn't project, so tlist requirements pass through */
2158 subplan = create_plan_recurse(root, best_path->subpath, flags);
2160 plan = make_lockrows(subplan, best_path->rowMarks, best_path->epqParam);
2162 copy_generic_path_info(&plan->plan, (Path *) best_path);
2168 * create_modifytable_plan
2169 * Create a ModifyTable plan for 'best_path'.
2171 * Returns a Plan node.
2173 static ModifyTable *
2174 create_modifytable_plan(PlannerInfo *root, ModifyTablePath *best_path)
2177 List *subplans = NIL;
2181 /* Build the plan for each input path */
2182 forboth(subpaths, best_path->subpaths,
2183 subroots, best_path->subroots)
2185 Path *subpath = (Path *) lfirst(subpaths);
2186 PlannerInfo *subroot = (PlannerInfo *) lfirst(subroots);
2190 * In an inherited UPDATE/DELETE, reference the per-child modified
2191 * subroot while creating Plans from Paths for the child rel. This is
2192 * a kluge, but otherwise it's too hard to ensure that Plan creation
2193 * functions (particularly in FDWs) don't depend on the contents of
2194 * "root" matching what they saw at Path creation time. The main
2195 * downside is that creation functions for Plans that might appear
2196 * below a ModifyTable cannot expect to modify the contents of "root"
2197 * and have it "stick" for subsequent processing such as setrefs.c.
2198 * That's not great, but it seems better than the alternative.
2200 subplan = create_plan_recurse(subroot, subpath, CP_EXACT_TLIST);
2202 /* Transfer resname/resjunk labeling, too, to keep executor happy */
2203 apply_tlist_labeling(subplan->targetlist, subroot->processed_tlist);
2205 subplans = lappend(subplans, subplan);
2208 plan = make_modifytable(root,
2209 best_path->operation,
2210 best_path->canSetTag,
2211 best_path->nominalRelation,
2212 best_path->resultRelations,
2214 best_path->withCheckOptionLists,
2215 best_path->returningLists,
2216 best_path->rowMarks,
2217 best_path->onconflict,
2218 best_path->epqParam);
2220 copy_generic_path_info(&plan->plan, &best_path->path);
2228 * Create a Limit plan for 'best_path' and (recursively) plans
2232 create_limit_plan(PlannerInfo *root, LimitPath *best_path, int flags)
2237 /* Limit doesn't project, so tlist requirements pass through */
2238 subplan = create_plan_recurse(root, best_path->subpath, flags);
2240 plan = make_limit(subplan,
2241 best_path->limitOffset,
2242 best_path->limitCount);
2244 copy_generic_path_info(&plan->plan, (Path *) best_path);
2250 /*****************************************************************************
2252 * BASE-RELATION SCAN METHODS
2254 *****************************************************************************/
2258 * create_seqscan_plan
2259 * Returns a seqscan plan for the base relation scanned by 'best_path'
2260 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2263 create_seqscan_plan(PlannerInfo *root, Path *best_path,
2264 List *tlist, List *scan_clauses)
2267 Index scan_relid = best_path->parent->relid;
2269 /* it should be a base rel... */
2270 Assert(scan_relid > 0);
2271 Assert(best_path->parent->rtekind == RTE_RELATION);
2273 /* Sort clauses into best execution order */
2274 scan_clauses = order_qual_clauses(root, scan_clauses);
2276 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2277 scan_clauses = extract_actual_clauses(scan_clauses, false);
2279 /* Replace any outer-relation variables with nestloop params */
2280 if (best_path->param_info)
2282 scan_clauses = (List *)
2283 replace_nestloop_params(root, (Node *) scan_clauses);
2286 scan_plan = make_seqscan(tlist,
2290 copy_generic_path_info(&scan_plan->plan, best_path);
2296 * create_samplescan_plan
2297 * Returns a samplescan plan for the base relation scanned by 'best_path'
2298 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2301 create_samplescan_plan(PlannerInfo *root, Path *best_path,
2302 List *tlist, List *scan_clauses)
2304 SampleScan *scan_plan;
2305 Index scan_relid = best_path->parent->relid;
2307 TableSampleClause *tsc;
2309 /* it should be a base rel with a tablesample clause... */
2310 Assert(scan_relid > 0);
2311 rte = planner_rt_fetch(scan_relid, root);
2312 Assert(rte->rtekind == RTE_RELATION);
2313 tsc = rte->tablesample;
2314 Assert(tsc != NULL);
2316 /* Sort clauses into best execution order */
2317 scan_clauses = order_qual_clauses(root, scan_clauses);
2319 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2320 scan_clauses = extract_actual_clauses(scan_clauses, false);
2322 /* Replace any outer-relation variables with nestloop params */
2323 if (best_path->param_info)
2325 scan_clauses = (List *)
2326 replace_nestloop_params(root, (Node *) scan_clauses);
2327 tsc = (TableSampleClause *)
2328 replace_nestloop_params(root, (Node *) tsc);
2331 scan_plan = make_samplescan(tlist,
2336 copy_generic_path_info(&scan_plan->scan.plan, best_path);
2342 * create_indexscan_plan
2343 * Returns an indexscan plan for the base relation scanned by 'best_path'
2344 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2346 * We use this for both plain IndexScans and IndexOnlyScans, because the
2347 * qual preprocessing work is the same for both. Note that the caller tells
2348 * us which to build --- we don't look at best_path->path.pathtype, because
2349 * create_bitmap_subplan needs to be able to override the prior decision.
2352 create_indexscan_plan(PlannerInfo *root,
2353 IndexPath *best_path,
2359 List *indexquals = best_path->indexquals;
2360 List *indexorderbys = best_path->indexorderbys;
2361 Index baserelid = best_path->path.parent->relid;
2362 Oid indexoid = best_path->indexinfo->indexoid;
2364 List *stripped_indexquals;
2365 List *fixed_indexquals;
2366 List *fixed_indexorderbys;
2367 List *indexorderbyops = NIL;
2370 /* it should be a base rel... */
2371 Assert(baserelid > 0);
2372 Assert(best_path->path.parent->rtekind == RTE_RELATION);
2375 * Build "stripped" indexquals structure (no RestrictInfos) to pass to
2376 * executor as indexqualorig
2378 stripped_indexquals = get_actual_clauses(indexquals);
2381 * The executor needs a copy with the indexkey on the left of each clause
2382 * and with index Vars substituted for table ones.
2384 fixed_indexquals = fix_indexqual_references(root, best_path);
2387 * Likewise fix up index attr references in the ORDER BY expressions.
2389 fixed_indexorderbys = fix_indexorderby_references(root, best_path);
2392 * The qpqual list must contain all restrictions not automatically handled
2393 * by the index, other than pseudoconstant clauses which will be handled
2394 * by a separate gating plan node. All the predicates in the indexquals
2395 * will be checked (either by the index itself, or by nodeIndexscan.c),
2396 * but if there are any "special" operators involved then they must be
2397 * included in qpqual. The upshot is that qpqual must contain
2398 * scan_clauses minus whatever appears in indexquals.
2400 * In normal cases simple pointer equality checks will be enough to spot
2401 * duplicate RestrictInfos, so we try that first.
2403 * Another common case is that a scan_clauses entry is generated from the
2404 * same EquivalenceClass as some indexqual, and is therefore redundant
2405 * with it, though not equal. (This happens when indxpath.c prefers a
2406 * different derived equality than what generate_join_implied_equalities
2407 * picked for a parameterized scan's ppi_clauses.)
2409 * In some situations (particularly with OR'd index conditions) we may
2410 * have scan_clauses that are not equal to, but are logically implied by,
2411 * the index quals; so we also try a predicate_implied_by() check to see
2412 * if we can discard quals that way. (predicate_implied_by assumes its
2413 * first input contains only immutable functions, so we have to check
2416 * Note: if you change this bit of code you should also look at
2417 * extract_nonindex_conditions() in costsize.c.
2420 foreach(l, scan_clauses)
2422 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2424 Assert(IsA(rinfo, RestrictInfo));
2425 if (rinfo->pseudoconstant)
2426 continue; /* we may drop pseudoconstants here */
2427 if (list_member_ptr(indexquals, rinfo))
2428 continue; /* simple duplicate */
2429 if (is_redundant_derived_clause(rinfo, indexquals))
2430 continue; /* derived from same EquivalenceClass */
2431 if (!contain_mutable_functions((Node *) rinfo->clause) &&
2432 predicate_implied_by(list_make1(rinfo->clause), indexquals))
2433 continue; /* provably implied by indexquals */
2434 qpqual = lappend(qpqual, rinfo);
2437 /* Sort clauses into best execution order */
2438 qpqual = order_qual_clauses(root, qpqual);
2440 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2441 qpqual = extract_actual_clauses(qpqual, false);
2444 * We have to replace any outer-relation variables with nestloop params in
2445 * the indexqualorig, qpqual, and indexorderbyorig expressions. A bit
2446 * annoying to have to do this separately from the processing in
2447 * fix_indexqual_references --- rethink this when generalizing the inner
2448 * indexscan support. But note we can't really do this earlier because
2449 * it'd break the comparisons to predicates above ... (or would it? Those
2450 * wouldn't have outer refs)
2452 if (best_path->path.param_info)
2454 stripped_indexquals = (List *)
2455 replace_nestloop_params(root, (Node *) stripped_indexquals);
2457 replace_nestloop_params(root, (Node *) qpqual);
2458 indexorderbys = (List *)
2459 replace_nestloop_params(root, (Node *) indexorderbys);
2463 * If there are ORDER BY expressions, look up the sort operators for their
2468 ListCell *pathkeyCell,
2472 * PathKey contains OID of the btree opfamily we're sorting by, but
2473 * that's not quite enough because we need the expression's datatype
2474 * to look up the sort operator in the operator family.
2476 Assert(list_length(best_path->path.pathkeys) == list_length(indexorderbys));
2477 forboth(pathkeyCell, best_path->path.pathkeys, exprCell, indexorderbys)
2479 PathKey *pathkey = (PathKey *) lfirst(pathkeyCell);
2480 Node *expr = (Node *) lfirst(exprCell);
2481 Oid exprtype = exprType(expr);
2484 /* Get sort operator from opfamily */
2485 sortop = get_opfamily_member(pathkey->pk_opfamily,
2488 pathkey->pk_strategy);
2489 if (!OidIsValid(sortop))
2490 elog(ERROR, "failed to find sort operator for ORDER BY expression");
2491 indexorderbyops = lappend_oid(indexorderbyops, sortop);
2495 /* Finally ready to build the plan node */
2497 scan_plan = (Scan *) make_indexonlyscan(tlist,
2502 fixed_indexorderbys,
2503 best_path->indexinfo->indextlist,
2504 best_path->indexscandir);
2506 scan_plan = (Scan *) make_indexscan(tlist,
2511 stripped_indexquals,
2512 fixed_indexorderbys,
2515 best_path->indexscandir);
2517 copy_generic_path_info(&scan_plan->plan, &best_path->path);
2523 * create_bitmap_scan_plan
2524 * Returns a bitmap scan plan for the base relation scanned by 'best_path'
2525 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2527 static BitmapHeapScan *
2528 create_bitmap_scan_plan(PlannerInfo *root,
2529 BitmapHeapPath *best_path,
2533 Index baserelid = best_path->path.parent->relid;
2534 Plan *bitmapqualplan;
2535 List *bitmapqualorig;
2540 BitmapHeapScan *scan_plan;
2542 /* it should be a base rel... */
2543 Assert(baserelid > 0);
2544 Assert(best_path->path.parent->rtekind == RTE_RELATION);
2546 /* Process the bitmapqual tree into a Plan tree and qual lists */
2547 bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
2548 &bitmapqualorig, &indexquals,
2552 * The qpqual list must contain all restrictions not automatically handled
2553 * by the index, other than pseudoconstant clauses which will be handled
2554 * by a separate gating plan node. All the predicates in the indexquals
2555 * will be checked (either by the index itself, or by
2556 * nodeBitmapHeapscan.c), but if there are any "special" operators
2557 * involved then they must be added to qpqual. The upshot is that qpqual
2558 * must contain scan_clauses minus whatever appears in indexquals.
2560 * This loop is similar to the comparable code in create_indexscan_plan(),
2561 * but with some differences because it has to compare the scan clauses to
2562 * stripped (no RestrictInfos) indexquals. See comments there for more
2565 * In normal cases simple equal() checks will be enough to spot duplicate
2566 * clauses, so we try that first. We next see if the scan clause is
2567 * redundant with any top-level indexqual by virtue of being generated
2568 * from the same EC. After that, try predicate_implied_by().
2570 * Unlike create_indexscan_plan(), the predicate_implied_by() test here is
2571 * useful for getting rid of qpquals that are implied by index predicates,
2572 * because the predicate conditions are included in the "indexquals"
2573 * returned by create_bitmap_subplan(). Bitmap scans have to do it that
2574 * way because predicate conditions need to be rechecked if the scan
2575 * becomes lossy, so they have to be included in bitmapqualorig.
2578 foreach(l, scan_clauses)
2580 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2581 Node *clause = (Node *) rinfo->clause;
2583 Assert(IsA(rinfo, RestrictInfo));
2584 if (rinfo->pseudoconstant)
2585 continue; /* we may drop pseudoconstants here */
2586 if (list_member(indexquals, clause))
2587 continue; /* simple duplicate */
2588 if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
2589 continue; /* derived from same EquivalenceClass */
2590 if (!contain_mutable_functions(clause) &&
2591 predicate_implied_by(list_make1(clause), indexquals))
2592 continue; /* provably implied by indexquals */
2593 qpqual = lappend(qpqual, rinfo);
2596 /* Sort clauses into best execution order */
2597 qpqual = order_qual_clauses(root, qpqual);
2599 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2600 qpqual = extract_actual_clauses(qpqual, false);
2603 * When dealing with special operators, we will at this point have
2604 * duplicate clauses in qpqual and bitmapqualorig. We may as well drop
2605 * 'em from bitmapqualorig, since there's no point in making the tests
2608 bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
2611 * We have to replace any outer-relation variables with nestloop params in
2612 * the qpqual and bitmapqualorig expressions. (This was already done for
2613 * expressions attached to plan nodes in the bitmapqualplan tree.)
2615 if (best_path->path.param_info)
2618 replace_nestloop_params(root, (Node *) qpqual);
2619 bitmapqualorig = (List *)
2620 replace_nestloop_params(root, (Node *) bitmapqualorig);
2623 /* Finally ready to build the plan node */
2624 scan_plan = make_bitmap_heapscan(tlist,
2630 copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
2636 * Given a bitmapqual tree, generate the Plan tree that implements it
2638 * As byproducts, we also return in *qual and *indexqual the qual lists
2639 * (in implicit-AND form, without RestrictInfos) describing the original index
2640 * conditions and the generated indexqual conditions. (These are the same in
2641 * simple cases, but when special index operators are involved, the former
2642 * list includes the special conditions while the latter includes the actual
2643 * indexable conditions derived from them.) Both lists include partial-index
2644 * predicates, because we have to recheck predicates as well as index
2645 * conditions if the bitmap scan becomes lossy.
2647 * In addition, we return a list of EquivalenceClass pointers for all the
2648 * top-level indexquals that were possibly-redundantly derived from ECs.
2649 * This allows removal of scan_clauses that are redundant with such quals.
2650 * (We do not attempt to detect such redundancies for quals that are within
2651 * OR subtrees. This could be done in a less hacky way if we returned the
2652 * indexquals in RestrictInfo form, but that would be slower and still pretty
2653 * messy, since we'd have to build new RestrictInfos in many cases.)
2656 create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
2657 List **qual, List **indexqual, List **indexECs)
2661 if (IsA(bitmapqual, BitmapAndPath))
2663 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
2664 List *subplans = NIL;
2665 List *subquals = NIL;
2666 List *subindexquals = NIL;
2667 List *subindexECs = NIL;
2671 * There may well be redundant quals among the subplans, since a
2672 * top-level WHERE qual might have gotten used to form several
2673 * different index quals. We don't try exceedingly hard to eliminate
2674 * redundancies, but we do eliminate obvious duplicates by using
2675 * list_concat_unique.
2677 foreach(l, apath->bitmapquals)
2684 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
2685 &subqual, &subindexqual,
2687 subplans = lappend(subplans, subplan);
2688 subquals = list_concat_unique(subquals, subqual);
2689 subindexquals = list_concat_unique(subindexquals, subindexqual);
2690 /* Duplicates in indexECs aren't worth getting rid of */
2691 subindexECs = list_concat(subindexECs, subindexEC);
2693 plan = (Plan *) make_bitmap_and(subplans);
2694 plan->startup_cost = apath->path.startup_cost;
2695 plan->total_cost = apath->path.total_cost;
2697 clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
2698 plan->plan_width = 0; /* meaningless */
2699 plan->parallel_aware = false;
2701 *indexqual = subindexquals;
2702 *indexECs = subindexECs;
2704 else if (IsA(bitmapqual, BitmapOrPath))
2706 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
2707 List *subplans = NIL;
2708 List *subquals = NIL;
2709 List *subindexquals = NIL;
2710 bool const_true_subqual = false;
2711 bool const_true_subindexqual = false;
2715 * Here, we only detect qual-free subplans. A qual-free subplan would
2716 * cause us to generate "... OR true ..." which we may as well reduce
2717 * to just "true". We do not try to eliminate redundant subclauses
2718 * because (a) it's not as likely as in the AND case, and (b) we might
2719 * well be working with hundreds or even thousands of OR conditions,
2720 * perhaps from a long IN list. The performance of list_append_unique
2721 * would be unacceptable.
2723 foreach(l, opath->bitmapquals)
2730 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
2731 &subqual, &subindexqual,
2733 subplans = lappend(subplans, subplan);
2735 const_true_subqual = true;
2736 else if (!const_true_subqual)
2737 subquals = lappend(subquals,
2738 make_ands_explicit(subqual));
2739 if (subindexqual == NIL)
2740 const_true_subindexqual = true;
2741 else if (!const_true_subindexqual)
2742 subindexquals = lappend(subindexquals,
2743 make_ands_explicit(subindexqual));
2747 * In the presence of ScalarArrayOpExpr quals, we might have built
2748 * BitmapOrPaths with just one subpath; don't add an OR step.
2750 if (list_length(subplans) == 1)
2752 plan = (Plan *) linitial(subplans);
2756 plan = (Plan *) make_bitmap_or(subplans);
2757 plan->startup_cost = opath->path.startup_cost;
2758 plan->total_cost = opath->path.total_cost;
2760 clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
2761 plan->plan_width = 0; /* meaningless */
2762 plan->parallel_aware = false;
2766 * If there were constant-TRUE subquals, the OR reduces to constant
2767 * TRUE. Also, avoid generating one-element ORs, which could happen
2768 * due to redundancy elimination or ScalarArrayOpExpr quals.
2770 if (const_true_subqual)
2772 else if (list_length(subquals) <= 1)
2775 *qual = list_make1(make_orclause(subquals));
2776 if (const_true_subindexqual)
2778 else if (list_length(subindexquals) <= 1)
2779 *indexqual = subindexquals;
2781 *indexqual = list_make1(make_orclause(subindexquals));
2784 else if (IsA(bitmapqual, IndexPath))
2786 IndexPath *ipath = (IndexPath *) bitmapqual;
2791 /* Use the regular indexscan plan build machinery... */
2792 iscan = (IndexScan *) create_indexscan_plan(root, ipath,
2794 Assert(IsA(iscan, IndexScan));
2795 /* then convert to a bitmap indexscan */
2796 plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
2799 iscan->indexqualorig);
2800 /* and set its cost/width fields appropriately */
2801 plan->startup_cost = 0.0;
2802 plan->total_cost = ipath->indextotalcost;
2804 clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
2805 plan->plan_width = 0; /* meaningless */
2806 plan->parallel_aware = false;
2807 *qual = get_actual_clauses(ipath->indexclauses);
2808 *indexqual = get_actual_clauses(ipath->indexquals);
2809 foreach(l, ipath->indexinfo->indpred)
2811 Expr *pred = (Expr *) lfirst(l);
2814 * We know that the index predicate must have been implied by the
2815 * query condition as a whole, but it may or may not be implied by
2816 * the conditions that got pushed into the bitmapqual. Avoid
2817 * generating redundant conditions.
2819 if (!predicate_implied_by(list_make1(pred), ipath->indexclauses))
2821 *qual = lappend(*qual, pred);
2822 *indexqual = lappend(*indexqual, pred);
2826 foreach(l, ipath->indexquals)
2828 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2830 if (rinfo->parent_ec)
2831 subindexECs = lappend(subindexECs, rinfo->parent_ec);
2833 *indexECs = subindexECs;
2837 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
2838 plan = NULL; /* keep compiler quiet */
2845 * create_tidscan_plan
2846 * Returns a tidscan plan for the base relation scanned by 'best_path'
2847 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2850 create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
2851 List *tlist, List *scan_clauses)
2854 Index scan_relid = best_path->path.parent->relid;
2855 List *tidquals = best_path->tidquals;
2858 /* it should be a base rel... */
2859 Assert(scan_relid > 0);
2860 Assert(best_path->path.parent->rtekind == RTE_RELATION);
2862 /* Sort clauses into best execution order */
2863 scan_clauses = order_qual_clauses(root, scan_clauses);
2865 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2866 scan_clauses = extract_actual_clauses(scan_clauses, false);
2868 /* Replace any outer-relation variables with nestloop params */
2869 if (best_path->path.param_info)
2872 replace_nestloop_params(root, (Node *) tidquals);
2873 scan_clauses = (List *)
2874 replace_nestloop_params(root, (Node *) scan_clauses);
2878 * Remove any clauses that are TID quals. This is a bit tricky since the
2879 * tidquals list has implicit OR semantics.
2881 ortidquals = tidquals;
2882 if (list_length(ortidquals) > 1)
2883 ortidquals = list_make1(make_orclause(ortidquals));
2884 scan_clauses = list_difference(scan_clauses, ortidquals);
2886 scan_plan = make_tidscan(tlist,
2891 copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
2897 * create_subqueryscan_plan
2898 * Returns a subqueryscan plan for the base relation scanned by 'best_path'
2899 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2901 static SubqueryScan *
2902 create_subqueryscan_plan(PlannerInfo *root, SubqueryScanPath *best_path,
2903 List *tlist, List *scan_clauses)
2905 SubqueryScan *scan_plan;
2906 RelOptInfo *rel = best_path->path.parent;
2907 Index scan_relid = rel->relid;
2910 /* it should be a subquery base rel... */
2911 Assert(scan_relid > 0);
2912 Assert(rel->rtekind == RTE_SUBQUERY);
2915 * Recursively create Plan from Path for subquery. Since we are entering
2916 * a different planner context (subroot), recurse to create_plan not
2917 * create_plan_recurse.
2919 subplan = create_plan(rel->subroot, best_path->subpath);
2921 /* Sort clauses into best execution order */
2922 scan_clauses = order_qual_clauses(root, scan_clauses);
2924 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2925 scan_clauses = extract_actual_clauses(scan_clauses, false);
2927 /* Replace any outer-relation variables with nestloop params */
2928 if (best_path->path.param_info)
2930 scan_clauses = (List *)
2931 replace_nestloop_params(root, (Node *) scan_clauses);
2932 process_subquery_nestloop_params(root,
2933 rel->subplan_params);
2936 scan_plan = make_subqueryscan(tlist,
2941 copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
2947 * create_functionscan_plan
2948 * Returns a functionscan plan for the base relation scanned by 'best_path'
2949 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2951 static FunctionScan *
2952 create_functionscan_plan(PlannerInfo *root, Path *best_path,
2953 List *tlist, List *scan_clauses)
2955 FunctionScan *scan_plan;
2956 Index scan_relid = best_path->parent->relid;
2960 /* it should be a function base rel... */
2961 Assert(scan_relid > 0);
2962 rte = planner_rt_fetch(scan_relid, root);
2963 Assert(rte->rtekind == RTE_FUNCTION);
2964 functions = rte->functions;
2966 /* Sort clauses into best execution order */
2967 scan_clauses = order_qual_clauses(root, scan_clauses);
2969 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2970 scan_clauses = extract_actual_clauses(scan_clauses, false);
2972 /* Replace any outer-relation variables with nestloop params */
2973 if (best_path->param_info)
2975 scan_clauses = (List *)
2976 replace_nestloop_params(root, (Node *) scan_clauses);
2977 /* The function expressions could contain nestloop params, too */
2978 functions = (List *) replace_nestloop_params(root, (Node *) functions);
2981 scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
2982 functions, rte->funcordinality);
2984 copy_generic_path_info(&scan_plan->scan.plan, best_path);
2990 * create_valuesscan_plan
2991 * Returns a valuesscan plan for the base relation scanned by 'best_path'
2992 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2995 create_valuesscan_plan(PlannerInfo *root, Path *best_path,
2996 List *tlist, List *scan_clauses)
2998 ValuesScan *scan_plan;
2999 Index scan_relid = best_path->parent->relid;
3003 /* it should be a values base rel... */
3004 Assert(scan_relid > 0);
3005 rte = planner_rt_fetch(scan_relid, root);
3006 Assert(rte->rtekind == RTE_VALUES);
3007 values_lists = rte->values_lists;
3009 /* Sort clauses into best execution order */
3010 scan_clauses = order_qual_clauses(root, scan_clauses);
3012 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3013 scan_clauses = extract_actual_clauses(scan_clauses, false);
3015 /* Replace any outer-relation variables with nestloop params */
3016 if (best_path->param_info)
3018 scan_clauses = (List *)
3019 replace_nestloop_params(root, (Node *) scan_clauses);
3020 /* The values lists could contain nestloop params, too */
3021 values_lists = (List *)
3022 replace_nestloop_params(root, (Node *) values_lists);
3025 scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid,
3028 copy_generic_path_info(&scan_plan->scan.plan, best_path);
3034 * create_ctescan_plan
3035 * Returns a ctescan plan for the base relation scanned by 'best_path'
3036 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3039 create_ctescan_plan(PlannerInfo *root, Path *best_path,
3040 List *tlist, List *scan_clauses)
3043 Index scan_relid = best_path->parent->relid;
3045 SubPlan *ctesplan = NULL;
3048 PlannerInfo *cteroot;
3053 Assert(scan_relid > 0);
3054 rte = planner_rt_fetch(scan_relid, root);
3055 Assert(rte->rtekind == RTE_CTE);
3056 Assert(!rte->self_reference);
3059 * Find the referenced CTE, and locate the SubPlan previously made for it.
3061 levelsup = rte->ctelevelsup;
3063 while (levelsup-- > 0)
3065 cteroot = cteroot->parent_root;
3066 if (!cteroot) /* shouldn't happen */
3067 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3071 * Note: cte_plan_ids can be shorter than cteList, if we are still working
3072 * on planning the CTEs (ie, this is a side-reference from another CTE).
3073 * So we mustn't use forboth here.
3076 foreach(lc, cteroot->parse->cteList)
3078 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
3080 if (strcmp(cte->ctename, rte->ctename) == 0)
3084 if (lc == NULL) /* shouldn't happen */
3085 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
3086 if (ndx >= list_length(cteroot->cte_plan_ids))
3087 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3088 plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
3089 Assert(plan_id > 0);
3090 foreach(lc, cteroot->init_plans)
3092 ctesplan = (SubPlan *) lfirst(lc);
3093 if (ctesplan->plan_id == plan_id)
3096 if (lc == NULL) /* shouldn't happen */
3097 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3100 * We need the CTE param ID, which is the sole member of the SubPlan's
3103 cte_param_id = linitial_int(ctesplan->setParam);
3105 /* Sort clauses into best execution order */
3106 scan_clauses = order_qual_clauses(root, scan_clauses);
3108 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3109 scan_clauses = extract_actual_clauses(scan_clauses, false);
3111 /* Replace any outer-relation variables with nestloop params */
3112 if (best_path->param_info)
3114 scan_clauses = (List *)
3115 replace_nestloop_params(root, (Node *) scan_clauses);
3118 scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
3119 plan_id, cte_param_id);
3121 copy_generic_path_info(&scan_plan->scan.plan, best_path);
3127 * create_worktablescan_plan
3128 * Returns a worktablescan plan for the base relation scanned by 'best_path'
3129 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3131 static WorkTableScan *
3132 create_worktablescan_plan(PlannerInfo *root, Path *best_path,
3133 List *tlist, List *scan_clauses)
3135 WorkTableScan *scan_plan;
3136 Index scan_relid = best_path->parent->relid;
3139 PlannerInfo *cteroot;
3141 Assert(scan_relid > 0);
3142 rte = planner_rt_fetch(scan_relid, root);
3143 Assert(rte->rtekind == RTE_CTE);
3144 Assert(rte->self_reference);
3147 * We need to find the worktable param ID, which is in the plan level
3148 * that's processing the recursive UNION, which is one level *below* where
3149 * the CTE comes from.
3151 levelsup = rte->ctelevelsup;
3152 if (levelsup == 0) /* shouldn't happen */
3153 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3156 while (levelsup-- > 0)
3158 cteroot = cteroot->parent_root;
3159 if (!cteroot) /* shouldn't happen */
3160 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3162 if (cteroot->wt_param_id < 0) /* shouldn't happen */
3163 elog(ERROR, "could not find param ID for CTE \"%s\"", rte->ctename);
3165 /* Sort clauses into best execution order */
3166 scan_clauses = order_qual_clauses(root, scan_clauses);
3168 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3169 scan_clauses = extract_actual_clauses(scan_clauses, false);
3171 /* Replace any outer-relation variables with nestloop params */
3172 if (best_path->param_info)
3174 scan_clauses = (List *)
3175 replace_nestloop_params(root, (Node *) scan_clauses);
3178 scan_plan = make_worktablescan(tlist, scan_clauses, scan_relid,
3179 cteroot->wt_param_id);
3181 copy_generic_path_info(&scan_plan->scan.plan, best_path);
3187 * create_foreignscan_plan
3188 * Returns a foreignscan plan for the relation scanned by 'best_path'
3189 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
3191 static ForeignScan *
3192 create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
3193 List *tlist, List *scan_clauses)
3195 ForeignScan *scan_plan;
3196 RelOptInfo *rel = best_path->path.parent;
3197 Index scan_relid = rel->relid;
3198 Oid rel_oid = InvalidOid;
3199 Plan *outer_plan = NULL;
3201 Assert(rel->fdwroutine != NULL);
3203 /* transform the child path if any */
3204 if (best_path->fdw_outerpath)
3205 outer_plan = create_plan_recurse(root, best_path->fdw_outerpath,
3209 * If we're scanning a base relation, fetch its OID. (Irrelevant if
3210 * scanning a join relation.)
3216 Assert(rel->rtekind == RTE_RELATION);
3217 rte = planner_rt_fetch(scan_relid, root);
3218 Assert(rte->rtekind == RTE_RELATION);
3219 rel_oid = rte->relid;
3223 * Sort clauses into best execution order. We do this first since the FDW
3224 * might have more info than we do and wish to adjust the ordering.
3226 scan_clauses = order_qual_clauses(root, scan_clauses);
3229 * Let the FDW perform its processing on the restriction clauses and
3230 * generate the plan node. Note that the FDW might remove restriction
3231 * clauses that it intends to execute remotely, or even add more (if it
3232 * has selected some join clauses for remote use but also wants them
3233 * rechecked locally).
3235 scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid,
3237 tlist, scan_clauses,
3240 /* Copy cost data from Path to Plan; no need to make FDW do this */
3241 copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3243 /* Copy foreign server OID; likewise, no need to make FDW do this */
3244 scan_plan->fs_server = rel->serverid;
3247 * Likewise, copy the relids that are represented by this foreign scan. An
3248 * upper rel doesn't have relids set, but it covers all the base relations
3249 * participating in the underlying scan, so use root's all_baserels.
3251 if (rel->reloptkind == RELOPT_UPPER_REL)
3252 scan_plan->fs_relids = root->all_baserels;
3254 scan_plan->fs_relids = best_path->path.parent->relids;
3257 * If this is a foreign join, and to make it valid to push down we had to
3258 * assume that the current user is the same as some user explicitly named
3259 * in the query, mark the finished plan as depending on the current user.
3261 if (rel->useridiscurrent)
3262 root->glob->dependsOnRole = true;
3265 * Replace any outer-relation variables with nestloop params in the qual,
3266 * fdw_exprs and fdw_recheck_quals expressions. We do this last so that
3267 * the FDW doesn't have to be involved. (Note that parts of fdw_exprs or
3268 * fdw_recheck_quals could have come from join clauses, so doing this
3269 * beforehand on the scan_clauses wouldn't work.) We assume
3270 * fdw_scan_tlist contains no such variables.
3272 if (best_path->path.param_info)
3274 scan_plan->scan.plan.qual = (List *)
3275 replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
3276 scan_plan->fdw_exprs = (List *)
3277 replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
3278 scan_plan->fdw_recheck_quals = (List *)
3279 replace_nestloop_params(root,
3280 (Node *) scan_plan->fdw_recheck_quals);
3284 * If rel is a base relation, detect whether any system columns are
3285 * requested from the rel. (If rel is a join relation, rel->relid will be
3286 * 0, but there can be no Var with relid 0 in the rel's targetlist or the
3287 * restriction clauses, so we skip this in that case. Note that any such
3288 * columns in base relations that were joined are assumed to be contained
3289 * in fdw_scan_tlist.) This is a bit of a kluge and might go away
3290 * someday, so we intentionally leave it out of the API presented to FDWs.
3292 scan_plan->fsSystemCol = false;
3295 Bitmapset *attrs_used = NULL;
3300 * First, examine all the attributes needed for joins or final output.
3301 * Note: we must look at rel's targetlist, not the attr_needed data,
3302 * because attr_needed isn't computed for inheritance child rels.
3304 pull_varattnos((Node *) rel->reltarget->exprs, scan_relid, &attrs_used);
3306 /* Add all the attributes used by restriction clauses. */
3307 foreach(lc, rel->baserestrictinfo)
3309 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3311 pull_varattnos((Node *) rinfo->clause, scan_relid, &attrs_used);
3314 /* Now, are any system columns requested from rel? */
3315 for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
3317 if (bms_is_member(i - FirstLowInvalidHeapAttributeNumber, attrs_used))
3319 scan_plan->fsSystemCol = true;
3324 bms_free(attrs_used);
3331 * create_custom_plan
3333 * Transform a CustomPath into a Plan.
3336 create_customscan_plan(PlannerInfo *root, CustomPath *best_path,
3337 List *tlist, List *scan_clauses)
3340 RelOptInfo *rel = best_path->path.parent;
3341 List *custom_plans = NIL;
3344 /* Recursively transform child paths. */
3345 foreach(lc, best_path->custom_paths)
3347 Plan *plan = create_plan_recurse(root, (Path *) lfirst(lc),
3350 custom_plans = lappend(custom_plans, plan);
3354 * Sort clauses into the best execution order, although custom-scan
3355 * provider can reorder them again.
3357 scan_clauses = order_qual_clauses(root, scan_clauses);
3360 * Invoke custom plan provider to create the Plan node represented by the
3363 cplan = (CustomScan *) best_path->methods->PlanCustomPath(root,
3369 Assert(IsA(cplan, CustomScan));
3372 * Copy cost data from Path to Plan; no need to make custom-plan providers
3375 copy_generic_path_info(&cplan->scan.plan, &best_path->path);
3377 /* Likewise, copy the relids that are represented by this custom scan */
3378 cplan->custom_relids = best_path->path.parent->relids;
3381 * Replace any outer-relation variables with nestloop params in the qual
3382 * and custom_exprs expressions. We do this last so that the custom-plan
3383 * provider doesn't have to be involved. (Note that parts of custom_exprs
3384 * could have come from join clauses, so doing this beforehand on the
3385 * scan_clauses wouldn't work.) We assume custom_scan_tlist contains no
3388 if (best_path->path.param_info)
3390 cplan->scan.plan.qual = (List *)
3391 replace_nestloop_params(root, (Node *) cplan->scan.plan.qual);
3392 cplan->custom_exprs = (List *)
3393 replace_nestloop_params(root, (Node *) cplan->custom_exprs);
3400 /*****************************************************************************
3404 *****************************************************************************/
3407 create_nestloop_plan(PlannerInfo *root,
3408 NestPath *best_path)
3410 NestLoop *join_plan;
3413 List *tlist = build_path_tlist(root, &best_path->path);
3414 List *joinrestrictclauses = best_path->joinrestrictinfo;
3419 Relids saveOuterRels = root->curOuterRels;
3424 /* NestLoop can project, so no need to be picky about child tlists */
3425 outer_plan = create_plan_recurse(root, best_path->outerjoinpath, 0);
3427 /* For a nestloop, include outer relids in curOuterRels for inner side */
3428 root->curOuterRels = bms_union(root->curOuterRels,
3429 best_path->outerjoinpath->parent->relids);
3431 inner_plan = create_plan_recurse(root, best_path->innerjoinpath, 0);
3433 /* Restore curOuterRels */
3434 bms_free(root->curOuterRels);
3435 root->curOuterRels = saveOuterRels;
3437 /* Sort join qual clauses into best execution order */
3438 joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
3440 /* Get the join qual clauses (in plain expression form) */
3441 /* Any pseudoconstant clauses are ignored here */
3442 if (IS_OUTER_JOIN(best_path->jointype))
3444 extract_actual_join_clauses(joinrestrictclauses,
3445 &joinclauses, &otherclauses);
3449 /* We can treat all clauses alike for an inner join */
3450 joinclauses = extract_actual_clauses(joinrestrictclauses, false);
3454 /* Replace any outer-relation variables with nestloop params */
3455 if (best_path->path.param_info)
3457 joinclauses = (List *)
3458 replace_nestloop_params(root, (Node *) joinclauses);
3459 otherclauses = (List *)
3460 replace_nestloop_params(root, (Node *) otherclauses);
3464 * Identify any nestloop parameters that should be supplied by this join
3465 * node, and move them from root->curOuterParams to the nestParams list.
3467 outerrelids = best_path->outerjoinpath->parent->relids;
3470 for (cell = list_head(root->curOuterParams); cell; cell = next)
3472 NestLoopParam *nlp = (NestLoopParam *) lfirst(cell);
3475 if (IsA(nlp->paramval, Var) &&
3476 bms_is_member(nlp->paramval->varno, outerrelids))
3478 root->curOuterParams = list_delete_cell(root->curOuterParams,
3480 nestParams = lappend(nestParams, nlp);
3482 else if (IsA(nlp->paramval, PlaceHolderVar) &&
3483 bms_overlap(((PlaceHolderVar *) nlp->paramval)->phrels,
3485 bms_is_subset(find_placeholder_info(root,
3486 (PlaceHolderVar *) nlp->paramval,
3490 root->curOuterParams = list_delete_cell(root->curOuterParams,
3492 nestParams = lappend(nestParams, nlp);
3498 join_plan = make_nestloop(tlist,
3504 best_path->jointype);
3506 copy_generic_path_info(&join_plan->join.plan, &best_path->path);
3512 create_mergejoin_plan(PlannerInfo *root,
3513 MergePath *best_path)
3515 MergeJoin *join_plan;
3518 List *tlist = build_path_tlist(root, &best_path->jpath.path);
3522 List *outerpathkeys;
3523 List *innerpathkeys;
3526 Oid *mergecollations;
3527 int *mergestrategies;
3528 bool *mergenullsfirst;
3535 * MergeJoin can project, so we don't have to demand exact tlists from the
3536 * inputs. However, if we're intending to sort an input's result, it's
3537 * best to request a small tlist so we aren't sorting more data than
3540 outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
3541 (best_path->outersortkeys != NIL) ? CP_SMALL_TLIST : 0);
3543 inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
3544 (best_path->innersortkeys != NIL) ? CP_SMALL_TLIST : 0);
3546 /* Sort join qual clauses into best execution order */
3547 /* NB: do NOT reorder the mergeclauses */
3548 joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
3550 /* Get the join qual clauses (in plain expression form) */
3551 /* Any pseudoconstant clauses are ignored here */
3552 if (IS_OUTER_JOIN(best_path->jpath.jointype))
3554 extract_actual_join_clauses(joinclauses,
3555 &joinclauses, &otherclauses);
3559 /* We can treat all clauses alike for an inner join */
3560 joinclauses = extract_actual_clauses(joinclauses, false);
3565 * Remove the mergeclauses from the list of join qual clauses, leaving the
3566 * list of quals that must be checked as qpquals.
3568 mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
3569 joinclauses = list_difference(joinclauses, mergeclauses);
3572 * Replace any outer-relation variables with nestloop params. There
3573 * should not be any in the mergeclauses.
3575 if (best_path->jpath.path.param_info)
3577 joinclauses = (List *)
3578 replace_nestloop_params(root, (Node *) joinclauses);
3579 otherclauses = (List *)
3580 replace_nestloop_params(root, (Node *) otherclauses);
3584 * Rearrange mergeclauses, if needed, so that the outer variable is always
3585 * on the left; mark the mergeclause restrictinfos with correct
3586 * outer_is_left status.
3588 mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
3589 best_path->jpath.outerjoinpath->parent->relids);
3592 * Create explicit sort nodes for the outer and inner paths if necessary.
3594 if (best_path->outersortkeys)
3596 Sort *sort = make_sort_from_pathkeys(outer_plan,
3597 best_path->outersortkeys);
3599 label_sort_with_costsize(root, sort, -1.0);
3600 outer_plan = (Plan *) sort;
3601 outerpathkeys = best_path->outersortkeys;
3604 outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
3606 if (best_path->innersortkeys)
3608 Sort *sort = make_sort_from_pathkeys(inner_plan,
3609 best_path->innersortkeys);
3611 label_sort_with_costsize(root, sort, -1.0);
3612 inner_plan = (Plan *) sort;
3613 innerpathkeys = best_path->innersortkeys;
3616 innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
3619 * If specified, add a materialize node to shield the inner plan from the
3620 * need to handle mark/restore.
3622 if (best_path->materialize_inner)
3624 Plan *matplan = (Plan *) make_material(inner_plan);
3627 * We assume the materialize will not spill to disk, and therefore
3628 * charge just cpu_operator_cost per tuple. (Keep this estimate in
3629 * sync with final_cost_mergejoin.)
3631 copy_plan_costsize(matplan, inner_plan);
3632 matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
3634 inner_plan = matplan;
3638 * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
3639 * executor. The information is in the pathkeys for the two inputs, but
3640 * we need to be careful about the possibility of mergeclauses sharing a
3641 * pathkey (compare find_mergeclauses_for_pathkeys()).
3643 nClauses = list_length(mergeclauses);
3644 Assert(nClauses == list_length(best_path->path_mergeclauses));
3645 mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
3646 mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
3647 mergestrategies = (int *) palloc(nClauses * sizeof(int));
3648 mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
3650 lop = list_head(outerpathkeys);
3651 lip = list_head(innerpathkeys);
3653 foreach(lc, best_path->path_mergeclauses)
3655 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3656 EquivalenceClass *oeclass;
3657 EquivalenceClass *ieclass;
3660 EquivalenceClass *opeclass;
3661 EquivalenceClass *ipeclass;
3664 /* fetch outer/inner eclass from mergeclause */
3665 Assert(IsA(rinfo, RestrictInfo));
3666 if (rinfo->outer_is_left)
3668 oeclass = rinfo->left_ec;
3669 ieclass = rinfo->right_ec;
3673 oeclass = rinfo->right_ec;
3674 ieclass = rinfo->left_ec;
3676 Assert(oeclass != NULL);
3677 Assert(ieclass != NULL);
3680 * For debugging purposes, we check that the eclasses match the paths'
3681 * pathkeys. In typical cases the merge clauses are one-to-one with
3682 * the pathkeys, but when dealing with partially redundant query
3683 * conditions, we might have clauses that re-reference earlier path
3684 * keys. The case that we need to reject is where a pathkey is
3685 * entirely skipped over.
3687 * lop and lip reference the first as-yet-unused pathkey elements;
3688 * it's okay to match them, or any element before them. If they're
3689 * NULL then we have found all pathkey elements to be used.
3693 opathkey = (PathKey *) lfirst(lop);
3694 opeclass = opathkey->pk_eclass;
3695 if (oeclass == opeclass)
3697 /* fast path for typical case */
3702 /* redundant clauses ... must match something before lop */
3703 foreach(l2, outerpathkeys)
3707 opathkey = (PathKey *) lfirst(l2);
3708 opeclass = opathkey->pk_eclass;
3709 if (oeclass == opeclass)
3712 if (oeclass != opeclass)
3713 elog(ERROR, "outer pathkeys do not match mergeclauses");
3718 /* redundant clauses ... must match some already-used pathkey */
3721 foreach(l2, outerpathkeys)
3723 opathkey = (PathKey *) lfirst(l2);
3724 opeclass = opathkey->pk_eclass;
3725 if (oeclass == opeclass)
3729 elog(ERROR, "outer pathkeys do not match mergeclauses");
3734 ipathkey = (PathKey *) lfirst(lip);
3735 ipeclass = ipathkey->pk_eclass;
3736 if (ieclass == ipeclass)
3738 /* fast path for typical case */
3743 /* redundant clauses ... must match something before lip */
3744 foreach(l2, innerpathkeys)
3748 ipathkey = (PathKey *) lfirst(l2);
3749 ipeclass = ipathkey->pk_eclass;
3750 if (ieclass == ipeclass)
3753 if (ieclass != ipeclass)
3754 elog(ERROR, "inner pathkeys do not match mergeclauses");
3759 /* redundant clauses ... must match some already-used pathkey */
3762 foreach(l2, innerpathkeys)
3764 ipathkey = (PathKey *) lfirst(l2);
3765 ipeclass = ipathkey->pk_eclass;
3766 if (ieclass == ipeclass)
3770 elog(ERROR, "inner pathkeys do not match mergeclauses");
3773 /* pathkeys should match each other too (more debugging) */
3774 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
3775 opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
3776 opathkey->pk_strategy != ipathkey->pk_strategy ||
3777 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
3778 elog(ERROR, "left and right pathkeys do not match in mergejoin");
3780 /* OK, save info for executor */
3781 mergefamilies[i] = opathkey->pk_opfamily;
3782 mergecollations[i] = opathkey->pk_eclass->ec_collation;
3783 mergestrategies[i] = opathkey->pk_strategy;
3784 mergenullsfirst[i] = opathkey->pk_nulls_first;
3789 * Note: it is not an error if we have additional pathkey elements (i.e.,
3790 * lop or lip isn't NULL here). The input paths might be better-sorted
3791 * than we need for the current mergejoin.
3795 * Now we can build the mergejoin node.
3797 join_plan = make_mergejoin(tlist,
3807 best_path->jpath.jointype);
3809 /* Costs of sort and material steps are included in path cost already */
3810 copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
3816 create_hashjoin_plan(PlannerInfo *root,
3817 HashPath *best_path)
3819 HashJoin *join_plan;
3823 List *tlist = build_path_tlist(root, &best_path->jpath.path);
3827 Oid skewTable = InvalidOid;
3828 AttrNumber skewColumn = InvalidAttrNumber;
3829 bool skewInherit = false;
3830 Oid skewColType = InvalidOid;
3831 int32 skewColTypmod = -1;
3834 * HashJoin can project, so we don't have to demand exact tlists from the
3835 * inputs. However, it's best to request a small tlist from the inner
3836 * side, so that we aren't storing more data than necessary. Likewise, if
3837 * we anticipate batching, request a small tlist from the outer side so
3838 * that we don't put extra data in the outer batch files.
3840 outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
3841 (best_path->num_batches > 1) ? CP_SMALL_TLIST : 0);
3843 inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
3846 /* Sort join qual clauses into best execution order */
3847 joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
3848 /* There's no point in sorting the hash clauses ... */
3850 /* Get the join qual clauses (in plain expression form) */
3851 /* Any pseudoconstant clauses are ignored here */
3852 if (IS_OUTER_JOIN(best_path->jpath.jointype))
3854 extract_actual_join_clauses(joinclauses,
3855 &joinclauses, &otherclauses);
3859 /* We can treat all clauses alike for an inner join */
3860 joinclauses = extract_actual_clauses(joinclauses, false);
3865 * Remove the hashclauses from the list of join qual clauses, leaving the
3866 * list of quals that must be checked as qpquals.
3868 hashclauses = get_actual_clauses(best_path->path_hashclauses);
3869 joinclauses = list_difference(joinclauses, hashclauses);
3872 * Replace any outer-relation variables with nestloop params. There
3873 * should not be any in the hashclauses.
3875 if (best_path->jpath.path.param_info)
3877 joinclauses = (List *)
3878 replace_nestloop_params(root, (Node *) joinclauses);
3879 otherclauses = (List *)
3880 replace_nestloop_params(root, (Node *) otherclauses);
3884 * Rearrange hashclauses, if needed, so that the outer variable is always
3887 hashclauses = get_switched_clauses(best_path->path_hashclauses,
3888 best_path->jpath.outerjoinpath->parent->relids);
3891 * If there is a single join clause and we can identify the outer variable
3892 * as a simple column reference, supply its identity for possible use in
3893 * skew optimization. (Note: in principle we could do skew optimization
3894 * with multiple join clauses, but we'd have to be able to determine the
3895 * most common combinations of outer values, which we don't currently have
3896 * enough stats for.)
3898 if (list_length(hashclauses) == 1)
3900 OpExpr *clause = (OpExpr *) linitial(hashclauses);
3903 Assert(is_opclause(clause));
3904 node = (Node *) linitial(clause->args);
3905 if (IsA(node, RelabelType))
3906 node = (Node *) ((RelabelType *) node)->arg;
3909 Var *var = (Var *) node;
3912 rte = root->simple_rte_array[var->varno];
3913 if (rte->rtekind == RTE_RELATION)
3915 skewTable = rte->relid;
3916 skewColumn = var->varattno;
3917 skewInherit = rte->inh;
3918 skewColType = var->vartype;
3919 skewColTypmod = var->vartypmod;
3925 * Build the hash node and hash join node.
3927 hash_plan = make_hash(inner_plan,
3935 * Set Hash node's startup & total costs equal to total cost of input
3936 * plan; this only affects EXPLAIN display not decisions.
3938 copy_plan_costsize(&hash_plan->plan, inner_plan);
3939 hash_plan->plan.startup_cost = hash_plan->plan.total_cost;
3941 join_plan = make_hashjoin(tlist,
3947 best_path->jpath.jointype);
3949 copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
3955 /*****************************************************************************
3957 * SUPPORTING ROUTINES
3959 *****************************************************************************/
3962 * replace_nestloop_params
3963 * Replace outer-relation Vars and PlaceHolderVars in the given expression
3964 * with nestloop Params
3966 * All Vars and PlaceHolderVars belonging to the relation(s) identified by
3967 * root->curOuterRels are replaced by Params, and entries are added to
3968 * root->curOuterParams if not already present.
3971 replace_nestloop_params(PlannerInfo *root, Node *expr)
3973 /* No setup needed for tree walk, so away we go */
3974 return replace_nestloop_params_mutator(expr, root);
3978 replace_nestloop_params_mutator(Node *node, PlannerInfo *root)
3984 Var *var = (Var *) node;
3989 /* Upper-level Vars should be long gone at this point */
3990 Assert(var->varlevelsup == 0);
3991 /* If not to be replaced, we can just return the Var unmodified */
3992 if (!bms_is_member(var->varno, root->curOuterRels))
3994 /* Create a Param representing the Var */
3995 param = assign_nestloop_param_var(root, var);
3996 /* Is this param already listed in root->curOuterParams? */
3997 foreach(lc, root->curOuterParams)
3999 nlp = (NestLoopParam *) lfirst(lc);
4000 if (nlp->paramno == param->paramid)
4002 Assert(equal(var, nlp->paramval));
4003 /* Present, so we can just return the Param */
4004 return (Node *) param;
4008 nlp = makeNode(NestLoopParam);
4009 nlp->paramno = param->paramid;
4010 nlp->paramval = var;
4011 root->curOuterParams = lappend(root->curOuterParams, nlp);
4012 /* And return the replacement Param */
4013 return (Node *) param;
4015 if (IsA(node, PlaceHolderVar))
4017 PlaceHolderVar *phv = (PlaceHolderVar *) node;
4022 /* Upper-level PlaceHolderVars should be long gone at this point */
4023 Assert(phv->phlevelsup == 0);
4026 * Check whether we need to replace the PHV. We use bms_overlap as a
4027 * cheap/quick test to see if the PHV might be evaluated in the outer
4028 * rels, and then grab its PlaceHolderInfo to tell for sure.
4030 if (!bms_overlap(phv->phrels, root->curOuterRels) ||
4031 !bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
4032 root->curOuterRels))
4035 * We can't replace the whole PHV, but we might still need to
4036 * replace Vars or PHVs within its expression, in case it ends up
4037 * actually getting evaluated here. (It might get evaluated in
4038 * this plan node, or some child node; in the latter case we don't
4039 * really need to process the expression here, but we haven't got
4040 * enough info to tell if that's the case.) Flat-copy the PHV
4041 * node and then recurse on its expression.
4043 * Note that after doing this, we might have different
4044 * representations of the contents of the same PHV in different
4045 * parts of the plan tree. This is OK because equal() will just
4046 * match on phid/phlevelsup, so setrefs.c will still recognize an
4047 * upper-level reference to a lower-level copy of the same PHV.
4049 PlaceHolderVar *newphv = makeNode(PlaceHolderVar);
4051 memcpy(newphv, phv, sizeof(PlaceHolderVar));
4052 newphv->phexpr = (Expr *)
4053 replace_nestloop_params_mutator((Node *) phv->phexpr,
4055 return (Node *) newphv;
4057 /* Create a Param representing the PlaceHolderVar */
4058 param = assign_nestloop_param_placeholdervar(root, phv);
4059 /* Is this param already listed in root->curOuterParams? */
4060 foreach(lc, root->curOuterParams)
4062 nlp = (NestLoopParam *) lfirst(lc);
4063 if (nlp->paramno == param->paramid)
4065 Assert(equal(phv, nlp->paramval));
4066 /* Present, so we can just return the Param */
4067 return (Node *) param;
4071 nlp = makeNode(NestLoopParam);
4072 nlp->paramno = param->paramid;
4073 nlp->paramval = (Var *) phv;
4074 root->curOuterParams = lappend(root->curOuterParams, nlp);
4075 /* And return the replacement Param */
4076 return (Node *) param;
4078 return expression_tree_mutator(node,
4079 replace_nestloop_params_mutator,
4084 * process_subquery_nestloop_params
4085 * Handle params of a parameterized subquery that need to be fed
4086 * from an outer nestloop.
4088 * Currently, that would be *all* params that a subquery in FROM has demanded
4089 * from the current query level, since they must be LATERAL references.
4091 * The subplan's references to the outer variables are already represented
4092 * as PARAM_EXEC Params, so we need not modify the subplan here. What we
4093 * do need to do is add entries to root->curOuterParams to signal the parent
4094 * nestloop plan node that it must provide these values.
4097 process_subquery_nestloop_params(PlannerInfo *root, List *subplan_params)
4101 foreach(ppl, subplan_params)
4103 PlannerParamItem *pitem = (PlannerParamItem *) lfirst(ppl);
4105 if (IsA(pitem->item, Var))
4107 Var *var = (Var *) pitem->item;
4111 /* If not from a nestloop outer rel, complain */
4112 if (!bms_is_member(var->varno, root->curOuterRels))
4113 elog(ERROR, "non-LATERAL parameter required by subquery");
4114 /* Is this param already listed in root->curOuterParams? */
4115 foreach(lc, root->curOuterParams)
4117 nlp = (NestLoopParam *) lfirst(lc);
4118 if (nlp->paramno == pitem->paramId)
4120 Assert(equal(var, nlp->paramval));
4121 /* Present, so nothing to do */
4128 nlp = makeNode(NestLoopParam);
4129 nlp->paramno = pitem->paramId;
4130 nlp->paramval = copyObject(var);
4131 root->curOuterParams = lappend(root->curOuterParams, nlp);
4134 else if (IsA(pitem->item, PlaceHolderVar))
4136 PlaceHolderVar *phv = (PlaceHolderVar *) pitem->item;
4140 /* If not from a nestloop outer rel, complain */
4141 if (!bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
4142 root->curOuterRels))
4143 elog(ERROR, "non-LATERAL parameter required by subquery");
4144 /* Is this param already listed in root->curOuterParams? */
4145 foreach(lc, root->curOuterParams)
4147 nlp = (NestLoopParam *) lfirst(lc);
4148 if (nlp->paramno == pitem->paramId)
4150 Assert(equal(phv, nlp->paramval));
4151 /* Present, so nothing to do */
4158 nlp = makeNode(NestLoopParam);
4159 nlp->paramno = pitem->paramId;
4160 nlp->paramval = copyObject(phv);
4161 root->curOuterParams = lappend(root->curOuterParams, nlp);
4165 elog(ERROR, "unexpected type of subquery parameter");
4170 * fix_indexqual_references
4171 * Adjust indexqual clauses to the form the executor's indexqual
4174 * We have four tasks here:
4175 * * Remove RestrictInfo nodes from the input clauses.
4176 * * Replace any outer-relation Var or PHV nodes with nestloop Params.
4177 * (XXX eventually, that responsibility should go elsewhere?)
4178 * * Index keys must be represented by Var nodes with varattno set to the
4179 * index's attribute number, not the attribute number in the original rel.
4180 * * If the index key is on the right, commute the clause to put it on the
4183 * The result is a modified copy of the path's indexquals list --- the
4184 * original is not changed. Note also that the copy shares no substructure
4185 * with the original; this is needed in case there is a subplan in it (we need
4186 * two separate copies of the subplan tree, or things will go awry).
4189 fix_indexqual_references(PlannerInfo *root, IndexPath *index_path)
4191 IndexOptInfo *index = index_path->indexinfo;
4192 List *fixed_indexquals;
4196 fixed_indexquals = NIL;
4198 forboth(lcc, index_path->indexquals, lci, index_path->indexqualcols)
4200 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcc);
4201 int indexcol = lfirst_int(lci);
4204 Assert(IsA(rinfo, RestrictInfo));
4207 * Replace any outer-relation variables with nestloop params.
4209 * This also makes a copy of the clause, so it's safe to modify it
4212 clause = replace_nestloop_params(root, (Node *) rinfo->clause);
4214 if (IsA(clause, OpExpr))
4216 OpExpr *op = (OpExpr *) clause;
4218 if (list_length(op->args) != 2)
4219 elog(ERROR, "indexqual clause is not binary opclause");
4222 * Check to see if the indexkey is on the right; if so, commute
4223 * the clause. The indexkey should be the side that refers to
4224 * (only) the base relation.
4226 if (!bms_equal(rinfo->left_relids, index->rel->relids))
4230 * Now replace the indexkey expression with an index Var.
4232 linitial(op->args) = fix_indexqual_operand(linitial(op->args),
4236 else if (IsA(clause, RowCompareExpr))
4238 RowCompareExpr *rc = (RowCompareExpr *) clause;
4246 * Re-discover which index columns are used in the rowcompare.
4248 newrc = adjust_rowcompare_for_index(rc,
4255 * Trouble if adjust_rowcompare_for_index thought the
4256 * RowCompareExpr didn't match the index as-is; the clause should
4257 * have gone through that routine already.
4259 if (newrc != (Expr *) rc)
4260 elog(ERROR, "inconsistent results from adjust_rowcompare_for_index");
4263 * Check to see if the indexkey is on the right; if so, commute
4267 CommuteRowCompareExpr(rc);
4270 * Now replace the indexkey expressions with index Vars.
4272 Assert(list_length(rc->largs) == list_length(indexcolnos));
4273 forboth(lca, rc->largs, lcai, indexcolnos)
4275 lfirst(lca) = fix_indexqual_operand(lfirst(lca),
4280 else if (IsA(clause, ScalarArrayOpExpr))
4282 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
4284 /* Never need to commute... */
4286 /* Replace the indexkey expression with an index Var. */
4287 linitial(saop->args) = fix_indexqual_operand(linitial(saop->args),
4291 else if (IsA(clause, NullTest))
4293 NullTest *nt = (NullTest *) clause;
4295 /* Replace the indexkey expression with an index Var. */
4296 nt->arg = (Expr *) fix_indexqual_operand((Node *) nt->arg,
4301 elog(ERROR, "unsupported indexqual type: %d",
4302 (int) nodeTag(clause));
4304 fixed_indexquals = lappend(fixed_indexquals, clause);
4307 return fixed_indexquals;
4311 * fix_indexorderby_references
4312 * Adjust indexorderby clauses to the form the executor's index
4315 * This is a simplified version of fix_indexqual_references. The input does
4316 * not have RestrictInfo nodes, and we assume that indxpath.c already
4317 * commuted the clauses to put the index keys on the left. Also, we don't
4318 * bother to support any cases except simple OpExprs, since nothing else
4319 * is allowed for ordering operators.
4322 fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path)
4324 IndexOptInfo *index = index_path->indexinfo;
4325 List *fixed_indexorderbys;
4329 fixed_indexorderbys = NIL;
4331 forboth(lcc, index_path->indexorderbys, lci, index_path->indexorderbycols)
4333 Node *clause = (Node *) lfirst(lcc);
4334 int indexcol = lfirst_int(lci);
4337 * Replace any outer-relation variables with nestloop params.
4339 * This also makes a copy of the clause, so it's safe to modify it
4342 clause = replace_nestloop_params(root, clause);
4344 if (IsA(clause, OpExpr))
4346 OpExpr *op = (OpExpr *) clause;
4348 if (list_length(op->args) != 2)
4349 elog(ERROR, "indexorderby clause is not binary opclause");
4352 * Now replace the indexkey expression with an index Var.
4354 linitial(op->args) = fix_indexqual_operand(linitial(op->args),
4359 elog(ERROR, "unsupported indexorderby type: %d",
4360 (int) nodeTag(clause));
4362 fixed_indexorderbys = lappend(fixed_indexorderbys, clause);
4365 return fixed_indexorderbys;
4369 * fix_indexqual_operand
4370 * Convert an indexqual expression to a Var referencing the index column.
4372 * We represent index keys by Var nodes having varno == INDEX_VAR and varattno
4373 * equal to the index's attribute number (index column position).
4375 * Most of the code here is just for sanity cross-checking that the given
4376 * expression actually matches the index column it's claimed to.
4379 fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol)
4383 ListCell *indexpr_item;
4386 * Remove any binary-compatible relabeling of the indexkey
4388 if (IsA(node, RelabelType))
4389 node = (Node *) ((RelabelType *) node)->arg;
4391 Assert(indexcol >= 0 && indexcol < index->ncolumns);
4393 if (index->indexkeys[indexcol] != 0)
4395 /* It's a simple index column */
4396 if (IsA(node, Var) &&
4397 ((Var *) node)->varno == index->rel->relid &&
4398 ((Var *) node)->varattno == index->indexkeys[indexcol])
4400 result = (Var *) copyObject(node);
4401 result->varno = INDEX_VAR;
4402 result->varattno = indexcol + 1;
4403 return (Node *) result;
4406 elog(ERROR, "index key does not match expected index column");
4409 /* It's an index expression, so find and cross-check the expression */
4410 indexpr_item = list_head(index->indexprs);
4411 for (pos = 0; pos < index->ncolumns; pos++)
4413 if (index->indexkeys[pos] == 0)
4415 if (indexpr_item == NULL)
4416 elog(ERROR, "too few entries in indexprs list");
4417 if (pos == indexcol)
4421 indexkey = (Node *) lfirst(indexpr_item);
4422 if (indexkey && IsA(indexkey, RelabelType))
4423 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4424 if (equal(node, indexkey))
4426 result = makeVar(INDEX_VAR, indexcol + 1,
4427 exprType(lfirst(indexpr_item)), -1,
4428 exprCollation(lfirst(indexpr_item)),
4430 return (Node *) result;
4433 elog(ERROR, "index key does not match expected index column");
4435 indexpr_item = lnext(indexpr_item);
4440 elog(ERROR, "index key does not match expected index column");
4441 return NULL; /* keep compiler quiet */
4445 * get_switched_clauses
4446 * Given a list of merge or hash joinclauses (as RestrictInfo nodes),
4447 * extract the bare clauses, and rearrange the elements within the
4448 * clauses, if needed, so the outer join variable is on the left and
4449 * the inner is on the right. The original clause data structure is not
4450 * touched; a modified list is returned. We do, however, set the transient
4451 * outer_is_left field in each RestrictInfo to show which side was which.
4454 get_switched_clauses(List *clauses, Relids outerrelids)
4461 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
4462 OpExpr *clause = (OpExpr *) restrictinfo->clause;
4464 Assert(is_opclause(clause));
4465 if (bms_is_subset(restrictinfo->right_relids, outerrelids))
4468 * Duplicate just enough of the structure to allow commuting the
4469 * clause without changing the original list. Could use
4470 * copyObject, but a complete deep copy is overkill.
4472 OpExpr *temp = makeNode(OpExpr);
4474 temp->opno = clause->opno;
4475 temp->opfuncid = InvalidOid;
4476 temp->opresulttype = clause->opresulttype;
4477 temp->opretset = clause->opretset;
4478 temp->opcollid = clause->opcollid;
4479 temp->inputcollid = clause->inputcollid;
4480 temp->args = list_copy(clause->args);
4481 temp->location = clause->location;
4482 /* Commute it --- note this modifies the temp node in-place. */
4483 CommuteOpExpr(temp);
4484 t_list = lappend(t_list, temp);
4485 restrictinfo->outer_is_left = false;
4489 Assert(bms_is_subset(restrictinfo->left_relids, outerrelids));
4490 t_list = lappend(t_list, clause);
4491 restrictinfo->outer_is_left = true;
4498 * order_qual_clauses
4499 * Given a list of qual clauses that will all be evaluated at the same
4500 * plan node, sort the list into the order we want to check the quals
4503 * Ideally the order should be driven by a combination of execution cost and
4504 * selectivity, but it's not immediately clear how to account for both,
4505 * and given the uncertainty of the estimates the reliability of the decisions
4506 * would be doubtful anyway. So we just order by estimated per-tuple cost,
4507 * being careful not to change the order when (as is often the case) the
4508 * estimates are identical.
4510 * Although this will work on either bare clauses or RestrictInfos, it's
4511 * much faster to apply it to RestrictInfos, since it can re-use cost
4512 * information that is cached in RestrictInfos.
4514 * Note: some callers pass lists that contain entries that will later be
4515 * removed; this is the easiest way to let this routine see RestrictInfos
4516 * instead of bare clauses. It's OK because we only sort by cost, but
4517 * a cost/selectivity combination would likely do the wrong thing.
4520 order_qual_clauses(PlannerInfo *root, List *clauses)
4527 int nitems = list_length(clauses);
4533 /* No need to work hard for 0 or 1 clause */
4538 * Collect the items and costs into an array. This is to avoid repeated
4539 * cost_qual_eval work if the inputs aren't RestrictInfos.
4541 items = (QualItem *) palloc(nitems * sizeof(QualItem));
4543 foreach(lc, clauses)
4545 Node *clause = (Node *) lfirst(lc);
4548 cost_qual_eval_node(&qcost, clause, root);
4549 items[i].clause = clause;
4550 items[i].cost = qcost.per_tuple;
4555 * Sort. We don't use qsort() because it's not guaranteed stable for
4556 * equal keys. The expected number of entries is small enough that a
4557 * simple insertion sort should be good enough.
4559 for (i = 1; i < nitems; i++)
4561 QualItem newitem = items[i];
4564 /* insert newitem into the already-sorted subarray */
4565 for (j = i; j > 0; j--)
4567 if (newitem.cost >= items[j - 1].cost)
4569 items[j] = items[j - 1];
4574 /* Convert back to a list */
4576 for (i = 0; i < nitems; i++)
4577 result = lappend(result, items[i].clause);
4583 * Copy cost and size info from a Path node to the Plan node created from it.
4584 * The executor usually won't use this info, but it's needed by EXPLAIN.
4585 * Also copy the parallel-aware flag, which the executor *will* use.
4588 copy_generic_path_info(Plan *dest, Path *src)
4590 dest->startup_cost = src->startup_cost;
4591 dest->total_cost = src->total_cost;
4592 dest->plan_rows = src->rows;
4593 dest->plan_width = src->pathtarget->width;
4594 dest->parallel_aware = src->parallel_aware;
4598 * Copy cost and size info from a lower plan node to an inserted node.
4599 * (Most callers alter the info after copying it.)
4602 copy_plan_costsize(Plan *dest, Plan *src)
4604 dest->startup_cost = src->startup_cost;
4605 dest->total_cost = src->total_cost;
4606 dest->plan_rows = src->plan_rows;
4607 dest->plan_width = src->plan_width;
4608 /* Assume the inserted node is not parallel-aware. */
4609 dest->parallel_aware = false;
4613 * Some places in this file build Sort nodes that don't have a directly
4614 * corresponding Path node. The cost of the sort is, or should have been,
4615 * included in the cost of the Path node we're working from, but since it's
4616 * not split out, we have to re-figure it using cost_sort(). This is just
4617 * to label the Sort node nicely for EXPLAIN.
4619 * limit_tuples is as for cost_sort (in particular, pass -1 if no limit)
4622 label_sort_with_costsize(PlannerInfo *root, Sort *plan, double limit_tuples)
4624 Plan *lefttree = plan->plan.lefttree;
4625 Path sort_path; /* dummy for result of cost_sort */
4627 cost_sort(&sort_path, root, NIL,
4628 lefttree->total_cost,
4629 lefttree->plan_rows,
4630 lefttree->plan_width,
4634 plan->plan.startup_cost = sort_path.startup_cost;
4635 plan->plan.total_cost = sort_path.total_cost;
4636 plan->plan.plan_rows = lefttree->plan_rows;
4637 plan->plan.plan_width = lefttree->plan_width;
4638 plan->plan.parallel_aware = false;
4642 /*****************************************************************************
4644 * PLAN NODE BUILDING ROUTINES
4646 * In general, these functions are not passed the original Path and therefore
4647 * leave it to the caller to fill in the cost/width fields from the Path,
4648 * typically by calling copy_generic_path_info(). This convention is
4649 * somewhat historical, but it does support a few places above where we build
4650 * a plan node without having an exactly corresponding Path node. Under no
4651 * circumstances should one of these functions do its own cost calculations,
4652 * as that would be redundant with calculations done while building Paths.
4654 *****************************************************************************/
4657 make_seqscan(List *qptlist,
4661 SeqScan *node = makeNode(SeqScan);
4662 Plan *plan = &node->plan;
4664 plan->targetlist = qptlist;
4665 plan->qual = qpqual;
4666 plan->lefttree = NULL;
4667 plan->righttree = NULL;
4668 node->scanrelid = scanrelid;
4674 make_samplescan(List *qptlist,
4677 TableSampleClause *tsc)
4679 SampleScan *node = makeNode(SampleScan);
4680 Plan *plan = &node->scan.plan;
4682 plan->targetlist = qptlist;
4683 plan->qual = qpqual;
4684 plan->lefttree = NULL;
4685 plan->righttree = NULL;
4686 node->scan.scanrelid = scanrelid;
4687 node->tablesample = tsc;
4693 make_indexscan(List *qptlist,
4698 List *indexqualorig,
4700 List *indexorderbyorig,
4701 List *indexorderbyops,
4702 ScanDirection indexscandir)
4704 IndexScan *node = makeNode(IndexScan);
4705 Plan *plan = &node->scan.plan;
4707 plan->targetlist = qptlist;
4708 plan->qual = qpqual;
4709 plan->lefttree = NULL;
4710 plan->righttree = NULL;
4711 node->scan.scanrelid = scanrelid;
4712 node->indexid = indexid;
4713 node->indexqual = indexqual;
4714 node->indexqualorig = indexqualorig;
4715 node->indexorderby = indexorderby;
4716 node->indexorderbyorig = indexorderbyorig;
4717 node->indexorderbyops = indexorderbyops;
4718 node->indexorderdir = indexscandir;
4723 static IndexOnlyScan *
4724 make_indexonlyscan(List *qptlist,
4731 ScanDirection indexscandir)
4733 IndexOnlyScan *node = makeNode(IndexOnlyScan);
4734 Plan *plan = &node->scan.plan;
4736 plan->targetlist = qptlist;
4737 plan->qual = qpqual;
4738 plan->lefttree = NULL;
4739 plan->righttree = NULL;
4740 node->scan.scanrelid = scanrelid;
4741 node->indexid = indexid;
4742 node->indexqual = indexqual;
4743 node->indexorderby = indexorderby;
4744 node->indextlist = indextlist;
4745 node->indexorderdir = indexscandir;
4750 static BitmapIndexScan *
4751 make_bitmap_indexscan(Index scanrelid,
4754 List *indexqualorig)
4756 BitmapIndexScan *node = makeNode(BitmapIndexScan);
4757 Plan *plan = &node->scan.plan;
4759 plan->targetlist = NIL; /* not used */
4760 plan->qual = NIL; /* not used */
4761 plan->lefttree = NULL;
4762 plan->righttree = NULL;
4763 node->scan.scanrelid = scanrelid;
4764 node->indexid = indexid;
4765 node->indexqual = indexqual;
4766 node->indexqualorig = indexqualorig;
4771 static BitmapHeapScan *
4772 make_bitmap_heapscan(List *qptlist,
4775 List *bitmapqualorig,
4778 BitmapHeapScan *node = makeNode(BitmapHeapScan);
4779 Plan *plan = &node->scan.plan;
4781 plan->targetlist = qptlist;
4782 plan->qual = qpqual;
4783 plan->lefttree = lefttree;
4784 plan->righttree = NULL;
4785 node->scan.scanrelid = scanrelid;
4786 node->bitmapqualorig = bitmapqualorig;
4792 make_tidscan(List *qptlist,
4797 TidScan *node = makeNode(TidScan);
4798 Plan *plan = &node->scan.plan;
4800 plan->targetlist = qptlist;
4801 plan->qual = qpqual;
4802 plan->lefttree = NULL;
4803 plan->righttree = NULL;
4804 node->scan.scanrelid = scanrelid;
4805 node->tidquals = tidquals;
4810 static SubqueryScan *
4811 make_subqueryscan(List *qptlist,
4816 SubqueryScan *node = makeNode(SubqueryScan);
4817 Plan *plan = &node->scan.plan;
4819 plan->targetlist = qptlist;
4820 plan->qual = qpqual;
4821 plan->lefttree = NULL;
4822 plan->righttree = NULL;
4823 node->scan.scanrelid = scanrelid;
4824 node->subplan = subplan;
4829 static FunctionScan *
4830 make_functionscan(List *qptlist,
4834 bool funcordinality)
4836 FunctionScan *node = makeNode(FunctionScan);
4837 Plan *plan = &node->scan.plan;
4839 plan->targetlist = qptlist;
4840 plan->qual = qpqual;
4841 plan->lefttree = NULL;
4842 plan->righttree = NULL;
4843 node->scan.scanrelid = scanrelid;
4844 node->functions = functions;
4845 node->funcordinality = funcordinality;
4851 make_valuesscan(List *qptlist,
4856 ValuesScan *node = makeNode(ValuesScan);
4857 Plan *plan = &node->scan.plan;
4859 plan->targetlist = qptlist;
4860 plan->qual = qpqual;
4861 plan->lefttree = NULL;
4862 plan->righttree = NULL;
4863 node->scan.scanrelid = scanrelid;
4864 node->values_lists = values_lists;
4870 make_ctescan(List *qptlist,
4876 CteScan *node = makeNode(CteScan);
4877 Plan *plan = &node->scan.plan;
4879 plan->targetlist = qptlist;
4880 plan->qual = qpqual;
4881 plan->lefttree = NULL;
4882 plan->righttree = NULL;
4883 node->scan.scanrelid = scanrelid;
4884 node->ctePlanId = ctePlanId;
4885 node->cteParam = cteParam;
4890 static WorkTableScan *
4891 make_worktablescan(List *qptlist,
4896 WorkTableScan *node = makeNode(WorkTableScan);
4897 Plan *plan = &node->scan.plan;
4899 plan->targetlist = qptlist;
4900 plan->qual = qpqual;
4901 plan->lefttree = NULL;
4902 plan->righttree = NULL;
4903 node->scan.scanrelid = scanrelid;
4904 node->wtParam = wtParam;
4910 make_foreignscan(List *qptlist,
4915 List *fdw_scan_tlist,
4916 List *fdw_recheck_quals,
4919 ForeignScan *node = makeNode(ForeignScan);
4920 Plan *plan = &node->scan.plan;
4922 /* cost will be filled in by create_foreignscan_plan */
4923 plan->targetlist = qptlist;
4924 plan->qual = qpqual;
4925 plan->lefttree = outer_plan;
4926 plan->righttree = NULL;
4927 node->scan.scanrelid = scanrelid;
4928 node->operation = CMD_SELECT;
4929 /* fs_server will be filled in by create_foreignscan_plan */
4930 node->fs_server = InvalidOid;
4931 node->fdw_exprs = fdw_exprs;
4932 node->fdw_private = fdw_private;
4933 node->fdw_scan_tlist = fdw_scan_tlist;
4934 node->fdw_recheck_quals = fdw_recheck_quals;
4935 /* fs_relids will be filled in by create_foreignscan_plan */
4936 node->fs_relids = NULL;
4937 /* fsSystemCol will be filled in by create_foreignscan_plan */
4938 node->fsSystemCol = false;
4944 make_append(List *appendplans, List *tlist)
4946 Append *node = makeNode(Append);
4947 Plan *plan = &node->plan;
4949 plan->targetlist = tlist;
4951 plan->lefttree = NULL;
4952 plan->righttree = NULL;
4953 node->appendplans = appendplans;
4958 static RecursiveUnion *
4959 make_recursive_union(List *tlist,
4966 RecursiveUnion *node = makeNode(RecursiveUnion);
4967 Plan *plan = &node->plan;
4968 int numCols = list_length(distinctList);
4970 plan->targetlist = tlist;
4972 plan->lefttree = lefttree;
4973 plan->righttree = righttree;
4974 node->wtParam = wtParam;
4977 * convert SortGroupClause list into arrays of attr indexes and equality
4978 * operators, as wanted by executor
4980 node->numCols = numCols;
4984 AttrNumber *dupColIdx;
4988 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
4989 dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
4991 foreach(slitem, distinctList)
4993 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
4994 TargetEntry *tle = get_sortgroupclause_tle(sortcl,
4997 dupColIdx[keyno] = tle->resno;
4998 dupOperators[keyno] = sortcl->eqop;
4999 Assert(OidIsValid(dupOperators[keyno]));
5002 node->dupColIdx = dupColIdx;
5003 node->dupOperators = dupOperators;
5005 node->numGroups = numGroups;
5011 make_bitmap_and(List *bitmapplans)
5013 BitmapAnd *node = makeNode(BitmapAnd);
5014 Plan *plan = &node->plan;
5016 plan->targetlist = NIL;
5018 plan->lefttree = NULL;
5019 plan->righttree = NULL;
5020 node->bitmapplans = bitmapplans;
5026 make_bitmap_or(List *bitmapplans)
5028 BitmapOr *node = makeNode(BitmapOr);
5029 Plan *plan = &node->plan;
5031 plan->targetlist = NIL;
5033 plan->lefttree = NULL;
5034 plan->righttree = NULL;
5035 node->bitmapplans = bitmapplans;
5041 make_nestloop(List *tlist,
5049 NestLoop *node = makeNode(NestLoop);
5050 Plan *plan = &node->join.plan;
5052 plan->targetlist = tlist;
5053 plan->qual = otherclauses;
5054 plan->lefttree = lefttree;
5055 plan->righttree = righttree;
5056 node->join.jointype = jointype;
5057 node->join.joinqual = joinclauses;
5058 node->nestParams = nestParams;
5064 make_hashjoin(List *tlist,
5072 HashJoin *node = makeNode(HashJoin);
5073 Plan *plan = &node->join.plan;
5075 plan->targetlist = tlist;
5076 plan->qual = otherclauses;
5077 plan->lefttree = lefttree;
5078 plan->righttree = righttree;
5079 node->hashclauses = hashclauses;
5080 node->join.jointype = jointype;
5081 node->join.joinqual = joinclauses;
5087 make_hash(Plan *lefttree,
5089 AttrNumber skewColumn,
5092 int32 skewColTypmod)
5094 Hash *node = makeNode(Hash);
5095 Plan *plan = &node->plan;
5097 plan->targetlist = lefttree->targetlist;
5099 plan->lefttree = lefttree;
5100 plan->righttree = NULL;
5102 node->skewTable = skewTable;
5103 node->skewColumn = skewColumn;
5104 node->skewInherit = skewInherit;
5105 node->skewColType = skewColType;
5106 node->skewColTypmod = skewColTypmod;
5112 make_mergejoin(List *tlist,
5117 Oid *mergecollations,
5118 int *mergestrategies,
5119 bool *mergenullsfirst,
5124 MergeJoin *node = makeNode(MergeJoin);
5125 Plan *plan = &node->join.plan;
5127 plan->targetlist = tlist;
5128 plan->qual = otherclauses;
5129 plan->lefttree = lefttree;
5130 plan->righttree = righttree;
5131 node->mergeclauses = mergeclauses;
5132 node->mergeFamilies = mergefamilies;
5133 node->mergeCollations = mergecollations;
5134 node->mergeStrategies = mergestrategies;
5135 node->mergeNullsFirst = mergenullsfirst;
5136 node->join.jointype = jointype;
5137 node->join.joinqual = joinclauses;
5143 * make_sort --- basic routine to build a Sort plan node
5145 * Caller must have built the sortColIdx, sortOperators, collations, and
5146 * nullsFirst arrays already.
5149 make_sort(Plan *lefttree, int numCols,
5150 AttrNumber *sortColIdx, Oid *sortOperators,
5151 Oid *collations, bool *nullsFirst)
5153 Sort *node = makeNode(Sort);
5154 Plan *plan = &node->plan;
5156 plan->targetlist = lefttree->targetlist;
5158 plan->lefttree = lefttree;
5159 plan->righttree = NULL;
5160 node->numCols = numCols;
5161 node->sortColIdx = sortColIdx;
5162 node->sortOperators = sortOperators;
5163 node->collations = collations;
5164 node->nullsFirst = nullsFirst;
5170 * prepare_sort_from_pathkeys
5171 * Prepare to sort according to given pathkeys
5173 * This is used to set up for both Sort and MergeAppend nodes. It calculates
5174 * the executor's representation of the sort key information, and adjusts the
5175 * plan targetlist if needed to add resjunk sort columns.
5178 * 'lefttree' is the plan node which yields input tuples
5179 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
5180 * 'relids' identifies the child relation being sorted, if any
5181 * 'reqColIdx' is NULL or an array of required sort key column numbers
5182 * 'adjust_tlist_in_place' is TRUE if lefttree must be modified in-place
5184 * We must convert the pathkey information into arrays of sort key column
5185 * numbers, sort operator OIDs, collation OIDs, and nulls-first flags,
5186 * which is the representation the executor wants. These are returned into
5187 * the output parameters *p_numsortkeys etc.
5189 * When looking for matches to an EquivalenceClass's members, we will only
5190 * consider child EC members if they match 'relids'. This protects against
5191 * possible incorrect matches to child expressions that contain no Vars.
5193 * If reqColIdx isn't NULL then it contains sort key column numbers that
5194 * we should match. This is used when making child plans for a MergeAppend;
5195 * it's an error if we can't match the columns.
5197 * If the pathkeys include expressions that aren't simple Vars, we will
5198 * usually need to add resjunk items to the input plan's targetlist to
5199 * compute these expressions, since the Sort/MergeAppend node itself won't
5200 * do any such calculations. If the input plan type isn't one that can do
5201 * projections, this means adding a Result node just to do the projection.
5202 * However, the caller can pass adjust_tlist_in_place = TRUE to force the
5203 * lefttree tlist to be modified in-place regardless of whether the node type
5204 * can project --- we use this for fixing the tlist of MergeAppend itself.
5206 * Returns the node which is to be the input to the Sort (either lefttree,
5207 * or a Result stacked atop lefttree).
5210 prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys,
5212 const AttrNumber *reqColIdx,
5213 bool adjust_tlist_in_place,
5215 AttrNumber **p_sortColIdx,
5216 Oid **p_sortOperators,
5218 bool **p_nullsFirst)
5220 List *tlist = lefttree->targetlist;
5223 AttrNumber *sortColIdx;
5229 * We will need at most list_length(pathkeys) sort columns; possibly less
5231 numsortkeys = list_length(pathkeys);
5232 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
5233 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
5234 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
5235 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
5239 foreach(i, pathkeys)
5241 PathKey *pathkey = (PathKey *) lfirst(i);
5242 EquivalenceClass *ec = pathkey->pk_eclass;
5243 EquivalenceMember *em;
5244 TargetEntry *tle = NULL;
5245 Oid pk_datatype = InvalidOid;
5249 if (ec->ec_has_volatile)
5252 * If the pathkey's EquivalenceClass is volatile, then it must
5253 * have come from an ORDER BY clause, and we have to match it to
5254 * that same targetlist entry.
5256 if (ec->ec_sortref == 0) /* can't happen */
5257 elog(ERROR, "volatile EquivalenceClass has no sortref");
5258 tle = get_sortgroupref_tle(ec->ec_sortref, tlist);
5260 Assert(list_length(ec->ec_members) == 1);
5261 pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
5263 else if (reqColIdx != NULL)
5266 * If we are given a sort column number to match, only consider
5267 * the single TLE at that position. It's possible that there is
5268 * no such TLE, in which case fall through and generate a resjunk
5269 * targetentry (we assume this must have happened in the parent
5270 * plan as well). If there is a TLE but it doesn't match the
5271 * pathkey's EC, we do the same, which is probably the wrong thing
5272 * but we'll leave it to caller to complain about the mismatch.
5274 tle = get_tle_by_resno(tlist, reqColIdx[numsortkeys]);
5277 em = find_ec_member_for_tle(ec, tle, relids);
5280 /* found expr at right place in tlist */
5281 pk_datatype = em->em_datatype;
5290 * Otherwise, we can sort by any non-constant expression listed in
5291 * the pathkey's EquivalenceClass. For now, we take the first
5292 * tlist item found in the EC. If there's no match, we'll generate
5293 * a resjunk entry using the first EC member that is an expression
5294 * in the input's vars. (The non-const restriction only matters
5295 * if the EC is below_outer_join; but if it isn't, it won't
5296 * contain consts anyway, else we'd have discarded the pathkey as
5299 * XXX if we have a choice, is there any way of figuring out which
5300 * might be cheapest to execute? (For example, int4lt is likely
5301 * much cheaper to execute than numericlt, but both might appear
5302 * in the same equivalence class...) Not clear that we ever will
5303 * have an interesting choice in practice, so it may not matter.
5307 tle = (TargetEntry *) lfirst(j);
5308 em = find_ec_member_for_tle(ec, tle, relids);
5311 /* found expr already in tlist */
5312 pk_datatype = em->em_datatype;
5322 * No matching tlist item; look for a computable expression. Note
5323 * that we treat Aggrefs as if they were variables; this is
5324 * necessary when attempting to sort the output from an Agg node
5325 * for use in a WindowFunc (since grouping_planner will have
5326 * treated the Aggrefs as variables, too). Likewise, if we find a
5327 * WindowFunc in a sort expression, treat it as a variable.
5329 Expr *sortexpr = NULL;
5331 foreach(j, ec->ec_members)
5333 EquivalenceMember *em = (EquivalenceMember *) lfirst(j);
5338 * We shouldn't be trying to sort by an equivalence class that
5339 * contains a constant, so no need to consider such cases any
5342 if (em->em_is_const)
5346 * Ignore child members unless they match the rel being
5349 if (em->em_is_child &&
5350 !bms_equal(em->em_relids, relids))
5353 sortexpr = em->em_expr;
5354 exprvars = pull_var_clause((Node *) sortexpr,
5355 PVC_INCLUDE_AGGREGATES |
5356 PVC_INCLUDE_WINDOWFUNCS |
5357 PVC_INCLUDE_PLACEHOLDERS);
5358 foreach(k, exprvars)
5360 if (!tlist_member_ignore_relabel(lfirst(k), tlist))
5363 list_free(exprvars);
5366 pk_datatype = em->em_datatype;
5367 break; /* found usable expression */
5371 elog(ERROR, "could not find pathkey item to sort");
5374 * Do we need to insert a Result node?
5376 if (!adjust_tlist_in_place &&
5377 !is_projection_capable_plan(lefttree))
5379 /* copy needed so we don't modify input's tlist below */
5380 tlist = copyObject(tlist);
5381 lefttree = inject_projection_plan(lefttree, tlist);
5384 /* Don't bother testing is_projection_capable_plan again */
5385 adjust_tlist_in_place = true;
5388 * Add resjunk entry to input's tlist
5390 tle = makeTargetEntry(sortexpr,
5391 list_length(tlist) + 1,
5394 tlist = lappend(tlist, tle);
5395 lefttree->targetlist = tlist; /* just in case NIL before */
5399 * Look up the correct sort operator from the PathKey's slightly
5400 * abstracted representation.
5402 sortop = get_opfamily_member(pathkey->pk_opfamily,
5405 pathkey->pk_strategy);
5406 if (!OidIsValid(sortop)) /* should not happen */
5407 elog(ERROR, "could not find member %d(%u,%u) of opfamily %u",
5408 pathkey->pk_strategy, pk_datatype, pk_datatype,
5409 pathkey->pk_opfamily);
5411 /* Add the column to the sort arrays */
5412 sortColIdx[numsortkeys] = tle->resno;
5413 sortOperators[numsortkeys] = sortop;
5414 collations[numsortkeys] = ec->ec_collation;
5415 nullsFirst[numsortkeys] = pathkey->pk_nulls_first;
5419 /* Return results */
5420 *p_numsortkeys = numsortkeys;
5421 *p_sortColIdx = sortColIdx;
5422 *p_sortOperators = sortOperators;
5423 *p_collations = collations;
5424 *p_nullsFirst = nullsFirst;
5430 * find_ec_member_for_tle
5431 * Locate an EquivalenceClass member matching the given TLE, if any
5433 * Child EC members are ignored unless they match 'relids'.
5435 static EquivalenceMember *
5436 find_ec_member_for_tle(EquivalenceClass *ec,
5443 /* We ignore binary-compatible relabeling on both ends */
5445 while (tlexpr && IsA(tlexpr, RelabelType))
5446 tlexpr = ((RelabelType *) tlexpr)->arg;
5448 foreach(lc, ec->ec_members)
5450 EquivalenceMember *em = (EquivalenceMember *) lfirst(lc);
5454 * We shouldn't be trying to sort by an equivalence class that
5455 * contains a constant, so no need to consider such cases any further.
5457 if (em->em_is_const)
5461 * Ignore child members unless they match the rel being sorted.
5463 if (em->em_is_child &&
5464 !bms_equal(em->em_relids, relids))
5467 /* Match if same expression (after stripping relabel) */
5468 emexpr = em->em_expr;
5469 while (emexpr && IsA(emexpr, RelabelType))
5470 emexpr = ((RelabelType *) emexpr)->arg;
5472 if (equal(emexpr, tlexpr))
5480 * make_sort_from_pathkeys
5481 * Create sort plan to sort according to given pathkeys
5483 * 'lefttree' is the node which yields input tuples
5484 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
5487 make_sort_from_pathkeys(Plan *lefttree, List *pathkeys)
5490 AttrNumber *sortColIdx;
5495 /* Compute sort column info, and adjust lefttree as needed */
5496 lefttree = prepare_sort_from_pathkeys(lefttree, pathkeys,
5506 /* Now build the Sort node */
5507 return make_sort(lefttree, numsortkeys,
5508 sortColIdx, sortOperators,
5509 collations, nullsFirst);
5513 * make_sort_from_sortclauses
5514 * Create sort plan to sort according to given sortclauses
5516 * 'sortcls' is a list of SortGroupClauses
5517 * 'lefttree' is the node which yields input tuples
5520 make_sort_from_sortclauses(List *sortcls, Plan *lefttree)
5522 List *sub_tlist = lefttree->targetlist;
5525 AttrNumber *sortColIdx;
5530 /* Convert list-ish representation to arrays wanted by executor */
5531 numsortkeys = list_length(sortcls);
5532 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
5533 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
5534 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
5535 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
5540 SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
5541 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
5543 sortColIdx[numsortkeys] = tle->resno;
5544 sortOperators[numsortkeys] = sortcl->sortop;
5545 collations[numsortkeys] = exprCollation((Node *) tle->expr);
5546 nullsFirst[numsortkeys] = sortcl->nulls_first;
5550 return make_sort(lefttree, numsortkeys,
5551 sortColIdx, sortOperators,
5552 collations, nullsFirst);
5556 * make_sort_from_groupcols
5557 * Create sort plan to sort based on grouping columns
5559 * 'groupcls' is the list of SortGroupClauses
5560 * 'grpColIdx' gives the column numbers to use
5562 * This might look like it could be merged with make_sort_from_sortclauses,
5563 * but presently we *must* use the grpColIdx[] array to locate sort columns,
5564 * because the child plan's tlist is not marked with ressortgroupref info
5565 * appropriate to the grouping node. So, only the sort ordering info
5566 * is used from the SortGroupClause entries.
5569 make_sort_from_groupcols(List *groupcls,
5570 AttrNumber *grpColIdx,
5573 List *sub_tlist = lefttree->targetlist;
5576 AttrNumber *sortColIdx;
5581 /* Convert list-ish representation to arrays wanted by executor */
5582 numsortkeys = list_length(groupcls);
5583 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
5584 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
5585 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
5586 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
5589 foreach(l, groupcls)
5591 SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
5592 TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[numsortkeys]);
5595 elog(ERROR, "could not retrieve tle for sort-from-groupcols");
5597 sortColIdx[numsortkeys] = tle->resno;
5598 sortOperators[numsortkeys] = grpcl->sortop;
5599 collations[numsortkeys] = exprCollation((Node *) tle->expr);
5600 nullsFirst[numsortkeys] = grpcl->nulls_first;
5604 return make_sort(lefttree, numsortkeys,
5605 sortColIdx, sortOperators,
5606 collations, nullsFirst);
5610 make_material(Plan *lefttree)
5612 Material *node = makeNode(Material);
5613 Plan *plan = &node->plan;
5615 plan->targetlist = lefttree->targetlist;
5617 plan->lefttree = lefttree;
5618 plan->righttree = NULL;
5624 * materialize_finished_plan: stick a Material node atop a completed plan
5626 * There are a couple of places where we want to attach a Material node
5627 * after completion of create_plan(), without any MaterialPath path.
5628 * Those places should probably be refactored someday to do this on the
5629 * Path representation, but it's not worth the trouble yet.
5632 materialize_finished_plan(Plan *subplan)
5635 Path matpath; /* dummy for result of cost_material */
5637 matplan = (Plan *) make_material(subplan);
5640 cost_material(&matpath,
5641 subplan->startup_cost,
5642 subplan->total_cost,
5644 subplan->plan_width);
5645 matplan->startup_cost = matpath.startup_cost;
5646 matplan->total_cost = matpath.total_cost;
5647 matplan->plan_rows = subplan->plan_rows;
5648 matplan->plan_width = subplan->plan_width;
5649 matplan->parallel_aware = false;
5655 make_agg(List *tlist, List *qual,
5656 AggStrategy aggstrategy, AggSplit aggsplit,
5657 int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators,
5658 List *groupingSets, List *chain,
5659 double dNumGroups, Plan *lefttree)
5661 Agg *node = makeNode(Agg);
5662 Plan *plan = &node->plan;
5665 /* Reduce to long, but 'ware overflow! */
5666 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
5668 node->aggstrategy = aggstrategy;
5669 node->aggsplit = aggsplit;
5670 node->numCols = numGroupCols;
5671 node->grpColIdx = grpColIdx;
5672 node->grpOperators = grpOperators;
5673 node->numGroups = numGroups;
5674 node->aggParams = NULL; /* SS_finalize_plan() will fill this */
5675 node->groupingSets = groupingSets;
5676 node->chain = chain;
5679 plan->targetlist = tlist;
5680 plan->lefttree = lefttree;
5681 plan->righttree = NULL;
5687 make_windowagg(List *tlist, Index winref,
5688 int partNumCols, AttrNumber *partColIdx, Oid *partOperators,
5689 int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators,
5690 int frameOptions, Node *startOffset, Node *endOffset,
5693 WindowAgg *node = makeNode(WindowAgg);
5694 Plan *plan = &node->plan;
5696 node->winref = winref;
5697 node->partNumCols = partNumCols;
5698 node->partColIdx = partColIdx;
5699 node->partOperators = partOperators;
5700 node->ordNumCols = ordNumCols;
5701 node->ordColIdx = ordColIdx;
5702 node->ordOperators = ordOperators;
5703 node->frameOptions = frameOptions;
5704 node->startOffset = startOffset;
5705 node->endOffset = endOffset;
5707 plan->targetlist = tlist;
5708 plan->lefttree = lefttree;
5709 plan->righttree = NULL;
5710 /* WindowAgg nodes never have a qual clause */
5717 make_group(List *tlist,
5720 AttrNumber *grpColIdx,
5724 Group *node = makeNode(Group);
5725 Plan *plan = &node->plan;
5727 node->numCols = numGroupCols;
5728 node->grpColIdx = grpColIdx;
5729 node->grpOperators = grpOperators;
5732 plan->targetlist = tlist;
5733 plan->lefttree = lefttree;
5734 plan->righttree = NULL;
5740 * distinctList is a list of SortGroupClauses, identifying the targetlist items
5741 * that should be considered by the Unique filter. The input path must
5742 * already be sorted accordingly.
5745 make_unique_from_sortclauses(Plan *lefttree, List *distinctList)
5747 Unique *node = makeNode(Unique);
5748 Plan *plan = &node->plan;
5749 int numCols = list_length(distinctList);
5751 AttrNumber *uniqColIdx;
5755 plan->targetlist = lefttree->targetlist;
5757 plan->lefttree = lefttree;
5758 plan->righttree = NULL;
5761 * convert SortGroupClause list into arrays of attr indexes and equality
5762 * operators, as wanted by executor
5764 Assert(numCols > 0);
5765 uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
5766 uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
5768 foreach(slitem, distinctList)
5770 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
5771 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
5773 uniqColIdx[keyno] = tle->resno;
5774 uniqOperators[keyno] = sortcl->eqop;
5775 Assert(OidIsValid(uniqOperators[keyno]));
5779 node->numCols = numCols;
5780 node->uniqColIdx = uniqColIdx;
5781 node->uniqOperators = uniqOperators;
5787 * as above, but use pathkeys to identify the sort columns and semantics
5790 make_unique_from_pathkeys(Plan *lefttree, List *pathkeys, int numCols)
5792 Unique *node = makeNode(Unique);
5793 Plan *plan = &node->plan;
5795 AttrNumber *uniqColIdx;
5799 plan->targetlist = lefttree->targetlist;
5801 plan->lefttree = lefttree;
5802 plan->righttree = NULL;
5805 * Convert pathkeys list into arrays of attr indexes and equality
5806 * operators, as wanted by executor. This has a lot in common with
5807 * prepare_sort_from_pathkeys ... maybe unify sometime?
5809 Assert(numCols >= 0 && numCols <= list_length(pathkeys));
5810 uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
5811 uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
5813 foreach(lc, pathkeys)
5815 PathKey *pathkey = (PathKey *) lfirst(lc);
5816 EquivalenceClass *ec = pathkey->pk_eclass;
5817 EquivalenceMember *em;
5818 TargetEntry *tle = NULL;
5819 Oid pk_datatype = InvalidOid;
5823 /* Ignore pathkeys beyond the specified number of columns */
5824 if (keyno >= numCols)
5827 if (ec->ec_has_volatile)
5830 * If the pathkey's EquivalenceClass is volatile, then it must
5831 * have come from an ORDER BY clause, and we have to match it to
5832 * that same targetlist entry.
5834 if (ec->ec_sortref == 0) /* can't happen */
5835 elog(ERROR, "volatile EquivalenceClass has no sortref");
5836 tle = get_sortgroupref_tle(ec->ec_sortref, plan->targetlist);
5838 Assert(list_length(ec->ec_members) == 1);
5839 pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
5844 * Otherwise, we can use any non-constant expression listed in the
5845 * pathkey's EquivalenceClass. For now, we take the first tlist
5846 * item found in the EC.
5848 foreach(j, plan->targetlist)
5850 tle = (TargetEntry *) lfirst(j);
5851 em = find_ec_member_for_tle(ec, tle, NULL);
5854 /* found expr already in tlist */
5855 pk_datatype = em->em_datatype;
5863 elog(ERROR, "could not find pathkey item to sort");
5866 * Look up the correct equality operator from the PathKey's slightly
5867 * abstracted representation.
5869 eqop = get_opfamily_member(pathkey->pk_opfamily,
5872 BTEqualStrategyNumber);
5873 if (!OidIsValid(eqop)) /* should not happen */
5874 elog(ERROR, "could not find member %d(%u,%u) of opfamily %u",
5875 BTEqualStrategyNumber, pk_datatype, pk_datatype,
5876 pathkey->pk_opfamily);
5878 uniqColIdx[keyno] = tle->resno;
5879 uniqOperators[keyno] = eqop;
5884 node->numCols = numCols;
5885 node->uniqColIdx = uniqColIdx;
5886 node->uniqOperators = uniqOperators;
5892 make_gather(List *qptlist,
5898 Gather *node = makeNode(Gather);
5899 Plan *plan = &node->plan;
5901 plan->targetlist = qptlist;
5902 plan->qual = qpqual;
5903 plan->lefttree = subplan;
5904 plan->righttree = NULL;
5905 node->num_workers = nworkers;
5906 node->single_copy = single_copy;
5907 node->invisible = false;
5913 * distinctList is a list of SortGroupClauses, identifying the targetlist
5914 * items that should be considered by the SetOp filter. The input path must
5915 * already be sorted accordingly.
5918 make_setop(SetOpCmd cmd, SetOpStrategy strategy, Plan *lefttree,
5919 List *distinctList, AttrNumber flagColIdx, int firstFlag,
5922 SetOp *node = makeNode(SetOp);
5923 Plan *plan = &node->plan;
5924 int numCols = list_length(distinctList);
5926 AttrNumber *dupColIdx;
5930 plan->targetlist = lefttree->targetlist;
5932 plan->lefttree = lefttree;
5933 plan->righttree = NULL;
5936 * convert SortGroupClause list into arrays of attr indexes and equality
5937 * operators, as wanted by executor
5939 Assert(numCols > 0);
5940 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
5941 dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
5943 foreach(slitem, distinctList)
5945 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
5946 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
5948 dupColIdx[keyno] = tle->resno;
5949 dupOperators[keyno] = sortcl->eqop;
5950 Assert(OidIsValid(dupOperators[keyno]));
5955 node->strategy = strategy;
5956 node->numCols = numCols;
5957 node->dupColIdx = dupColIdx;
5958 node->dupOperators = dupOperators;
5959 node->flagColIdx = flagColIdx;
5960 node->firstFlag = firstFlag;
5961 node->numGroups = numGroups;
5968 * Build a LockRows plan node
5971 make_lockrows(Plan *lefttree, List *rowMarks, int epqParam)
5973 LockRows *node = makeNode(LockRows);
5974 Plan *plan = &node->plan;
5976 plan->targetlist = lefttree->targetlist;
5978 plan->lefttree = lefttree;
5979 plan->righttree = NULL;
5981 node->rowMarks = rowMarks;
5982 node->epqParam = epqParam;
5989 * Build a Limit plan node
5992 make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount)
5994 Limit *node = makeNode(Limit);
5995 Plan *plan = &node->plan;
5997 plan->targetlist = lefttree->targetlist;
5999 plan->lefttree = lefttree;
6000 plan->righttree = NULL;
6002 node->limitOffset = limitOffset;
6003 node->limitCount = limitCount;
6010 * Build a Result plan node
6013 make_result(List *tlist,
6014 Node *resconstantqual,
6017 Result *node = makeNode(Result);
6018 Plan *plan = &node->plan;
6020 plan->targetlist = tlist;
6022 plan->lefttree = subplan;
6023 plan->righttree = NULL;
6024 node->resconstantqual = resconstantqual;
6031 * Build a ModifyTable plan node
6033 static ModifyTable *
6034 make_modifytable(PlannerInfo *root,
6035 CmdType operation, bool canSetTag,
6036 Index nominalRelation,
6037 List *resultRelations, List *subplans,
6038 List *withCheckOptionLists, List *returningLists,
6039 List *rowMarks, OnConflictExpr *onconflict, int epqParam)
6041 ModifyTable *node = makeNode(ModifyTable);
6042 List *fdw_private_list;
6043 Bitmapset *direct_modify_plans;
6047 Assert(list_length(resultRelations) == list_length(subplans));
6048 Assert(withCheckOptionLists == NIL ||
6049 list_length(resultRelations) == list_length(withCheckOptionLists));
6050 Assert(returningLists == NIL ||
6051 list_length(resultRelations) == list_length(returningLists));
6053 node->plan.lefttree = NULL;
6054 node->plan.righttree = NULL;
6055 node->plan.qual = NIL;
6056 /* setrefs.c will fill in the targetlist, if needed */
6057 node->plan.targetlist = NIL;
6059 node->operation = operation;
6060 node->canSetTag = canSetTag;
6061 node->nominalRelation = nominalRelation;
6062 node->resultRelations = resultRelations;
6063 node->resultRelIndex = -1; /* will be set correctly in setrefs.c */
6064 node->plans = subplans;
6067 node->onConflictAction = ONCONFLICT_NONE;
6068 node->onConflictSet = NIL;
6069 node->onConflictWhere = NULL;
6070 node->arbiterIndexes = NIL;
6071 node->exclRelRTI = 0;
6072 node->exclRelTlist = NIL;
6076 node->onConflictAction = onconflict->action;
6077 node->onConflictSet = onconflict->onConflictSet;
6078 node->onConflictWhere = onconflict->onConflictWhere;
6081 * If a set of unique index inference elements was provided (an
6082 * INSERT...ON CONFLICT "inference specification"), then infer
6083 * appropriate unique indexes (or throw an error if none are
6086 node->arbiterIndexes = infer_arbiter_indexes(root);
6088 node->exclRelRTI = onconflict->exclRelIndex;
6089 node->exclRelTlist = onconflict->exclRelTlist;
6091 node->withCheckOptionLists = withCheckOptionLists;
6092 node->returningLists = returningLists;
6093 node->rowMarks = rowMarks;
6094 node->epqParam = epqParam;
6097 * For each result relation that is a foreign table, allow the FDW to
6098 * construct private plan data, and accumulate it all into a list.
6100 fdw_private_list = NIL;
6101 direct_modify_plans = NULL;
6103 foreach(lc, resultRelations)
6105 Index rti = lfirst_int(lc);
6106 FdwRoutine *fdwroutine;
6111 * If possible, we want to get the FdwRoutine from our RelOptInfo for
6112 * the table. But sometimes we don't have a RelOptInfo and must get
6113 * it the hard way. (In INSERT, the target relation is not scanned,
6114 * so it's not a baserel; and there are also corner cases for
6115 * updatable views where the target rel isn't a baserel.)
6117 if (rti < root->simple_rel_array_size &&
6118 root->simple_rel_array[rti] != NULL)
6120 RelOptInfo *resultRel = root->simple_rel_array[rti];
6122 fdwroutine = resultRel->fdwroutine;
6126 RangeTblEntry *rte = planner_rt_fetch(rti, root);
6128 Assert(rte->rtekind == RTE_RELATION);
6129 if (rte->relkind == RELKIND_FOREIGN_TABLE)
6130 fdwroutine = GetFdwRoutineByRelId(rte->relid);
6136 * If the target foreign table has any row-level triggers, we can't
6137 * modify the foreign table directly.
6139 direct_modify = false;
6140 if (fdwroutine != NULL &&
6141 fdwroutine->PlanDirectModify != NULL &&
6142 fdwroutine->BeginDirectModify != NULL &&
6143 fdwroutine->IterateDirectModify != NULL &&
6144 fdwroutine->EndDirectModify != NULL &&
6145 !has_row_triggers(root, rti, operation))
6146 direct_modify = fdwroutine->PlanDirectModify(root, node, rti, i);
6148 direct_modify_plans = bms_add_member(direct_modify_plans, i);
6150 if (!direct_modify &&
6151 fdwroutine != NULL &&
6152 fdwroutine->PlanForeignModify != NULL)
6153 fdw_private = fdwroutine->PlanForeignModify(root, node, rti, i);
6156 fdw_private_list = lappend(fdw_private_list, fdw_private);
6159 node->fdwPrivLists = fdw_private_list;
6160 node->fdwDirectModifyPlans = direct_modify_plans;
6166 * is_projection_capable_path
6167 * Check whether a given Path node is able to do projection.
6170 is_projection_capable_path(Path *path)
6172 /* Most plan types can project, so just list the ones that can't */
6173 switch (path->pathtype)
6184 case T_RecursiveUnion:
6189 * Append can't project, but if it's being used to represent a
6190 * dummy path, claim that it can project. This prevents us from
6191 * converting a rel from dummy to non-dummy status by applying a
6192 * projection to its dummy path.
6194 return IS_DUMMY_PATH(path);
6202 * is_projection_capable_plan
6203 * Check whether a given Plan node is able to do projection.
6206 is_projection_capable_plan(Plan *plan)
6208 /* Most plan types can project, so just list the ones that can't */
6209 switch (nodeTag(plan))
6221 case T_RecursiveUnion: