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-2016, 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/makefuncs.h"
28 #include "nodes/nodeFuncs.h"
29 #include "optimizer/clauses.h"
30 #include "optimizer/cost.h"
31 #include "optimizer/paths.h"
32 #include "optimizer/placeholder.h"
33 #include "optimizer/plancat.h"
34 #include "optimizer/planmain.h"
35 #include "optimizer/planner.h"
36 #include "optimizer/predtest.h"
37 #include "optimizer/prep.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"
47 static Plan *create_plan_recurse(PlannerInfo *root, Path *best_path);
48 static Plan *create_scan_plan(PlannerInfo *root, Path *best_path);
49 static List *build_path_tlist(PlannerInfo *root, Path *path);
50 static bool use_physical_tlist(PlannerInfo *root, RelOptInfo *rel);
51 static void disuse_physical_tlist(PlannerInfo *root, Plan *plan, Path *path);
52 static Plan *create_gating_plan(PlannerInfo *root, Plan *plan, List *quals);
53 static Plan *create_join_plan(PlannerInfo *root, JoinPath *best_path);
54 static Plan *create_append_plan(PlannerInfo *root, AppendPath *best_path);
55 static Plan *create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path);
56 static Result *create_result_plan(PlannerInfo *root, ResultPath *best_path);
57 static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path);
58 static Plan *create_unique_plan(PlannerInfo *root, UniquePath *best_path);
59 static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path,
60 List *tlist, List *scan_clauses);
61 static SampleScan *create_samplescan_plan(PlannerInfo *root, Path *best_path,
62 List *tlist, List *scan_clauses);
63 static Gather *create_gather_plan(PlannerInfo *root,
64 GatherPath *best_path);
65 static Scan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path,
66 List *tlist, List *scan_clauses, bool indexonly);
67 static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
68 BitmapHeapPath *best_path,
69 List *tlist, List *scan_clauses);
70 static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
71 List **qual, List **indexqual, List **indexECs);
72 static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
73 List *tlist, List *scan_clauses);
74 static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
75 List *tlist, List *scan_clauses);
76 static FunctionScan *create_functionscan_plan(PlannerInfo *root, Path *best_path,
77 List *tlist, List *scan_clauses);
78 static ValuesScan *create_valuesscan_plan(PlannerInfo *root, Path *best_path,
79 List *tlist, List *scan_clauses);
80 static CteScan *create_ctescan_plan(PlannerInfo *root, Path *best_path,
81 List *tlist, List *scan_clauses);
82 static WorkTableScan *create_worktablescan_plan(PlannerInfo *root, Path *best_path,
83 List *tlist, List *scan_clauses);
84 static ForeignScan *create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
85 List *tlist, List *scan_clauses);
86 static CustomScan *create_customscan_plan(PlannerInfo *root,
87 CustomPath *best_path,
88 List *tlist, List *scan_clauses);
89 static NestLoop *create_nestloop_plan(PlannerInfo *root, NestPath *best_path,
90 Plan *outer_plan, Plan *inner_plan);
91 static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path,
92 Plan *outer_plan, Plan *inner_plan);
93 static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path,
94 Plan *outer_plan, Plan *inner_plan);
95 static Node *replace_nestloop_params(PlannerInfo *root, Node *expr);
96 static Node *replace_nestloop_params_mutator(Node *node, PlannerInfo *root);
97 static void process_subquery_nestloop_params(PlannerInfo *root,
98 List *subplan_params);
99 static List *fix_indexqual_references(PlannerInfo *root, IndexPath *index_path);
100 static List *fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path);
101 static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol);
102 static List *get_switched_clauses(List *clauses, Relids outerrelids);
103 static List *order_qual_clauses(PlannerInfo *root, List *clauses);
104 static void copy_generic_path_info(Plan *dest, Path *src);
105 static void copy_plan_costsize(Plan *dest, Plan *src);
106 static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
107 static SampleScan *make_samplescan(List *qptlist, List *qpqual, Index scanrelid,
108 TableSampleClause *tsc);
109 static Gather *make_gather(List *qptlist, List *qpqual,
110 int nworkers, bool single_copy, Plan *subplan);
111 static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
112 Oid indexid, List *indexqual, List *indexqualorig,
113 List *indexorderby, List *indexorderbyorig,
114 List *indexorderbyops,
115 ScanDirection indexscandir);
116 static IndexOnlyScan *make_indexonlyscan(List *qptlist, List *qpqual,
117 Index scanrelid, Oid indexid,
118 List *indexqual, List *indexorderby,
120 ScanDirection indexscandir);
121 static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid,
123 List *indexqualorig);
124 static BitmapHeapScan *make_bitmap_heapscan(List *qptlist,
127 List *bitmapqualorig,
129 static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
131 static FunctionScan *make_functionscan(List *qptlist, List *qpqual,
132 Index scanrelid, List *functions, bool funcordinality);
133 static ValuesScan *make_valuesscan(List *qptlist, List *qpqual,
134 Index scanrelid, List *values_lists);
135 static CteScan *make_ctescan(List *qptlist, List *qpqual,
136 Index scanrelid, int ctePlanId, int cteParam);
137 static WorkTableScan *make_worktablescan(List *qptlist, List *qpqual,
138 Index scanrelid, int wtParam);
139 static BitmapAnd *make_bitmap_and(List *bitmapplans);
140 static BitmapOr *make_bitmap_or(List *bitmapplans);
141 static NestLoop *make_nestloop(List *tlist,
142 List *joinclauses, List *otherclauses, List *nestParams,
143 Plan *lefttree, Plan *righttree,
145 static HashJoin *make_hashjoin(List *tlist,
146 List *joinclauses, List *otherclauses,
148 Plan *lefttree, Plan *righttree,
150 static Hash *make_hash(Plan *lefttree,
152 AttrNumber skewColumn,
155 int32 skewColTypmod);
156 static MergeJoin *make_mergejoin(List *tlist,
157 List *joinclauses, List *otherclauses,
160 Oid *mergecollations,
161 int *mergestrategies,
162 bool *mergenullsfirst,
163 Plan *lefttree, Plan *righttree,
165 static Sort *make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
166 AttrNumber *sortColIdx, Oid *sortOperators,
167 Oid *collations, bool *nullsFirst,
168 double limit_tuples);
169 static Plan *prepare_sort_from_pathkeys(PlannerInfo *root,
170 Plan *lefttree, List *pathkeys,
172 const AttrNumber *reqColIdx,
173 bool adjust_tlist_in_place,
175 AttrNumber **p_sortColIdx,
176 Oid **p_sortOperators,
178 bool **p_nullsFirst);
179 static EquivalenceMember *find_ec_member_for_tle(EquivalenceClass *ec,
182 static Material *make_material(Plan *lefttree);
187 * Creates the access plan for a query by recursively processing the
188 * desired tree of pathnodes, starting at the node 'best_path'. For
189 * every pathnode found, we create a corresponding plan node containing
190 * appropriate id, target list, and qualification information.
192 * The tlists and quals in the plan tree are still in planner format,
193 * ie, Vars still correspond to the parser's numbering. This will be
194 * fixed later by setrefs.c.
196 * best_path is the best access path
198 * Returns a Plan tree.
201 create_plan(PlannerInfo *root, Path *best_path)
205 /* plan_params should not be in use in current query level */
206 Assert(root->plan_params == NIL);
208 /* Initialize this module's private workspace in PlannerInfo */
209 root->curOuterRels = NULL;
210 root->curOuterParams = NIL;
212 /* Recursively process the path tree */
213 plan = create_plan_recurse(root, best_path);
215 /* Check we successfully assigned all NestLoopParams to plan nodes */
216 if (root->curOuterParams != NIL)
217 elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
220 * Reset plan_params to ensure param IDs used for nestloop params are not
223 root->plan_params = NIL;
229 * create_plan_recurse
230 * Recursive guts of create_plan().
233 create_plan_recurse(PlannerInfo *root, Path *best_path)
237 switch (best_path->pathtype)
242 case T_IndexOnlyScan:
243 case T_BitmapHeapScan:
249 case T_WorkTableScan:
252 plan = create_scan_plan(root, best_path);
257 plan = create_join_plan(root,
258 (JoinPath *) best_path);
261 plan = create_append_plan(root,
262 (AppendPath *) best_path);
265 plan = create_merge_append_plan(root,
266 (MergeAppendPath *) best_path);
269 plan = (Plan *) create_result_plan(root,
270 (ResultPath *) best_path);
273 plan = (Plan *) create_material_plan(root,
274 (MaterialPath *) best_path);
277 plan = create_unique_plan(root,
278 (UniquePath *) best_path);
281 plan = (Plan *) create_gather_plan(root,
282 (GatherPath *) best_path);
285 elog(ERROR, "unrecognized node type: %d",
286 (int) best_path->pathtype);
287 plan = NULL; /* keep compiler quiet */
296 * Create a scan plan for the parent relation of 'best_path'.
299 create_scan_plan(PlannerInfo *root, Path *best_path)
301 RelOptInfo *rel = best_path->parent;
307 * For table scans, rather than using the relation targetlist (which is
308 * only those Vars actually needed by the query), we prefer to generate a
309 * tlist containing all Vars in order. This will allow the executor to
310 * optimize away projection of the table tuples, if possible. (Note that
311 * planner.c may replace the tlist we generate here, forcing projection to
314 if (use_physical_tlist(root, rel))
316 if (best_path->pathtype == T_IndexOnlyScan)
318 /* For index-only scan, the preferred tlist is the index's */
319 tlist = copyObject(((IndexPath *) best_path)->indexinfo->indextlist);
323 tlist = build_physical_tlist(root, rel);
324 /* if fail because of dropped cols, use regular method */
326 tlist = build_path_tlist(root, best_path);
331 tlist = build_path_tlist(root, best_path);
335 * Extract the relevant restriction clauses from the parent relation. The
336 * executor must apply all these restrictions during the scan, except for
337 * pseudoconstants which we'll take care of below.
339 scan_clauses = rel->baserestrictinfo;
342 * If this is a parameterized scan, we also need to enforce all the join
343 * clauses available from the outer relation(s).
345 * For paranoia's sake, don't modify the stored baserestrictinfo list.
347 if (best_path->param_info)
348 scan_clauses = list_concat(list_copy(scan_clauses),
349 best_path->param_info->ppi_clauses);
351 switch (best_path->pathtype)
354 plan = (Plan *) create_seqscan_plan(root,
361 plan = (Plan *) create_samplescan_plan(root,
368 plan = (Plan *) create_indexscan_plan(root,
369 (IndexPath *) best_path,
375 case T_IndexOnlyScan:
376 plan = (Plan *) create_indexscan_plan(root,
377 (IndexPath *) best_path,
383 case T_BitmapHeapScan:
384 plan = (Plan *) create_bitmap_scan_plan(root,
385 (BitmapHeapPath *) best_path,
391 plan = (Plan *) create_tidscan_plan(root,
392 (TidPath *) best_path,
398 plan = (Plan *) create_subqueryscan_plan(root,
405 plan = (Plan *) create_functionscan_plan(root,
412 plan = (Plan *) create_valuesscan_plan(root,
419 plan = (Plan *) create_ctescan_plan(root,
425 case T_WorkTableScan:
426 plan = (Plan *) create_worktablescan_plan(root,
433 plan = (Plan *) create_foreignscan_plan(root,
434 (ForeignPath *) best_path,
440 plan = (Plan *) create_customscan_plan(root,
441 (CustomPath *) best_path,
447 elog(ERROR, "unrecognized node type: %d",
448 (int) best_path->pathtype);
449 plan = NULL; /* keep compiler quiet */
454 * If there are any pseudoconstant clauses attached to this node, insert a
455 * gating Result node that evaluates the pseudoconstants as one-time
458 if (root->hasPseudoConstantQuals)
459 plan = create_gating_plan(root, plan, scan_clauses);
465 * Build a target list (ie, a list of TargetEntry) for the Path's output.
468 build_path_tlist(PlannerInfo *root, Path *path)
470 RelOptInfo *rel = path->parent;
475 foreach(v, rel->reltargetlist)
477 /* Do we really need to copy here? Not sure */
478 Node *node = (Node *) copyObject(lfirst(v));
481 * If it's a parameterized path, there might be lateral references in
482 * the tlist, which need to be replaced with Params. There's no need
483 * to remake the TargetEntry nodes, so apply this to each list item
486 if (path->param_info)
487 node = replace_nestloop_params(root, node);
489 tlist = lappend(tlist, makeTargetEntry((Expr *) node,
500 * Decide whether to use a tlist matching relation structure,
501 * rather than only those Vars actually referenced.
504 use_physical_tlist(PlannerInfo *root, RelOptInfo *rel)
510 * We can do this for real relation scans, subquery scans, function scans,
511 * values scans, and CTE scans (but not for, eg, joins).
513 if (rel->rtekind != RTE_RELATION &&
514 rel->rtekind != RTE_SUBQUERY &&
515 rel->rtekind != RTE_FUNCTION &&
516 rel->rtekind != RTE_VALUES &&
517 rel->rtekind != RTE_CTE)
521 * Can't do it with inheritance cases either (mainly because Append
524 if (rel->reloptkind != RELOPT_BASEREL)
528 * Can't do it if any system columns or whole-row Vars are requested.
529 * (This could possibly be fixed but would take some fragile assumptions
530 * in setrefs.c, I think.)
532 for (i = rel->min_attr; i <= 0; i++)
534 if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
539 * Can't do it if the rel is required to emit any placeholder expressions,
542 foreach(lc, root->placeholder_list)
544 PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
546 if (bms_nonempty_difference(phinfo->ph_needed, rel->relids) &&
547 bms_is_subset(phinfo->ph_eval_at, rel->relids))
555 * disuse_physical_tlist
556 * Switch a plan node back to emitting only Vars actually referenced.
558 * If the plan node immediately above a scan would prefer to get only
559 * needed Vars and not a physical tlist, it must call this routine to
560 * undo the decision made by use_physical_tlist(). Currently, Hash, Sort,
561 * Material, and Gather nodes want this, so they don't have to store or
562 * transfer useless columns.
565 disuse_physical_tlist(PlannerInfo *root, Plan *plan, Path *path)
567 /* Only need to undo it for path types handled by create_scan_plan() */
568 switch (path->pathtype)
573 case T_IndexOnlyScan:
574 case T_BitmapHeapScan:
580 case T_WorkTableScan:
583 plan->targetlist = build_path_tlist(root, path);
592 * Deal with pseudoconstant qual clauses
594 * If the node's quals list includes any pseudoconstant quals, put them
595 * into a gating Result node atop the already-built plan. Otherwise,
596 * return the plan as-is.
598 * Note that we don't change cost or size estimates when doing gating.
599 * The costs of qual eval were already folded into the plan's startup cost.
600 * Leaving the size alone amounts to assuming that the gating qual will
601 * succeed, which is the conservative estimate for planning upper queries.
602 * We certainly don't want to assume the output size is zero (unless the
603 * gating qual is actually constant FALSE, and that case is dealt with in
604 * clausesel.c). Interpolating between the two cases is silly, because
605 * it doesn't reflect what will really happen at runtime, and besides which
606 * in most cases we have only a very bad idea of the probability of the gating
610 create_gating_plan(PlannerInfo *root, Plan *plan, List *quals)
612 List *pseudoconstants;
614 /* Sort into desirable execution order while still in RestrictInfo form */
615 quals = order_qual_clauses(root, quals);
617 /* Pull out any pseudoconstant quals from the RestrictInfo list */
618 pseudoconstants = extract_actual_clauses(quals, true);
620 if (!pseudoconstants)
623 return (Plan *) make_result(root,
625 (Node *) pseudoconstants,
631 * Create a join plan for 'best_path' and (recursively) plans for its
632 * inner and outer paths.
635 create_join_plan(PlannerInfo *root, JoinPath *best_path)
640 Relids saveOuterRels = root->curOuterRels;
642 outer_plan = create_plan_recurse(root, best_path->outerjoinpath);
644 /* For a nestloop, include outer relids in curOuterRels for inner side */
645 if (best_path->path.pathtype == T_NestLoop)
646 root->curOuterRels = bms_union(root->curOuterRels,
647 best_path->outerjoinpath->parent->relids);
649 inner_plan = create_plan_recurse(root, best_path->innerjoinpath);
651 switch (best_path->path.pathtype)
654 plan = (Plan *) create_mergejoin_plan(root,
655 (MergePath *) best_path,
660 plan = (Plan *) create_hashjoin_plan(root,
661 (HashPath *) best_path,
666 /* Restore curOuterRels */
667 bms_free(root->curOuterRels);
668 root->curOuterRels = saveOuterRels;
670 plan = (Plan *) create_nestloop_plan(root,
671 (NestPath *) best_path,
676 elog(ERROR, "unrecognized node type: %d",
677 (int) best_path->path.pathtype);
678 plan = NULL; /* keep compiler quiet */
683 * If there are any pseudoconstant clauses attached to this node, insert a
684 * gating Result node that evaluates the pseudoconstants as one-time
687 if (root->hasPseudoConstantQuals)
688 plan = create_gating_plan(root, plan, best_path->joinrestrictinfo);
693 * * Expensive function pullups may have pulled local predicates * into
694 * this path node. Put them in the qpqual of the plan node. * JMH,
697 if (get_loc_restrictinfo(best_path) != NIL)
698 set_qpqual((Plan) plan,
699 list_concat(get_qpqual((Plan) plan),
700 get_actual_clauses(get_loc_restrictinfo(best_path))));
708 * Create an Append plan for 'best_path' and (recursively) plans
711 * Returns a Plan node.
714 create_append_plan(PlannerInfo *root, AppendPath *best_path)
717 List *tlist = build_path_tlist(root, &best_path->path);
718 List *subplans = NIL;
722 * The subpaths list could be empty, if every child was proven empty by
723 * constraint exclusion. In that case generate a dummy plan that returns
726 * Note that an AppendPath with no members is also generated in certain
727 * cases where there was no appending construct at all, but we know the
728 * relation is empty (see set_dummy_rel_pathlist).
730 if (best_path->subpaths == NIL)
732 /* Generate a Result plan with constant-FALSE gating qual */
733 return (Plan *) make_result(root,
735 (Node *) list_make1(makeBoolConst(false,
740 /* Build the plan for each child */
741 foreach(subpaths, best_path->subpaths)
743 Path *subpath = (Path *) lfirst(subpaths);
745 subplans = lappend(subplans, create_plan_recurse(root, subpath));
749 * XXX ideally, if there's just one child, we'd not bother to generate an
750 * Append node but just return the single child. At the moment this does
751 * not work because the varno of the child scan plan won't match the
752 * parent-rel Vars it'll be asked to emit.
755 plan = make_append(subplans, tlist);
757 return (Plan *) plan;
761 * create_merge_append_plan
762 * Create a MergeAppend plan for 'best_path' and (recursively) plans
765 * Returns a Plan node.
768 create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path)
770 MergeAppend *node = makeNode(MergeAppend);
771 Plan *plan = &node->plan;
772 List *tlist = build_path_tlist(root, &best_path->path);
773 List *pathkeys = best_path->path.pathkeys;
774 List *subplans = NIL;
778 * We don't have the actual creation of the MergeAppend node split out
779 * into a separate make_xxx function. This is because we want to run
780 * prepare_sort_from_pathkeys on it before we do so on the individual
781 * child plans, to make cross-checking the sort info easier.
783 copy_generic_path_info(plan, (Path *) best_path);
784 plan->targetlist = tlist;
786 plan->lefttree = NULL;
787 plan->righttree = NULL;
789 /* Compute sort column info, and adjust MergeAppend's tlist as needed */
790 (void) prepare_sort_from_pathkeys(root, plan, pathkeys,
791 best_path->path.parent->relids,
796 &node->sortOperators,
801 * Now prepare the child plans. We must apply prepare_sort_from_pathkeys
802 * even to subplans that don't need an explicit sort, to make sure they
803 * are returning the same sort key columns the MergeAppend expects.
805 foreach(subpaths, best_path->subpaths)
807 Path *subpath = (Path *) lfirst(subpaths);
810 AttrNumber *sortColIdx;
815 /* Build the child plan */
816 subplan = create_plan_recurse(root, subpath);
818 /* Compute sort column info, and adjust subplan's tlist as needed */
819 subplan = prepare_sort_from_pathkeys(root, subplan, pathkeys,
820 subpath->parent->relids,
830 * Check that we got the same sort key information. We just Assert
831 * that the sortops match, since those depend only on the pathkeys;
832 * but it seems like a good idea to check the sort column numbers
833 * explicitly, to ensure the tlists really do match up.
835 Assert(numsortkeys == node->numCols);
836 if (memcmp(sortColIdx, node->sortColIdx,
837 numsortkeys * sizeof(AttrNumber)) != 0)
838 elog(ERROR, "MergeAppend child's targetlist doesn't match MergeAppend");
839 Assert(memcmp(sortOperators, node->sortOperators,
840 numsortkeys * sizeof(Oid)) == 0);
841 Assert(memcmp(collations, node->collations,
842 numsortkeys * sizeof(Oid)) == 0);
843 Assert(memcmp(nullsFirst, node->nullsFirst,
844 numsortkeys * sizeof(bool)) == 0);
846 /* Now, insert a Sort node if subplan isn't sufficiently ordered */
847 if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
848 subplan = (Plan *) make_sort(root, subplan, numsortkeys,
849 sortColIdx, sortOperators,
850 collations, nullsFirst,
851 best_path->limit_tuples);
853 subplans = lappend(subplans, subplan);
856 node->mergeplans = subplans;
858 return (Plan *) node;
863 * Create a Result plan for 'best_path'.
864 * This is only used for the case of a query with an empty jointree.
866 * Returns a Plan node.
869 create_result_plan(PlannerInfo *root, ResultPath *best_path)
874 /* The tlist will be installed later, since we have no RelOptInfo */
875 Assert(best_path->path.parent == NULL);
878 /* best_path->quals is just bare clauses */
880 quals = order_qual_clauses(root, best_path->quals);
882 return make_result(root, tlist, (Node *) quals, NULL);
886 * create_material_plan
887 * Create a Material plan for 'best_path' and (recursively) plans
890 * Returns a Plan node.
893 create_material_plan(PlannerInfo *root, MaterialPath *best_path)
898 subplan = create_plan_recurse(root, best_path->subpath);
900 /* We don't want any excess columns in the materialized tuples */
901 disuse_physical_tlist(root, subplan, best_path->subpath);
903 plan = make_material(subplan);
905 copy_generic_path_info(&plan->plan, (Path *) best_path);
912 * Create a Unique plan for 'best_path' and (recursively) plans
915 * Returns a Plan node.
918 create_unique_plan(PlannerInfo *root, UniquePath *best_path)
928 AttrNumber *groupColIdx;
932 subplan = create_plan_recurse(root, best_path->subpath);
934 /* Done if we don't need to do any actual unique-ifying */
935 if (best_path->umethod == UNIQUE_PATH_NOOP)
939 * As constructed, the subplan has a "flat" tlist containing just the Vars
940 * needed here and at upper levels. The values we are supposed to
941 * unique-ify may be expressions in these variables. We have to add any
942 * such expressions to the subplan's tlist.
944 * The subplan may have a "physical" tlist if it is a simple scan plan. If
945 * we're going to sort, this should be reduced to the regular tlist, so
946 * that we don't sort more data than we need to. For hashing, the tlist
947 * should be left as-is if we don't need to add any expressions; but if we
948 * do have to add expressions, then a projection step will be needed at
949 * runtime anyway, so we may as well remove unneeded items. Therefore
950 * newtlist starts from build_path_tlist() not just a copy of the
951 * subplan's tlist; and we don't install it into the subplan unless we are
952 * sorting or stuff has to be added.
954 in_operators = best_path->in_operators;
955 uniq_exprs = best_path->uniq_exprs;
957 /* initialize modified subplan tlist as just the "required" vars */
958 newtlist = build_path_tlist(root, &best_path->path);
959 nextresno = list_length(newtlist) + 1;
962 foreach(l, uniq_exprs)
964 Node *uniqexpr = lfirst(l);
967 tle = tlist_member(uniqexpr, newtlist);
970 tle = makeTargetEntry((Expr *) uniqexpr,
974 newtlist = lappend(newtlist, tle);
980 if (newitems || best_path->umethod == UNIQUE_PATH_SORT)
983 * If the top plan node can't do projections and its existing target
984 * list isn't already what we need, we need to add a Result node to
987 if (!is_projection_capable_plan(subplan) &&
988 !tlist_same_exprs(newtlist, subplan->targetlist))
989 subplan = (Plan *) make_result(root, newtlist, NULL, subplan);
991 subplan->targetlist = newtlist;
995 * Build control information showing which subplan output columns are to
996 * be examined by the grouping step. Unfortunately we can't merge this
997 * with the previous loop, since we didn't then know which version of the
998 * subplan tlist we'd end up using.
1000 newtlist = subplan->targetlist;
1001 numGroupCols = list_length(uniq_exprs);
1002 groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber));
1005 foreach(l, uniq_exprs)
1007 Node *uniqexpr = lfirst(l);
1010 tle = tlist_member(uniqexpr, newtlist);
1011 if (!tle) /* shouldn't happen */
1012 elog(ERROR, "failed to find unique expression in subplan tlist");
1013 groupColIdx[groupColPos++] = tle->resno;
1016 if (best_path->umethod == UNIQUE_PATH_HASH)
1019 Oid *groupOperators;
1021 numGroups = (long) Min(best_path->path.rows, (double) LONG_MAX);
1024 * Get the hashable equality operators for the Agg node to use.
1025 * Normally these are the same as the IN clause operators, but if
1026 * those are cross-type operators then the equality operators are the
1027 * ones for the IN clause operators' RHS datatype.
1029 groupOperators = (Oid *) palloc(numGroupCols * sizeof(Oid));
1031 foreach(l, in_operators)
1033 Oid in_oper = lfirst_oid(l);
1036 if (!get_compatible_hash_operators(in_oper, NULL, &eq_oper))
1037 elog(ERROR, "could not find compatible hash operator for operator %u",
1039 groupOperators[groupColPos++] = eq_oper;
1043 * Since the Agg node is going to project anyway, we can give it the
1044 * minimum output tlist, without any stuff we might have added to the
1047 plan = (Plan *) make_agg(root,
1048 build_path_tlist(root, &best_path->path),
1063 List *sortList = NIL;
1065 /* Create an ORDER BY list to sort the input compatibly */
1067 foreach(l, in_operators)
1069 Oid in_oper = lfirst_oid(l);
1073 SortGroupClause *sortcl;
1075 sortop = get_ordering_op_for_equality_op(in_oper, false);
1076 if (!OidIsValid(sortop)) /* shouldn't happen */
1077 elog(ERROR, "could not find ordering operator for equality operator %u",
1081 * The Unique node will need equality operators. Normally these
1082 * are the same as the IN clause operators, but if those are
1083 * cross-type operators then the equality operators are the ones
1084 * for the IN clause operators' RHS datatype.
1086 eqop = get_equality_op_for_ordering_op(sortop, NULL);
1087 if (!OidIsValid(eqop)) /* shouldn't happen */
1088 elog(ERROR, "could not find equality operator for ordering operator %u",
1091 tle = get_tle_by_resno(subplan->targetlist,
1092 groupColIdx[groupColPos]);
1093 Assert(tle != NULL);
1095 sortcl = makeNode(SortGroupClause);
1096 sortcl->tleSortGroupRef = assignSortGroupRef(tle,
1097 subplan->targetlist);
1098 sortcl->eqop = eqop;
1099 sortcl->sortop = sortop;
1100 sortcl->nulls_first = false;
1101 sortcl->hashable = false; /* no need to make this accurate */
1102 sortList = lappend(sortList, sortcl);
1105 plan = (Plan *) make_sort_from_sortclauses(root, sortList, subplan);
1106 plan = (Plan *) make_unique(plan, sortList);
1109 /* Adjust output size estimate (other fields should be OK already) */
1110 plan->plan_rows = best_path->path.rows;
1116 * create_gather_plan
1118 * Create a Gather plan for 'best_path' and (recursively) plans
1122 create_gather_plan(PlannerInfo *root, GatherPath *best_path)
1124 Gather *gather_plan;
1127 subplan = create_plan_recurse(root, best_path->subpath);
1129 disuse_physical_tlist(root, subplan, best_path->subpath);
1131 gather_plan = make_gather(subplan->targetlist,
1133 best_path->path.parallel_degree,
1134 best_path->single_copy,
1137 copy_generic_path_info(&gather_plan->plan, &best_path->path);
1139 /* use parallel mode for parallel plans. */
1140 root->glob->parallelModeNeeded = true;
1146 /*****************************************************************************
1148 * BASE-RELATION SCAN METHODS
1150 *****************************************************************************/
1154 * create_seqscan_plan
1155 * Returns a seqscan plan for the base relation scanned by 'best_path'
1156 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1159 create_seqscan_plan(PlannerInfo *root, Path *best_path,
1160 List *tlist, List *scan_clauses)
1163 Index scan_relid = best_path->parent->relid;
1165 /* it should be a base rel... */
1166 Assert(scan_relid > 0);
1167 Assert(best_path->parent->rtekind == RTE_RELATION);
1169 /* Sort clauses into best execution order */
1170 scan_clauses = order_qual_clauses(root, scan_clauses);
1172 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1173 scan_clauses = extract_actual_clauses(scan_clauses, false);
1175 /* Replace any outer-relation variables with nestloop params */
1176 if (best_path->param_info)
1178 scan_clauses = (List *)
1179 replace_nestloop_params(root, (Node *) scan_clauses);
1182 scan_plan = make_seqscan(tlist,
1186 copy_generic_path_info(&scan_plan->plan, best_path);
1192 * create_samplescan_plan
1193 * Returns a samplescan plan for the base relation scanned by 'best_path'
1194 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1197 create_samplescan_plan(PlannerInfo *root, Path *best_path,
1198 List *tlist, List *scan_clauses)
1200 SampleScan *scan_plan;
1201 Index scan_relid = best_path->parent->relid;
1203 TableSampleClause *tsc;
1205 /* it should be a base rel with a tablesample clause... */
1206 Assert(scan_relid > 0);
1207 rte = planner_rt_fetch(scan_relid, root);
1208 Assert(rte->rtekind == RTE_RELATION);
1209 tsc = rte->tablesample;
1210 Assert(tsc != NULL);
1212 /* Sort clauses into best execution order */
1213 scan_clauses = order_qual_clauses(root, scan_clauses);
1215 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1216 scan_clauses = extract_actual_clauses(scan_clauses, false);
1218 /* Replace any outer-relation variables with nestloop params */
1219 if (best_path->param_info)
1221 scan_clauses = (List *)
1222 replace_nestloop_params(root, (Node *) scan_clauses);
1223 tsc = (TableSampleClause *)
1224 replace_nestloop_params(root, (Node *) tsc);
1227 scan_plan = make_samplescan(tlist,
1232 copy_generic_path_info(&scan_plan->scan.plan, best_path);
1238 * create_indexscan_plan
1239 * Returns an indexscan plan for the base relation scanned by 'best_path'
1240 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1242 * We use this for both plain IndexScans and IndexOnlyScans, because the
1243 * qual preprocessing work is the same for both. Note that the caller tells
1244 * us which to build --- we don't look at best_path->path.pathtype, because
1245 * create_bitmap_subplan needs to be able to override the prior decision.
1248 create_indexscan_plan(PlannerInfo *root,
1249 IndexPath *best_path,
1255 List *indexquals = best_path->indexquals;
1256 List *indexorderbys = best_path->indexorderbys;
1257 Index baserelid = best_path->path.parent->relid;
1258 Oid indexoid = best_path->indexinfo->indexoid;
1260 List *stripped_indexquals;
1261 List *fixed_indexquals;
1262 List *fixed_indexorderbys;
1263 List *indexorderbyops = NIL;
1266 /* it should be a base rel... */
1267 Assert(baserelid > 0);
1268 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1271 * Build "stripped" indexquals structure (no RestrictInfos) to pass to
1272 * executor as indexqualorig
1274 stripped_indexquals = get_actual_clauses(indexquals);
1277 * The executor needs a copy with the indexkey on the left of each clause
1278 * and with index Vars substituted for table ones.
1280 fixed_indexquals = fix_indexqual_references(root, best_path);
1283 * Likewise fix up index attr references in the ORDER BY expressions.
1285 fixed_indexorderbys = fix_indexorderby_references(root, best_path);
1288 * The qpqual list must contain all restrictions not automatically handled
1289 * by the index, other than pseudoconstant clauses which will be handled
1290 * by a separate gating plan node. All the predicates in the indexquals
1291 * will be checked (either by the index itself, or by nodeIndexscan.c),
1292 * but if there are any "special" operators involved then they must be
1293 * included in qpqual. The upshot is that qpqual must contain
1294 * scan_clauses minus whatever appears in indexquals.
1296 * In normal cases simple pointer equality checks will be enough to spot
1297 * duplicate RestrictInfos, so we try that first.
1299 * Another common case is that a scan_clauses entry is generated from the
1300 * same EquivalenceClass as some indexqual, and is therefore redundant
1301 * with it, though not equal. (This happens when indxpath.c prefers a
1302 * different derived equality than what generate_join_implied_equalities
1303 * picked for a parameterized scan's ppi_clauses.)
1305 * In some situations (particularly with OR'd index conditions) we may
1306 * have scan_clauses that are not equal to, but are logically implied by,
1307 * the index quals; so we also try a predicate_implied_by() check to see
1308 * if we can discard quals that way. (predicate_implied_by assumes its
1309 * first input contains only immutable functions, so we have to check
1312 * We can also discard quals that are implied by a partial index's
1313 * predicate, but only in a plain SELECT; when scanning a target relation
1314 * of UPDATE/DELETE/SELECT FOR UPDATE, we must leave such quals in the
1315 * plan so that they'll be properly rechecked by EvalPlanQual testing.
1317 * Note: if you change this bit of code you should also look at
1318 * extract_nonindex_conditions() in costsize.c.
1321 foreach(l, scan_clauses)
1323 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1325 Assert(IsA(rinfo, RestrictInfo));
1326 if (rinfo->pseudoconstant)
1327 continue; /* we may drop pseudoconstants here */
1328 if (list_member_ptr(indexquals, rinfo))
1329 continue; /* simple duplicate */
1330 if (is_redundant_derived_clause(rinfo, indexquals))
1331 continue; /* derived from same EquivalenceClass */
1332 if (!contain_mutable_functions((Node *) rinfo->clause))
1334 List *clausel = list_make1(rinfo->clause);
1336 if (predicate_implied_by(clausel, indexquals))
1337 continue; /* provably implied by indexquals */
1338 if (best_path->indexinfo->indpred)
1340 if (baserelid != root->parse->resultRelation &&
1341 get_plan_rowmark(root->rowMarks, baserelid) == NULL)
1342 if (predicate_implied_by(clausel,
1343 best_path->indexinfo->indpred))
1344 continue; /* implied by index predicate */
1347 qpqual = lappend(qpqual, rinfo);
1350 /* Sort clauses into best execution order */
1351 qpqual = order_qual_clauses(root, qpqual);
1353 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1354 qpqual = extract_actual_clauses(qpqual, false);
1357 * We have to replace any outer-relation variables with nestloop params in
1358 * the indexqualorig, qpqual, and indexorderbyorig expressions. A bit
1359 * annoying to have to do this separately from the processing in
1360 * fix_indexqual_references --- rethink this when generalizing the inner
1361 * indexscan support. But note we can't really do this earlier because
1362 * it'd break the comparisons to predicates above ... (or would it? Those
1363 * wouldn't have outer refs)
1365 if (best_path->path.param_info)
1367 stripped_indexquals = (List *)
1368 replace_nestloop_params(root, (Node *) stripped_indexquals);
1370 replace_nestloop_params(root, (Node *) qpqual);
1371 indexorderbys = (List *)
1372 replace_nestloop_params(root, (Node *) indexorderbys);
1376 * If there are ORDER BY expressions, look up the sort operators for their
1381 ListCell *pathkeyCell,
1385 * PathKey contains OID of the btree opfamily we're sorting by, but
1386 * that's not quite enough because we need the expression's datatype
1387 * to look up the sort operator in the operator family.
1389 Assert(list_length(best_path->path.pathkeys) == list_length(indexorderbys));
1390 forboth(pathkeyCell, best_path->path.pathkeys, exprCell, indexorderbys)
1392 PathKey *pathkey = (PathKey *) lfirst(pathkeyCell);
1393 Node *expr = (Node *) lfirst(exprCell);
1394 Oid exprtype = exprType(expr);
1397 /* Get sort operator from opfamily */
1398 sortop = get_opfamily_member(pathkey->pk_opfamily,
1401 pathkey->pk_strategy);
1402 if (!OidIsValid(sortop))
1403 elog(ERROR, "failed to find sort operator for ORDER BY expression");
1404 indexorderbyops = lappend_oid(indexorderbyops, sortop);
1408 /* Finally ready to build the plan node */
1410 scan_plan = (Scan *) make_indexonlyscan(tlist,
1415 fixed_indexorderbys,
1416 best_path->indexinfo->indextlist,
1417 best_path->indexscandir);
1419 scan_plan = (Scan *) make_indexscan(tlist,
1424 stripped_indexquals,
1425 fixed_indexorderbys,
1428 best_path->indexscandir);
1430 copy_generic_path_info(&scan_plan->plan, &best_path->path);
1436 * create_bitmap_scan_plan
1437 * Returns a bitmap scan plan for the base relation scanned by 'best_path'
1438 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1440 static BitmapHeapScan *
1441 create_bitmap_scan_plan(PlannerInfo *root,
1442 BitmapHeapPath *best_path,
1446 Index baserelid = best_path->path.parent->relid;
1447 Plan *bitmapqualplan;
1448 List *bitmapqualorig;
1453 BitmapHeapScan *scan_plan;
1455 /* it should be a base rel... */
1456 Assert(baserelid > 0);
1457 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1459 /* Process the bitmapqual tree into a Plan tree and qual lists */
1460 bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
1461 &bitmapqualorig, &indexquals,
1465 * The qpqual list must contain all restrictions not automatically handled
1466 * by the index, other than pseudoconstant clauses which will be handled
1467 * by a separate gating plan node. All the predicates in the indexquals
1468 * will be checked (either by the index itself, or by
1469 * nodeBitmapHeapscan.c), but if there are any "special" operators
1470 * involved then they must be added to qpqual. The upshot is that qpqual
1471 * must contain scan_clauses minus whatever appears in indexquals.
1473 * This loop is similar to the comparable code in create_indexscan_plan(),
1474 * but with some differences because it has to compare the scan clauses to
1475 * stripped (no RestrictInfos) indexquals. See comments there for more
1478 * In normal cases simple equal() checks will be enough to spot duplicate
1479 * clauses, so we try that first. We next see if the scan clause is
1480 * redundant with any top-level indexqual by virtue of being generated
1481 * from the same EC. After that, try predicate_implied_by().
1483 * Unlike create_indexscan_plan(), we need take no special thought here
1484 * for partial index predicates; this is because the predicate conditions
1485 * are already listed in bitmapqualorig and indexquals. Bitmap scans have
1486 * to do it that way because predicate conditions need to be rechecked if
1487 * the scan becomes lossy, so they have to be included in bitmapqualorig.
1490 foreach(l, scan_clauses)
1492 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1493 Node *clause = (Node *) rinfo->clause;
1495 Assert(IsA(rinfo, RestrictInfo));
1496 if (rinfo->pseudoconstant)
1497 continue; /* we may drop pseudoconstants here */
1498 if (list_member(indexquals, clause))
1499 continue; /* simple duplicate */
1500 if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
1501 continue; /* derived from same EquivalenceClass */
1502 if (!contain_mutable_functions(clause))
1504 List *clausel = list_make1(clause);
1506 if (predicate_implied_by(clausel, indexquals))
1507 continue; /* provably implied by indexquals */
1509 qpqual = lappend(qpqual, rinfo);
1512 /* Sort clauses into best execution order */
1513 qpqual = order_qual_clauses(root, qpqual);
1515 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1516 qpqual = extract_actual_clauses(qpqual, false);
1519 * When dealing with special operators, we will at this point have
1520 * duplicate clauses in qpqual and bitmapqualorig. We may as well drop
1521 * 'em from bitmapqualorig, since there's no point in making the tests
1524 bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
1527 * We have to replace any outer-relation variables with nestloop params in
1528 * the qpqual and bitmapqualorig expressions. (This was already done for
1529 * expressions attached to plan nodes in the bitmapqualplan tree.)
1531 if (best_path->path.param_info)
1534 replace_nestloop_params(root, (Node *) qpqual);
1535 bitmapqualorig = (List *)
1536 replace_nestloop_params(root, (Node *) bitmapqualorig);
1539 /* Finally ready to build the plan node */
1540 scan_plan = make_bitmap_heapscan(tlist,
1546 copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
1552 * Given a bitmapqual tree, generate the Plan tree that implements it
1554 * As byproducts, we also return in *qual and *indexqual the qual lists
1555 * (in implicit-AND form, without RestrictInfos) describing the original index
1556 * conditions and the generated indexqual conditions. (These are the same in
1557 * simple cases, but when special index operators are involved, the former
1558 * list includes the special conditions while the latter includes the actual
1559 * indexable conditions derived from them.) Both lists include partial-index
1560 * predicates, because we have to recheck predicates as well as index
1561 * conditions if the bitmap scan becomes lossy.
1563 * In addition, we return a list of EquivalenceClass pointers for all the
1564 * top-level indexquals that were possibly-redundantly derived from ECs.
1565 * This allows removal of scan_clauses that are redundant with such quals.
1566 * (We do not attempt to detect such redundancies for quals that are within
1567 * OR subtrees. This could be done in a less hacky way if we returned the
1568 * indexquals in RestrictInfo form, but that would be slower and still pretty
1569 * messy, since we'd have to build new RestrictInfos in many cases.)
1572 create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
1573 List **qual, List **indexqual, List **indexECs)
1577 if (IsA(bitmapqual, BitmapAndPath))
1579 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
1580 List *subplans = NIL;
1581 List *subquals = NIL;
1582 List *subindexquals = NIL;
1583 List *subindexECs = NIL;
1587 * There may well be redundant quals among the subplans, since a
1588 * top-level WHERE qual might have gotten used to form several
1589 * different index quals. We don't try exceedingly hard to eliminate
1590 * redundancies, but we do eliminate obvious duplicates by using
1591 * list_concat_unique.
1593 foreach(l, apath->bitmapquals)
1600 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1601 &subqual, &subindexqual,
1603 subplans = lappend(subplans, subplan);
1604 subquals = list_concat_unique(subquals, subqual);
1605 subindexquals = list_concat_unique(subindexquals, subindexqual);
1606 /* Duplicates in indexECs aren't worth getting rid of */
1607 subindexECs = list_concat(subindexECs, subindexEC);
1609 plan = (Plan *) make_bitmap_and(subplans);
1610 plan->startup_cost = apath->path.startup_cost;
1611 plan->total_cost = apath->path.total_cost;
1613 clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
1614 plan->plan_width = 0; /* meaningless */
1616 *indexqual = subindexquals;
1617 *indexECs = subindexECs;
1619 else if (IsA(bitmapqual, BitmapOrPath))
1621 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
1622 List *subplans = NIL;
1623 List *subquals = NIL;
1624 List *subindexquals = NIL;
1625 bool const_true_subqual = false;
1626 bool const_true_subindexqual = false;
1630 * Here, we only detect qual-free subplans. A qual-free subplan would
1631 * cause us to generate "... OR true ..." which we may as well reduce
1632 * to just "true". We do not try to eliminate redundant subclauses
1633 * because (a) it's not as likely as in the AND case, and (b) we might
1634 * well be working with hundreds or even thousands of OR conditions,
1635 * perhaps from a long IN list. The performance of list_append_unique
1636 * would be unacceptable.
1638 foreach(l, opath->bitmapquals)
1645 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1646 &subqual, &subindexqual,
1648 subplans = lappend(subplans, subplan);
1650 const_true_subqual = true;
1651 else if (!const_true_subqual)
1652 subquals = lappend(subquals,
1653 make_ands_explicit(subqual));
1654 if (subindexqual == NIL)
1655 const_true_subindexqual = true;
1656 else if (!const_true_subindexqual)
1657 subindexquals = lappend(subindexquals,
1658 make_ands_explicit(subindexqual));
1662 * In the presence of ScalarArrayOpExpr quals, we might have built
1663 * BitmapOrPaths with just one subpath; don't add an OR step.
1665 if (list_length(subplans) == 1)
1667 plan = (Plan *) linitial(subplans);
1671 plan = (Plan *) make_bitmap_or(subplans);
1672 plan->startup_cost = opath->path.startup_cost;
1673 plan->total_cost = opath->path.total_cost;
1675 clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
1676 plan->plan_width = 0; /* meaningless */
1680 * If there were constant-TRUE subquals, the OR reduces to constant
1681 * TRUE. Also, avoid generating one-element ORs, which could happen
1682 * due to redundancy elimination or ScalarArrayOpExpr quals.
1684 if (const_true_subqual)
1686 else if (list_length(subquals) <= 1)
1689 *qual = list_make1(make_orclause(subquals));
1690 if (const_true_subindexqual)
1692 else if (list_length(subindexquals) <= 1)
1693 *indexqual = subindexquals;
1695 *indexqual = list_make1(make_orclause(subindexquals));
1698 else if (IsA(bitmapqual, IndexPath))
1700 IndexPath *ipath = (IndexPath *) bitmapqual;
1705 /* Use the regular indexscan plan build machinery... */
1706 iscan = (IndexScan *) create_indexscan_plan(root, ipath,
1708 Assert(IsA(iscan, IndexScan));
1709 /* then convert to a bitmap indexscan */
1710 plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
1713 iscan->indexqualorig);
1714 plan->startup_cost = 0.0;
1715 plan->total_cost = ipath->indextotalcost;
1717 clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
1718 plan->plan_width = 0; /* meaningless */
1719 *qual = get_actual_clauses(ipath->indexclauses);
1720 *indexqual = get_actual_clauses(ipath->indexquals);
1721 foreach(l, ipath->indexinfo->indpred)
1723 Expr *pred = (Expr *) lfirst(l);
1726 * We know that the index predicate must have been implied by the
1727 * query condition as a whole, but it may or may not be implied by
1728 * the conditions that got pushed into the bitmapqual. Avoid
1729 * generating redundant conditions.
1731 if (!predicate_implied_by(list_make1(pred), ipath->indexclauses))
1733 *qual = lappend(*qual, pred);
1734 *indexqual = lappend(*indexqual, pred);
1738 foreach(l, ipath->indexquals)
1740 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1742 if (rinfo->parent_ec)
1743 subindexECs = lappend(subindexECs, rinfo->parent_ec);
1745 *indexECs = subindexECs;
1749 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
1750 plan = NULL; /* keep compiler quiet */
1757 * create_tidscan_plan
1758 * Returns a tidscan plan for the base relation scanned by 'best_path'
1759 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1762 create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
1763 List *tlist, List *scan_clauses)
1766 Index scan_relid = best_path->path.parent->relid;
1767 List *tidquals = best_path->tidquals;
1770 /* it should be a base rel... */
1771 Assert(scan_relid > 0);
1772 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1774 /* Sort clauses into best execution order */
1775 scan_clauses = order_qual_clauses(root, scan_clauses);
1777 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1778 scan_clauses = extract_actual_clauses(scan_clauses, false);
1780 /* Replace any outer-relation variables with nestloop params */
1781 if (best_path->path.param_info)
1784 replace_nestloop_params(root, (Node *) tidquals);
1785 scan_clauses = (List *)
1786 replace_nestloop_params(root, (Node *) scan_clauses);
1790 * Remove any clauses that are TID quals. This is a bit tricky since the
1791 * tidquals list has implicit OR semantics.
1793 ortidquals = tidquals;
1794 if (list_length(ortidquals) > 1)
1795 ortidquals = list_make1(make_orclause(ortidquals));
1796 scan_clauses = list_difference(scan_clauses, ortidquals);
1798 scan_plan = make_tidscan(tlist,
1803 copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
1809 * create_subqueryscan_plan
1810 * Returns a subqueryscan plan for the base relation scanned by 'best_path'
1811 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1813 static SubqueryScan *
1814 create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
1815 List *tlist, List *scan_clauses)
1817 SubqueryScan *scan_plan;
1818 Index scan_relid = best_path->parent->relid;
1820 /* it should be a subquery base rel... */
1821 Assert(scan_relid > 0);
1822 Assert(best_path->parent->rtekind == RTE_SUBQUERY);
1824 /* Sort clauses into best execution order */
1825 scan_clauses = order_qual_clauses(root, scan_clauses);
1827 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1828 scan_clauses = extract_actual_clauses(scan_clauses, false);
1830 /* Replace any outer-relation variables with nestloop params */
1831 if (best_path->param_info)
1833 scan_clauses = (List *)
1834 replace_nestloop_params(root, (Node *) scan_clauses);
1835 process_subquery_nestloop_params(root,
1836 best_path->parent->subplan_params);
1839 scan_plan = make_subqueryscan(tlist,
1842 best_path->parent->subplan);
1844 copy_generic_path_info(&scan_plan->scan.plan, best_path);
1850 * create_functionscan_plan
1851 * Returns a functionscan plan for the base relation scanned by 'best_path'
1852 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1854 static FunctionScan *
1855 create_functionscan_plan(PlannerInfo *root, Path *best_path,
1856 List *tlist, List *scan_clauses)
1858 FunctionScan *scan_plan;
1859 Index scan_relid = best_path->parent->relid;
1863 /* it should be a function base rel... */
1864 Assert(scan_relid > 0);
1865 rte = planner_rt_fetch(scan_relid, root);
1866 Assert(rte->rtekind == RTE_FUNCTION);
1867 functions = rte->functions;
1869 /* Sort clauses into best execution order */
1870 scan_clauses = order_qual_clauses(root, scan_clauses);
1872 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1873 scan_clauses = extract_actual_clauses(scan_clauses, false);
1875 /* Replace any outer-relation variables with nestloop params */
1876 if (best_path->param_info)
1878 scan_clauses = (List *)
1879 replace_nestloop_params(root, (Node *) scan_clauses);
1880 /* The function expressions could contain nestloop params, too */
1881 functions = (List *) replace_nestloop_params(root, (Node *) functions);
1884 scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
1885 functions, rte->funcordinality);
1887 copy_generic_path_info(&scan_plan->scan.plan, best_path);
1893 * create_valuesscan_plan
1894 * Returns a valuesscan plan for the base relation scanned by 'best_path'
1895 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1898 create_valuesscan_plan(PlannerInfo *root, Path *best_path,
1899 List *tlist, List *scan_clauses)
1901 ValuesScan *scan_plan;
1902 Index scan_relid = best_path->parent->relid;
1906 /* it should be a values base rel... */
1907 Assert(scan_relid > 0);
1908 rte = planner_rt_fetch(scan_relid, root);
1909 Assert(rte->rtekind == RTE_VALUES);
1910 values_lists = rte->values_lists;
1912 /* Sort clauses into best execution order */
1913 scan_clauses = order_qual_clauses(root, scan_clauses);
1915 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1916 scan_clauses = extract_actual_clauses(scan_clauses, false);
1918 /* Replace any outer-relation variables with nestloop params */
1919 if (best_path->param_info)
1921 scan_clauses = (List *)
1922 replace_nestloop_params(root, (Node *) scan_clauses);
1923 /* The values lists could contain nestloop params, too */
1924 values_lists = (List *)
1925 replace_nestloop_params(root, (Node *) values_lists);
1928 scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid,
1931 copy_generic_path_info(&scan_plan->scan.plan, best_path);
1937 * create_ctescan_plan
1938 * Returns a ctescan plan for the base relation scanned by 'best_path'
1939 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1942 create_ctescan_plan(PlannerInfo *root, Path *best_path,
1943 List *tlist, List *scan_clauses)
1946 Index scan_relid = best_path->parent->relid;
1948 SubPlan *ctesplan = NULL;
1951 PlannerInfo *cteroot;
1956 Assert(scan_relid > 0);
1957 rte = planner_rt_fetch(scan_relid, root);
1958 Assert(rte->rtekind == RTE_CTE);
1959 Assert(!rte->self_reference);
1962 * Find the referenced CTE, and locate the SubPlan previously made for it.
1964 levelsup = rte->ctelevelsup;
1966 while (levelsup-- > 0)
1968 cteroot = cteroot->parent_root;
1969 if (!cteroot) /* shouldn't happen */
1970 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
1974 * Note: cte_plan_ids can be shorter than cteList, if we are still working
1975 * on planning the CTEs (ie, this is a side-reference from another CTE).
1976 * So we mustn't use forboth here.
1979 foreach(lc, cteroot->parse->cteList)
1981 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
1983 if (strcmp(cte->ctename, rte->ctename) == 0)
1987 if (lc == NULL) /* shouldn't happen */
1988 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
1989 if (ndx >= list_length(cteroot->cte_plan_ids))
1990 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
1991 plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
1992 Assert(plan_id > 0);
1993 foreach(lc, cteroot->init_plans)
1995 ctesplan = (SubPlan *) lfirst(lc);
1996 if (ctesplan->plan_id == plan_id)
1999 if (lc == NULL) /* shouldn't happen */
2000 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
2003 * We need the CTE param ID, which is the sole member of the SubPlan's
2006 cte_param_id = linitial_int(ctesplan->setParam);
2008 /* Sort clauses into best execution order */
2009 scan_clauses = order_qual_clauses(root, scan_clauses);
2011 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2012 scan_clauses = extract_actual_clauses(scan_clauses, false);
2014 /* Replace any outer-relation variables with nestloop params */
2015 if (best_path->param_info)
2017 scan_clauses = (List *)
2018 replace_nestloop_params(root, (Node *) scan_clauses);
2021 scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
2022 plan_id, cte_param_id);
2024 copy_generic_path_info(&scan_plan->scan.plan, best_path);
2030 * create_worktablescan_plan
2031 * Returns a worktablescan plan for the base relation scanned by 'best_path'
2032 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2034 static WorkTableScan *
2035 create_worktablescan_plan(PlannerInfo *root, Path *best_path,
2036 List *tlist, List *scan_clauses)
2038 WorkTableScan *scan_plan;
2039 Index scan_relid = best_path->parent->relid;
2042 PlannerInfo *cteroot;
2044 Assert(scan_relid > 0);
2045 rte = planner_rt_fetch(scan_relid, root);
2046 Assert(rte->rtekind == RTE_CTE);
2047 Assert(rte->self_reference);
2050 * We need to find the worktable param ID, which is in the plan level
2051 * that's processing the recursive UNION, which is one level *below* where
2052 * the CTE comes from.
2054 levelsup = rte->ctelevelsup;
2055 if (levelsup == 0) /* shouldn't happen */
2056 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2059 while (levelsup-- > 0)
2061 cteroot = cteroot->parent_root;
2062 if (!cteroot) /* shouldn't happen */
2063 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2065 if (cteroot->wt_param_id < 0) /* shouldn't happen */
2066 elog(ERROR, "could not find param ID for CTE \"%s\"", rte->ctename);
2068 /* Sort clauses into best execution order */
2069 scan_clauses = order_qual_clauses(root, scan_clauses);
2071 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2072 scan_clauses = extract_actual_clauses(scan_clauses, false);
2074 /* Replace any outer-relation variables with nestloop params */
2075 if (best_path->param_info)
2077 scan_clauses = (List *)
2078 replace_nestloop_params(root, (Node *) scan_clauses);
2081 scan_plan = make_worktablescan(tlist, scan_clauses, scan_relid,
2082 cteroot->wt_param_id);
2084 copy_generic_path_info(&scan_plan->scan.plan, best_path);
2090 * create_foreignscan_plan
2091 * Returns a foreignscan plan for the relation scanned by 'best_path'
2092 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2094 static ForeignScan *
2095 create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
2096 List *tlist, List *scan_clauses)
2098 ForeignScan *scan_plan;
2099 RelOptInfo *rel = best_path->path.parent;
2100 Index scan_relid = rel->relid;
2101 Oid rel_oid = InvalidOid;
2102 Bitmapset *attrs_used = NULL;
2103 Plan *outer_plan = NULL;
2107 Assert(rel->fdwroutine != NULL);
2109 /* transform the child path if any */
2110 if (best_path->fdw_outerpath)
2111 outer_plan = create_plan_recurse(root, best_path->fdw_outerpath);
2114 * If we're scanning a base relation, fetch its OID. (Irrelevant if
2115 * scanning a join relation.)
2121 Assert(rel->rtekind == RTE_RELATION);
2122 rte = planner_rt_fetch(scan_relid, root);
2123 Assert(rte->rtekind == RTE_RELATION);
2124 rel_oid = rte->relid;
2128 * Sort clauses into best execution order. We do this first since the FDW
2129 * might have more info than we do and wish to adjust the ordering.
2131 scan_clauses = order_qual_clauses(root, scan_clauses);
2134 * Let the FDW perform its processing on the restriction clauses and
2135 * generate the plan node. Note that the FDW might remove restriction
2136 * clauses that it intends to execute remotely, or even add more (if it
2137 * has selected some join clauses for remote use but also wants them
2138 * rechecked locally).
2140 scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid,
2142 tlist, scan_clauses,
2145 /* Copy cost data from Path to Plan; no need to make FDW do this */
2146 copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
2148 /* Copy foreign server OID; likewise, no need to make FDW do this */
2149 scan_plan->fs_server = rel->serverid;
2151 /* Likewise, copy the relids that are represented by this foreign scan */
2152 scan_plan->fs_relids = best_path->path.parent->relids;
2155 * If a join between foreign relations was pushed down, remember it. The
2156 * push-down safety of the join depends upon the server and user mapping
2157 * being same. That can change between planning and execution time, in which
2158 * case the plan should be invalidated.
2160 if (scan_relid == 0)
2161 root->glob->hasForeignJoin = true;
2164 * Replace any outer-relation variables with nestloop params in the qual,
2165 * fdw_exprs and fdw_recheck_quals expressions. We do this last so that
2166 * the FDW doesn't have to be involved. (Note that parts of fdw_exprs
2167 * or fdw_recheck_quals could have come from join clauses, so doing this
2168 * beforehand on the scan_clauses wouldn't work.) We assume
2169 * fdw_scan_tlist contains no such variables.
2171 if (best_path->path.param_info)
2173 scan_plan->scan.plan.qual = (List *)
2174 replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
2175 scan_plan->fdw_exprs = (List *)
2176 replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
2177 scan_plan->fdw_recheck_quals = (List *)
2178 replace_nestloop_params(root,
2179 (Node *) scan_plan->fdw_recheck_quals);
2183 * Detect whether any system columns are requested from rel. This is a
2184 * bit of a kluge and might go away someday, so we intentionally leave it
2185 * out of the API presented to FDWs.
2187 * First, examine all the attributes needed for joins or final output.
2188 * Note: we must look at reltargetlist, not the attr_needed data, because
2189 * attr_needed isn't computed for inheritance child rels.
2191 pull_varattnos((Node *) rel->reltargetlist, rel->relid, &attrs_used);
2193 /* Add all the attributes used by restriction clauses. */
2194 foreach(lc, rel->baserestrictinfo)
2196 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2198 pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
2201 /* Now, are any system columns requested from rel? */
2202 scan_plan->fsSystemCol = false;
2203 for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
2205 if (bms_is_member(i - FirstLowInvalidHeapAttributeNumber, attrs_used))
2207 scan_plan->fsSystemCol = true;
2212 bms_free(attrs_used);
2218 * create_custom_plan
2220 * Transform a CustomPath into a Plan.
2223 create_customscan_plan(PlannerInfo *root, CustomPath *best_path,
2224 List *tlist, List *scan_clauses)
2227 RelOptInfo *rel = best_path->path.parent;
2228 List *custom_plans = NIL;
2231 /* Recursively transform child paths. */
2232 foreach(lc, best_path->custom_paths)
2234 Plan *plan = create_plan_recurse(root, (Path *) lfirst(lc));
2236 custom_plans = lappend(custom_plans, plan);
2240 * Sort clauses into the best execution order, although custom-scan
2241 * provider can reorder them again.
2243 scan_clauses = order_qual_clauses(root, scan_clauses);
2246 * Invoke custom plan provider to create the Plan node represented by the
2249 cplan = (CustomScan *) best_path->methods->PlanCustomPath(root,
2255 Assert(IsA(cplan, CustomScan));
2258 * Copy cost data from Path to Plan; no need to make custom-plan providers
2261 copy_generic_path_info(&cplan->scan.plan, &best_path->path);
2263 /* Likewise, copy the relids that are represented by this custom scan */
2264 cplan->custom_relids = best_path->path.parent->relids;
2267 * Replace any outer-relation variables with nestloop params in the qual
2268 * and custom_exprs expressions. We do this last so that the custom-plan
2269 * provider doesn't have to be involved. (Note that parts of custom_exprs
2270 * could have come from join clauses, so doing this beforehand on the
2271 * scan_clauses wouldn't work.) We assume custom_scan_tlist contains no
2274 if (best_path->path.param_info)
2276 cplan->scan.plan.qual = (List *)
2277 replace_nestloop_params(root, (Node *) cplan->scan.plan.qual);
2278 cplan->custom_exprs = (List *)
2279 replace_nestloop_params(root, (Node *) cplan->custom_exprs);
2286 /*****************************************************************************
2290 *****************************************************************************/
2293 create_nestloop_plan(PlannerInfo *root,
2294 NestPath *best_path,
2298 NestLoop *join_plan;
2299 List *tlist = build_path_tlist(root, &best_path->path);
2300 List *joinrestrictclauses = best_path->joinrestrictinfo;
2309 /* Sort join qual clauses into best execution order */
2310 joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
2312 /* Get the join qual clauses (in plain expression form) */
2313 /* Any pseudoconstant clauses are ignored here */
2314 if (IS_OUTER_JOIN(best_path->jointype))
2316 extract_actual_join_clauses(joinrestrictclauses,
2317 &joinclauses, &otherclauses);
2321 /* We can treat all clauses alike for an inner join */
2322 joinclauses = extract_actual_clauses(joinrestrictclauses, false);
2326 /* Replace any outer-relation variables with nestloop params */
2327 if (best_path->path.param_info)
2329 joinclauses = (List *)
2330 replace_nestloop_params(root, (Node *) joinclauses);
2331 otherclauses = (List *)
2332 replace_nestloop_params(root, (Node *) otherclauses);
2336 * Identify any nestloop parameters that should be supplied by this join
2337 * node, and move them from root->curOuterParams to the nestParams list.
2339 outerrelids = best_path->outerjoinpath->parent->relids;
2342 for (cell = list_head(root->curOuterParams); cell; cell = next)
2344 NestLoopParam *nlp = (NestLoopParam *) lfirst(cell);
2347 if (IsA(nlp->paramval, Var) &&
2348 bms_is_member(nlp->paramval->varno, outerrelids))
2350 root->curOuterParams = list_delete_cell(root->curOuterParams,
2352 nestParams = lappend(nestParams, nlp);
2354 else if (IsA(nlp->paramval, PlaceHolderVar) &&
2355 bms_overlap(((PlaceHolderVar *) nlp->paramval)->phrels,
2357 bms_is_subset(find_placeholder_info(root,
2358 (PlaceHolderVar *) nlp->paramval,
2362 root->curOuterParams = list_delete_cell(root->curOuterParams,
2364 nestParams = lappend(nestParams, nlp);
2370 join_plan = make_nestloop(tlist,
2376 best_path->jointype);
2378 copy_generic_path_info(&join_plan->join.plan, &best_path->path);
2384 create_mergejoin_plan(PlannerInfo *root,
2385 MergePath *best_path,
2389 List *tlist = build_path_tlist(root, &best_path->jpath.path);
2393 List *outerpathkeys;
2394 List *innerpathkeys;
2397 Oid *mergecollations;
2398 int *mergestrategies;
2399 bool *mergenullsfirst;
2400 MergeJoin *join_plan;
2406 /* Sort join qual clauses into best execution order */
2407 /* NB: do NOT reorder the mergeclauses */
2408 joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
2410 /* Get the join qual clauses (in plain expression form) */
2411 /* Any pseudoconstant clauses are ignored here */
2412 if (IS_OUTER_JOIN(best_path->jpath.jointype))
2414 extract_actual_join_clauses(joinclauses,
2415 &joinclauses, &otherclauses);
2419 /* We can treat all clauses alike for an inner join */
2420 joinclauses = extract_actual_clauses(joinclauses, false);
2425 * Remove the mergeclauses from the list of join qual clauses, leaving the
2426 * list of quals that must be checked as qpquals.
2428 mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
2429 joinclauses = list_difference(joinclauses, mergeclauses);
2432 * Replace any outer-relation variables with nestloop params. There
2433 * should not be any in the mergeclauses.
2435 if (best_path->jpath.path.param_info)
2437 joinclauses = (List *)
2438 replace_nestloop_params(root, (Node *) joinclauses);
2439 otherclauses = (List *)
2440 replace_nestloop_params(root, (Node *) otherclauses);
2444 * Rearrange mergeclauses, if needed, so that the outer variable is always
2445 * on the left; mark the mergeclause restrictinfos with correct
2446 * outer_is_left status.
2448 mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
2449 best_path->jpath.outerjoinpath->parent->relids);
2452 * Create explicit sort nodes for the outer and inner paths if necessary.
2453 * Make sure there are no excess columns in the inputs if sorting.
2455 if (best_path->outersortkeys)
2457 disuse_physical_tlist(root, outer_plan, best_path->jpath.outerjoinpath);
2458 outer_plan = (Plan *)
2459 make_sort_from_pathkeys(root,
2461 best_path->outersortkeys,
2463 outerpathkeys = best_path->outersortkeys;
2466 outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
2468 if (best_path->innersortkeys)
2470 disuse_physical_tlist(root, inner_plan, best_path->jpath.innerjoinpath);
2471 inner_plan = (Plan *)
2472 make_sort_from_pathkeys(root,
2474 best_path->innersortkeys,
2476 innerpathkeys = best_path->innersortkeys;
2479 innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
2482 * If specified, add a materialize node to shield the inner plan from the
2483 * need to handle mark/restore.
2485 if (best_path->materialize_inner)
2487 Plan *matplan = (Plan *) make_material(inner_plan);
2490 * We assume the materialize will not spill to disk, and therefore
2491 * charge just cpu_operator_cost per tuple. (Keep this estimate in
2492 * sync with final_cost_mergejoin.)
2494 copy_plan_costsize(matplan, inner_plan);
2495 matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
2497 inner_plan = matplan;
2501 * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
2502 * executor. The information is in the pathkeys for the two inputs, but
2503 * we need to be careful about the possibility of mergeclauses sharing a
2504 * pathkey (compare find_mergeclauses_for_pathkeys()).
2506 nClauses = list_length(mergeclauses);
2507 Assert(nClauses == list_length(best_path->path_mergeclauses));
2508 mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
2509 mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
2510 mergestrategies = (int *) palloc(nClauses * sizeof(int));
2511 mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
2513 lop = list_head(outerpathkeys);
2514 lip = list_head(innerpathkeys);
2516 foreach(lc, best_path->path_mergeclauses)
2518 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2519 EquivalenceClass *oeclass;
2520 EquivalenceClass *ieclass;
2523 EquivalenceClass *opeclass;
2524 EquivalenceClass *ipeclass;
2527 /* fetch outer/inner eclass from mergeclause */
2528 Assert(IsA(rinfo, RestrictInfo));
2529 if (rinfo->outer_is_left)
2531 oeclass = rinfo->left_ec;
2532 ieclass = rinfo->right_ec;
2536 oeclass = rinfo->right_ec;
2537 ieclass = rinfo->left_ec;
2539 Assert(oeclass != NULL);
2540 Assert(ieclass != NULL);
2543 * For debugging purposes, we check that the eclasses match the paths'
2544 * pathkeys. In typical cases the merge clauses are one-to-one with
2545 * the pathkeys, but when dealing with partially redundant query
2546 * conditions, we might have clauses that re-reference earlier path
2547 * keys. The case that we need to reject is where a pathkey is
2548 * entirely skipped over.
2550 * lop and lip reference the first as-yet-unused pathkey elements;
2551 * it's okay to match them, or any element before them. If they're
2552 * NULL then we have found all pathkey elements to be used.
2556 opathkey = (PathKey *) lfirst(lop);
2557 opeclass = opathkey->pk_eclass;
2558 if (oeclass == opeclass)
2560 /* fast path for typical case */
2565 /* redundant clauses ... must match something before lop */
2566 foreach(l2, outerpathkeys)
2570 opathkey = (PathKey *) lfirst(l2);
2571 opeclass = opathkey->pk_eclass;
2572 if (oeclass == opeclass)
2575 if (oeclass != opeclass)
2576 elog(ERROR, "outer pathkeys do not match mergeclauses");
2581 /* redundant clauses ... must match some already-used pathkey */
2584 foreach(l2, outerpathkeys)
2586 opathkey = (PathKey *) lfirst(l2);
2587 opeclass = opathkey->pk_eclass;
2588 if (oeclass == opeclass)
2592 elog(ERROR, "outer pathkeys do not match mergeclauses");
2597 ipathkey = (PathKey *) lfirst(lip);
2598 ipeclass = ipathkey->pk_eclass;
2599 if (ieclass == ipeclass)
2601 /* fast path for typical case */
2606 /* redundant clauses ... must match something before lip */
2607 foreach(l2, innerpathkeys)
2611 ipathkey = (PathKey *) lfirst(l2);
2612 ipeclass = ipathkey->pk_eclass;
2613 if (ieclass == ipeclass)
2616 if (ieclass != ipeclass)
2617 elog(ERROR, "inner pathkeys do not match mergeclauses");
2622 /* redundant clauses ... must match some already-used pathkey */
2625 foreach(l2, innerpathkeys)
2627 ipathkey = (PathKey *) lfirst(l2);
2628 ipeclass = ipathkey->pk_eclass;
2629 if (ieclass == ipeclass)
2633 elog(ERROR, "inner pathkeys do not match mergeclauses");
2636 /* pathkeys should match each other too (more debugging) */
2637 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
2638 opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
2639 opathkey->pk_strategy != ipathkey->pk_strategy ||
2640 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
2641 elog(ERROR, "left and right pathkeys do not match in mergejoin");
2643 /* OK, save info for executor */
2644 mergefamilies[i] = opathkey->pk_opfamily;
2645 mergecollations[i] = opathkey->pk_eclass->ec_collation;
2646 mergestrategies[i] = opathkey->pk_strategy;
2647 mergenullsfirst[i] = opathkey->pk_nulls_first;
2652 * Note: it is not an error if we have additional pathkey elements (i.e.,
2653 * lop or lip isn't NULL here). The input paths might be better-sorted
2654 * than we need for the current mergejoin.
2658 * Now we can build the mergejoin node.
2660 join_plan = make_mergejoin(tlist,
2670 best_path->jpath.jointype);
2672 /* Costs of sort and material steps are included in path cost already */
2673 copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
2679 create_hashjoin_plan(PlannerInfo *root,
2680 HashPath *best_path,
2684 List *tlist = build_path_tlist(root, &best_path->jpath.path);
2688 Oid skewTable = InvalidOid;
2689 AttrNumber skewColumn = InvalidAttrNumber;
2690 bool skewInherit = false;
2691 Oid skewColType = InvalidOid;
2692 int32 skewColTypmod = -1;
2693 HashJoin *join_plan;
2696 /* Sort join qual clauses into best execution order */
2697 joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
2698 /* There's no point in sorting the hash clauses ... */
2700 /* Get the join qual clauses (in plain expression form) */
2701 /* Any pseudoconstant clauses are ignored here */
2702 if (IS_OUTER_JOIN(best_path->jpath.jointype))
2704 extract_actual_join_clauses(joinclauses,
2705 &joinclauses, &otherclauses);
2709 /* We can treat all clauses alike for an inner join */
2710 joinclauses = extract_actual_clauses(joinclauses, false);
2715 * Remove the hashclauses from the list of join qual clauses, leaving the
2716 * list of quals that must be checked as qpquals.
2718 hashclauses = get_actual_clauses(best_path->path_hashclauses);
2719 joinclauses = list_difference(joinclauses, hashclauses);
2722 * Replace any outer-relation variables with nestloop params. There
2723 * should not be any in the hashclauses.
2725 if (best_path->jpath.path.param_info)
2727 joinclauses = (List *)
2728 replace_nestloop_params(root, (Node *) joinclauses);
2729 otherclauses = (List *)
2730 replace_nestloop_params(root, (Node *) otherclauses);
2734 * Rearrange hashclauses, if needed, so that the outer variable is always
2737 hashclauses = get_switched_clauses(best_path->path_hashclauses,
2738 best_path->jpath.outerjoinpath->parent->relids);
2740 /* We don't want any excess columns in the hashed tuples */
2741 disuse_physical_tlist(root, inner_plan, best_path->jpath.innerjoinpath);
2743 /* If we expect batching, suppress excess columns in outer tuples too */
2744 if (best_path->num_batches > 1)
2745 disuse_physical_tlist(root, outer_plan, best_path->jpath.outerjoinpath);
2748 * If there is a single join clause and we can identify the outer variable
2749 * as a simple column reference, supply its identity for possible use in
2750 * skew optimization. (Note: in principle we could do skew optimization
2751 * with multiple join clauses, but we'd have to be able to determine the
2752 * most common combinations of outer values, which we don't currently have
2753 * enough stats for.)
2755 if (list_length(hashclauses) == 1)
2757 OpExpr *clause = (OpExpr *) linitial(hashclauses);
2760 Assert(is_opclause(clause));
2761 node = (Node *) linitial(clause->args);
2762 if (IsA(node, RelabelType))
2763 node = (Node *) ((RelabelType *) node)->arg;
2766 Var *var = (Var *) node;
2769 rte = root->simple_rte_array[var->varno];
2770 if (rte->rtekind == RTE_RELATION)
2772 skewTable = rte->relid;
2773 skewColumn = var->varattno;
2774 skewInherit = rte->inh;
2775 skewColType = var->vartype;
2776 skewColTypmod = var->vartypmod;
2782 * Build the hash node and hash join node.
2784 hash_plan = make_hash(inner_plan,
2790 join_plan = make_hashjoin(tlist,
2796 best_path->jpath.jointype);
2798 copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
2804 /*****************************************************************************
2806 * SUPPORTING ROUTINES
2808 *****************************************************************************/
2811 * replace_nestloop_params
2812 * Replace outer-relation Vars and PlaceHolderVars in the given expression
2813 * with nestloop Params
2815 * All Vars and PlaceHolderVars belonging to the relation(s) identified by
2816 * root->curOuterRels are replaced by Params, and entries are added to
2817 * root->curOuterParams if not already present.
2820 replace_nestloop_params(PlannerInfo *root, Node *expr)
2822 /* No setup needed for tree walk, so away we go */
2823 return replace_nestloop_params_mutator(expr, root);
2827 replace_nestloop_params_mutator(Node *node, PlannerInfo *root)
2833 Var *var = (Var *) node;
2838 /* Upper-level Vars should be long gone at this point */
2839 Assert(var->varlevelsup == 0);
2840 /* If not to be replaced, we can just return the Var unmodified */
2841 if (!bms_is_member(var->varno, root->curOuterRels))
2843 /* Create a Param representing the Var */
2844 param = assign_nestloop_param_var(root, var);
2845 /* Is this param already listed in root->curOuterParams? */
2846 foreach(lc, root->curOuterParams)
2848 nlp = (NestLoopParam *) lfirst(lc);
2849 if (nlp->paramno == param->paramid)
2851 Assert(equal(var, nlp->paramval));
2852 /* Present, so we can just return the Param */
2853 return (Node *) param;
2857 nlp = makeNode(NestLoopParam);
2858 nlp->paramno = param->paramid;
2859 nlp->paramval = var;
2860 root->curOuterParams = lappend(root->curOuterParams, nlp);
2861 /* And return the replacement Param */
2862 return (Node *) param;
2864 if (IsA(node, PlaceHolderVar))
2866 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2871 /* Upper-level PlaceHolderVars should be long gone at this point */
2872 Assert(phv->phlevelsup == 0);
2875 * Check whether we need to replace the PHV. We use bms_overlap as a
2876 * cheap/quick test to see if the PHV might be evaluated in the outer
2877 * rels, and then grab its PlaceHolderInfo to tell for sure.
2879 if (!bms_overlap(phv->phrels, root->curOuterRels) ||
2880 !bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
2881 root->curOuterRels))
2884 * We can't replace the whole PHV, but we might still need to
2885 * replace Vars or PHVs within its expression, in case it ends up
2886 * actually getting evaluated here. (It might get evaluated in
2887 * this plan node, or some child node; in the latter case we don't
2888 * really need to process the expression here, but we haven't got
2889 * enough info to tell if that's the case.) Flat-copy the PHV
2890 * node and then recurse on its expression.
2892 * Note that after doing this, we might have different
2893 * representations of the contents of the same PHV in different
2894 * parts of the plan tree. This is OK because equal() will just
2895 * match on phid/phlevelsup, so setrefs.c will still recognize an
2896 * upper-level reference to a lower-level copy of the same PHV.
2898 PlaceHolderVar *newphv = makeNode(PlaceHolderVar);
2900 memcpy(newphv, phv, sizeof(PlaceHolderVar));
2901 newphv->phexpr = (Expr *)
2902 replace_nestloop_params_mutator((Node *) phv->phexpr,
2904 return (Node *) newphv;
2906 /* Create a Param representing the PlaceHolderVar */
2907 param = assign_nestloop_param_placeholdervar(root, phv);
2908 /* Is this param already listed in root->curOuterParams? */
2909 foreach(lc, root->curOuterParams)
2911 nlp = (NestLoopParam *) lfirst(lc);
2912 if (nlp->paramno == param->paramid)
2914 Assert(equal(phv, nlp->paramval));
2915 /* Present, so we can just return the Param */
2916 return (Node *) param;
2920 nlp = makeNode(NestLoopParam);
2921 nlp->paramno = param->paramid;
2922 nlp->paramval = (Var *) phv;
2923 root->curOuterParams = lappend(root->curOuterParams, nlp);
2924 /* And return the replacement Param */
2925 return (Node *) param;
2927 return expression_tree_mutator(node,
2928 replace_nestloop_params_mutator,
2933 * process_subquery_nestloop_params
2934 * Handle params of a parameterized subquery that need to be fed
2935 * from an outer nestloop.
2937 * Currently, that would be *all* params that a subquery in FROM has demanded
2938 * from the current query level, since they must be LATERAL references.
2940 * The subplan's references to the outer variables are already represented
2941 * as PARAM_EXEC Params, so we need not modify the subplan here. What we
2942 * do need to do is add entries to root->curOuterParams to signal the parent
2943 * nestloop plan node that it must provide these values.
2946 process_subquery_nestloop_params(PlannerInfo *root, List *subplan_params)
2950 foreach(ppl, subplan_params)
2952 PlannerParamItem *pitem = (PlannerParamItem *) lfirst(ppl);
2954 if (IsA(pitem->item, Var))
2956 Var *var = (Var *) pitem->item;
2960 /* If not from a nestloop outer rel, complain */
2961 if (!bms_is_member(var->varno, root->curOuterRels))
2962 elog(ERROR, "non-LATERAL parameter required by subquery");
2963 /* Is this param already listed in root->curOuterParams? */
2964 foreach(lc, root->curOuterParams)
2966 nlp = (NestLoopParam *) lfirst(lc);
2967 if (nlp->paramno == pitem->paramId)
2969 Assert(equal(var, nlp->paramval));
2970 /* Present, so nothing to do */
2977 nlp = makeNode(NestLoopParam);
2978 nlp->paramno = pitem->paramId;
2979 nlp->paramval = copyObject(var);
2980 root->curOuterParams = lappend(root->curOuterParams, nlp);
2983 else if (IsA(pitem->item, PlaceHolderVar))
2985 PlaceHolderVar *phv = (PlaceHolderVar *) pitem->item;
2989 /* If not from a nestloop outer rel, complain */
2990 if (!bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
2991 root->curOuterRels))
2992 elog(ERROR, "non-LATERAL parameter required by subquery");
2993 /* Is this param already listed in root->curOuterParams? */
2994 foreach(lc, root->curOuterParams)
2996 nlp = (NestLoopParam *) lfirst(lc);
2997 if (nlp->paramno == pitem->paramId)
2999 Assert(equal(phv, nlp->paramval));
3000 /* Present, so nothing to do */
3007 nlp = makeNode(NestLoopParam);
3008 nlp->paramno = pitem->paramId;
3009 nlp->paramval = copyObject(phv);
3010 root->curOuterParams = lappend(root->curOuterParams, nlp);
3014 elog(ERROR, "unexpected type of subquery parameter");
3019 * fix_indexqual_references
3020 * Adjust indexqual clauses to the form the executor's indexqual
3023 * We have four tasks here:
3024 * * Remove RestrictInfo nodes from the input clauses.
3025 * * Replace any outer-relation Var or PHV nodes with nestloop Params.
3026 * (XXX eventually, that responsibility should go elsewhere?)
3027 * * Index keys must be represented by Var nodes with varattno set to the
3028 * index's attribute number, not the attribute number in the original rel.
3029 * * If the index key is on the right, commute the clause to put it on the
3032 * The result is a modified copy of the path's indexquals list --- the
3033 * original is not changed. Note also that the copy shares no substructure
3034 * with the original; this is needed in case there is a subplan in it (we need
3035 * two separate copies of the subplan tree, or things will go awry).
3038 fix_indexqual_references(PlannerInfo *root, IndexPath *index_path)
3040 IndexOptInfo *index = index_path->indexinfo;
3041 List *fixed_indexquals;
3045 fixed_indexquals = NIL;
3047 forboth(lcc, index_path->indexquals, lci, index_path->indexqualcols)
3049 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcc);
3050 int indexcol = lfirst_int(lci);
3053 Assert(IsA(rinfo, RestrictInfo));
3056 * Replace any outer-relation variables with nestloop params.
3058 * This also makes a copy of the clause, so it's safe to modify it
3061 clause = replace_nestloop_params(root, (Node *) rinfo->clause);
3063 if (IsA(clause, OpExpr))
3065 OpExpr *op = (OpExpr *) clause;
3067 if (list_length(op->args) != 2)
3068 elog(ERROR, "indexqual clause is not binary opclause");
3071 * Check to see if the indexkey is on the right; if so, commute
3072 * the clause. The indexkey should be the side that refers to
3073 * (only) the base relation.
3075 if (!bms_equal(rinfo->left_relids, index->rel->relids))
3079 * Now replace the indexkey expression with an index Var.
3081 linitial(op->args) = fix_indexqual_operand(linitial(op->args),
3085 else if (IsA(clause, RowCompareExpr))
3087 RowCompareExpr *rc = (RowCompareExpr *) clause;
3095 * Re-discover which index columns are used in the rowcompare.
3097 newrc = adjust_rowcompare_for_index(rc,
3104 * Trouble if adjust_rowcompare_for_index thought the
3105 * RowCompareExpr didn't match the index as-is; the clause should
3106 * have gone through that routine already.
3108 if (newrc != (Expr *) rc)
3109 elog(ERROR, "inconsistent results from adjust_rowcompare_for_index");
3112 * Check to see if the indexkey is on the right; if so, commute
3116 CommuteRowCompareExpr(rc);
3119 * Now replace the indexkey expressions with index Vars.
3121 Assert(list_length(rc->largs) == list_length(indexcolnos));
3122 forboth(lca, rc->largs, lcai, indexcolnos)
3124 lfirst(lca) = fix_indexqual_operand(lfirst(lca),
3129 else if (IsA(clause, ScalarArrayOpExpr))
3131 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
3133 /* Never need to commute... */
3135 /* Replace the indexkey expression with an index Var. */
3136 linitial(saop->args) = fix_indexqual_operand(linitial(saop->args),
3140 else if (IsA(clause, NullTest))
3142 NullTest *nt = (NullTest *) clause;
3144 /* Replace the indexkey expression with an index Var. */
3145 nt->arg = (Expr *) fix_indexqual_operand((Node *) nt->arg,
3150 elog(ERROR, "unsupported indexqual type: %d",
3151 (int) nodeTag(clause));
3153 fixed_indexquals = lappend(fixed_indexquals, clause);
3156 return fixed_indexquals;
3160 * fix_indexorderby_references
3161 * Adjust indexorderby clauses to the form the executor's index
3164 * This is a simplified version of fix_indexqual_references. The input does
3165 * not have RestrictInfo nodes, and we assume that indxpath.c already
3166 * commuted the clauses to put the index keys on the left. Also, we don't
3167 * bother to support any cases except simple OpExprs, since nothing else
3168 * is allowed for ordering operators.
3171 fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path)
3173 IndexOptInfo *index = index_path->indexinfo;
3174 List *fixed_indexorderbys;
3178 fixed_indexorderbys = NIL;
3180 forboth(lcc, index_path->indexorderbys, lci, index_path->indexorderbycols)
3182 Node *clause = (Node *) lfirst(lcc);
3183 int indexcol = lfirst_int(lci);
3186 * Replace any outer-relation variables with nestloop params.
3188 * This also makes a copy of the clause, so it's safe to modify it
3191 clause = replace_nestloop_params(root, clause);
3193 if (IsA(clause, OpExpr))
3195 OpExpr *op = (OpExpr *) clause;
3197 if (list_length(op->args) != 2)
3198 elog(ERROR, "indexorderby clause is not binary opclause");
3201 * Now replace the indexkey expression with an index Var.
3203 linitial(op->args) = fix_indexqual_operand(linitial(op->args),
3208 elog(ERROR, "unsupported indexorderby type: %d",
3209 (int) nodeTag(clause));
3211 fixed_indexorderbys = lappend(fixed_indexorderbys, clause);
3214 return fixed_indexorderbys;
3218 * fix_indexqual_operand
3219 * Convert an indexqual expression to a Var referencing the index column.
3221 * We represent index keys by Var nodes having varno == INDEX_VAR and varattno
3222 * equal to the index's attribute number (index column position).
3224 * Most of the code here is just for sanity cross-checking that the given
3225 * expression actually matches the index column it's claimed to.
3228 fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol)
3232 ListCell *indexpr_item;
3235 * Remove any binary-compatible relabeling of the indexkey
3237 if (IsA(node, RelabelType))
3238 node = (Node *) ((RelabelType *) node)->arg;
3240 Assert(indexcol >= 0 && indexcol < index->ncolumns);
3242 if (index->indexkeys[indexcol] != 0)
3244 /* It's a simple index column */
3245 if (IsA(node, Var) &&
3246 ((Var *) node)->varno == index->rel->relid &&
3247 ((Var *) node)->varattno == index->indexkeys[indexcol])
3249 result = (Var *) copyObject(node);
3250 result->varno = INDEX_VAR;
3251 result->varattno = indexcol + 1;
3252 return (Node *) result;
3255 elog(ERROR, "index key does not match expected index column");
3258 /* It's an index expression, so find and cross-check the expression */
3259 indexpr_item = list_head(index->indexprs);
3260 for (pos = 0; pos < index->ncolumns; pos++)
3262 if (index->indexkeys[pos] == 0)
3264 if (indexpr_item == NULL)
3265 elog(ERROR, "too few entries in indexprs list");
3266 if (pos == indexcol)
3270 indexkey = (Node *) lfirst(indexpr_item);
3271 if (indexkey && IsA(indexkey, RelabelType))
3272 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
3273 if (equal(node, indexkey))
3275 result = makeVar(INDEX_VAR, indexcol + 1,
3276 exprType(lfirst(indexpr_item)), -1,
3277 exprCollation(lfirst(indexpr_item)),
3279 return (Node *) result;
3282 elog(ERROR, "index key does not match expected index column");
3284 indexpr_item = lnext(indexpr_item);
3289 elog(ERROR, "index key does not match expected index column");
3290 return NULL; /* keep compiler quiet */
3294 * get_switched_clauses
3295 * Given a list of merge or hash joinclauses (as RestrictInfo nodes),
3296 * extract the bare clauses, and rearrange the elements within the
3297 * clauses, if needed, so the outer join variable is on the left and
3298 * the inner is on the right. The original clause data structure is not
3299 * touched; a modified list is returned. We do, however, set the transient
3300 * outer_is_left field in each RestrictInfo to show which side was which.
3303 get_switched_clauses(List *clauses, Relids outerrelids)
3310 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
3311 OpExpr *clause = (OpExpr *) restrictinfo->clause;
3313 Assert(is_opclause(clause));
3314 if (bms_is_subset(restrictinfo->right_relids, outerrelids))
3317 * Duplicate just enough of the structure to allow commuting the
3318 * clause without changing the original list. Could use
3319 * copyObject, but a complete deep copy is overkill.
3321 OpExpr *temp = makeNode(OpExpr);
3323 temp->opno = clause->opno;
3324 temp->opfuncid = InvalidOid;
3325 temp->opresulttype = clause->opresulttype;
3326 temp->opretset = clause->opretset;
3327 temp->opcollid = clause->opcollid;
3328 temp->inputcollid = clause->inputcollid;
3329 temp->args = list_copy(clause->args);
3330 temp->location = clause->location;
3331 /* Commute it --- note this modifies the temp node in-place. */
3332 CommuteOpExpr(temp);
3333 t_list = lappend(t_list, temp);
3334 restrictinfo->outer_is_left = false;
3338 Assert(bms_is_subset(restrictinfo->left_relids, outerrelids));
3339 t_list = lappend(t_list, clause);
3340 restrictinfo->outer_is_left = true;
3347 * order_qual_clauses
3348 * Given a list of qual clauses that will all be evaluated at the same
3349 * plan node, sort the list into the order we want to check the quals
3352 * Ideally the order should be driven by a combination of execution cost and
3353 * selectivity, but it's not immediately clear how to account for both,
3354 * and given the uncertainty of the estimates the reliability of the decisions
3355 * would be doubtful anyway. So we just order by estimated per-tuple cost,
3356 * being careful not to change the order when (as is often the case) the
3357 * estimates are identical.
3359 * Although this will work on either bare clauses or RestrictInfos, it's
3360 * much faster to apply it to RestrictInfos, since it can re-use cost
3361 * information that is cached in RestrictInfos.
3363 * Note: some callers pass lists that contain entries that will later be
3364 * removed; this is the easiest way to let this routine see RestrictInfos
3365 * instead of bare clauses. It's OK because we only sort by cost, but
3366 * a cost/selectivity combination would likely do the wrong thing.
3369 order_qual_clauses(PlannerInfo *root, List *clauses)
3376 int nitems = list_length(clauses);
3382 /* No need to work hard for 0 or 1 clause */
3387 * Collect the items and costs into an array. This is to avoid repeated
3388 * cost_qual_eval work if the inputs aren't RestrictInfos.
3390 items = (QualItem *) palloc(nitems * sizeof(QualItem));
3392 foreach(lc, clauses)
3394 Node *clause = (Node *) lfirst(lc);
3397 cost_qual_eval_node(&qcost, clause, root);
3398 items[i].clause = clause;
3399 items[i].cost = qcost.per_tuple;
3404 * Sort. We don't use qsort() because it's not guaranteed stable for
3405 * equal keys. The expected number of entries is small enough that a
3406 * simple insertion sort should be good enough.
3408 for (i = 1; i < nitems; i++)
3410 QualItem newitem = items[i];
3413 /* insert newitem into the already-sorted subarray */
3414 for (j = i; j > 0; j--)
3416 if (newitem.cost >= items[j - 1].cost)
3418 items[j] = items[j - 1];
3423 /* Convert back to a list */
3425 for (i = 0; i < nitems; i++)
3426 result = lappend(result, items[i].clause);
3432 * Copy cost and size info from a Path node to the Plan node created from it.
3433 * The executor usually won't use this info, but it's needed by EXPLAIN.
3435 * Also copy the parallel-aware flag, which the executor will use.
3438 copy_generic_path_info(Plan *dest, Path *src)
3442 dest->startup_cost = src->startup_cost;
3443 dest->total_cost = src->total_cost;
3444 dest->plan_rows = src->rows;
3445 dest->plan_width = src->parent->width;
3446 dest->parallel_aware = src->parallel_aware;
3450 dest->startup_cost = 0;
3451 dest->total_cost = 0;
3452 dest->plan_rows = 0;
3453 dest->plan_width = 0;
3454 dest->parallel_aware = false;
3459 * Copy cost and size info from a lower plan node to an inserted node.
3460 * (Most callers alter the info after copying it.)
3463 copy_plan_costsize(Plan *dest, Plan *src)
3467 dest->startup_cost = src->startup_cost;
3468 dest->total_cost = src->total_cost;
3469 dest->plan_rows = src->plan_rows;
3470 dest->plan_width = src->plan_width;
3474 dest->startup_cost = 0;
3475 dest->total_cost = 0;
3476 dest->plan_rows = 0;
3477 dest->plan_width = 0;
3482 /*****************************************************************************
3484 * PLAN NODE BUILDING ROUTINES
3486 * Some of these are exported because they are called to build plan nodes
3487 * in contexts where we're not deriving the plan node from a path node.
3489 *****************************************************************************/
3492 make_seqscan(List *qptlist,
3496 SeqScan *node = makeNode(SeqScan);
3497 Plan *plan = &node->plan;
3499 /* cost should be inserted by caller */
3500 plan->targetlist = qptlist;
3501 plan->qual = qpqual;
3502 plan->lefttree = NULL;
3503 plan->righttree = NULL;
3504 node->scanrelid = scanrelid;
3510 make_samplescan(List *qptlist,
3513 TableSampleClause *tsc)
3515 SampleScan *node = makeNode(SampleScan);
3516 Plan *plan = &node->scan.plan;
3518 /* cost should be inserted by caller */
3519 plan->targetlist = qptlist;
3520 plan->qual = qpqual;
3521 plan->lefttree = NULL;
3522 plan->righttree = NULL;
3523 node->scan.scanrelid = scanrelid;
3524 node->tablesample = tsc;
3530 make_indexscan(List *qptlist,
3535 List *indexqualorig,
3537 List *indexorderbyorig,
3538 List *indexorderbyops,
3539 ScanDirection indexscandir)
3541 IndexScan *node = makeNode(IndexScan);
3542 Plan *plan = &node->scan.plan;
3544 /* cost should be inserted by caller */
3545 plan->targetlist = qptlist;
3546 plan->qual = qpqual;
3547 plan->lefttree = NULL;
3548 plan->righttree = NULL;
3549 node->scan.scanrelid = scanrelid;
3550 node->indexid = indexid;
3551 node->indexqual = indexqual;
3552 node->indexqualorig = indexqualorig;
3553 node->indexorderby = indexorderby;
3554 node->indexorderbyorig = indexorderbyorig;
3555 node->indexorderbyops = indexorderbyops;
3556 node->indexorderdir = indexscandir;
3561 static IndexOnlyScan *
3562 make_indexonlyscan(List *qptlist,
3569 ScanDirection indexscandir)
3571 IndexOnlyScan *node = makeNode(IndexOnlyScan);
3572 Plan *plan = &node->scan.plan;
3574 /* cost should be inserted by caller */
3575 plan->targetlist = qptlist;
3576 plan->qual = qpqual;
3577 plan->lefttree = NULL;
3578 plan->righttree = NULL;
3579 node->scan.scanrelid = scanrelid;
3580 node->indexid = indexid;
3581 node->indexqual = indexqual;
3582 node->indexorderby = indexorderby;
3583 node->indextlist = indextlist;
3584 node->indexorderdir = indexscandir;
3589 static BitmapIndexScan *
3590 make_bitmap_indexscan(Index scanrelid,
3593 List *indexqualorig)
3595 BitmapIndexScan *node = makeNode(BitmapIndexScan);
3596 Plan *plan = &node->scan.plan;
3598 /* cost should be inserted by caller */
3599 plan->targetlist = NIL; /* not used */
3600 plan->qual = NIL; /* not used */
3601 plan->lefttree = NULL;
3602 plan->righttree = NULL;
3603 node->scan.scanrelid = scanrelid;
3604 node->indexid = indexid;
3605 node->indexqual = indexqual;
3606 node->indexqualorig = indexqualorig;
3611 static BitmapHeapScan *
3612 make_bitmap_heapscan(List *qptlist,
3615 List *bitmapqualorig,
3618 BitmapHeapScan *node = makeNode(BitmapHeapScan);
3619 Plan *plan = &node->scan.plan;
3621 /* cost should be inserted by caller */
3622 plan->targetlist = qptlist;
3623 plan->qual = qpqual;
3624 plan->lefttree = lefttree;
3625 plan->righttree = NULL;
3626 node->scan.scanrelid = scanrelid;
3627 node->bitmapqualorig = bitmapqualorig;
3633 make_tidscan(List *qptlist,
3638 TidScan *node = makeNode(TidScan);
3639 Plan *plan = &node->scan.plan;
3641 /* cost should be inserted by caller */
3642 plan->targetlist = qptlist;
3643 plan->qual = qpqual;
3644 plan->lefttree = NULL;
3645 plan->righttree = NULL;
3646 node->scan.scanrelid = scanrelid;
3647 node->tidquals = tidquals;
3653 make_subqueryscan(List *qptlist,
3658 SubqueryScan *node = makeNode(SubqueryScan);
3659 Plan *plan = &node->scan.plan;
3662 * Cost is figured here for the convenience of prepunion.c. Note this is
3663 * only correct for the case where qpqual is empty; otherwise caller
3664 * should overwrite cost with a better estimate.
3666 copy_plan_costsize(plan, subplan);
3667 plan->total_cost += cpu_tuple_cost * subplan->plan_rows;
3669 plan->targetlist = qptlist;
3670 plan->qual = qpqual;
3671 plan->lefttree = NULL;
3672 plan->righttree = NULL;
3673 node->scan.scanrelid = scanrelid;
3674 node->subplan = subplan;
3679 static FunctionScan *
3680 make_functionscan(List *qptlist,
3684 bool funcordinality)
3686 FunctionScan *node = makeNode(FunctionScan);
3687 Plan *plan = &node->scan.plan;
3689 /* cost should be inserted by caller */
3690 plan->targetlist = qptlist;
3691 plan->qual = qpqual;
3692 plan->lefttree = NULL;
3693 plan->righttree = NULL;
3694 node->scan.scanrelid = scanrelid;
3695 node->functions = functions;
3696 node->funcordinality = funcordinality;
3702 make_valuesscan(List *qptlist,
3707 ValuesScan *node = makeNode(ValuesScan);
3708 Plan *plan = &node->scan.plan;
3710 /* cost should be inserted by caller */
3711 plan->targetlist = qptlist;
3712 plan->qual = qpqual;
3713 plan->lefttree = NULL;
3714 plan->righttree = NULL;
3715 node->scan.scanrelid = scanrelid;
3716 node->values_lists = values_lists;
3722 make_ctescan(List *qptlist,
3728 CteScan *node = makeNode(CteScan);
3729 Plan *plan = &node->scan.plan;
3731 /* cost should be inserted by caller */
3732 plan->targetlist = qptlist;
3733 plan->qual = qpqual;
3734 plan->lefttree = NULL;
3735 plan->righttree = NULL;
3736 node->scan.scanrelid = scanrelid;
3737 node->ctePlanId = ctePlanId;
3738 node->cteParam = cteParam;
3743 static WorkTableScan *
3744 make_worktablescan(List *qptlist,
3749 WorkTableScan *node = makeNode(WorkTableScan);
3750 Plan *plan = &node->scan.plan;
3752 /* cost should be inserted by caller */
3753 plan->targetlist = qptlist;
3754 plan->qual = qpqual;
3755 plan->lefttree = NULL;
3756 plan->righttree = NULL;
3757 node->scan.scanrelid = scanrelid;
3758 node->wtParam = wtParam;
3764 make_foreignscan(List *qptlist,
3769 List *fdw_scan_tlist,
3770 List *fdw_recheck_quals,
3773 ForeignScan *node = makeNode(ForeignScan);
3774 Plan *plan = &node->scan.plan;
3776 /* cost will be filled in by create_foreignscan_plan */
3777 plan->targetlist = qptlist;
3778 plan->qual = qpqual;
3779 plan->lefttree = outer_plan;
3780 plan->righttree = NULL;
3781 node->scan.scanrelid = scanrelid;
3782 /* fs_server will be filled in by create_foreignscan_plan */
3783 node->fs_server = InvalidOid;
3784 node->fdw_exprs = fdw_exprs;
3785 node->fdw_private = fdw_private;
3786 node->fdw_scan_tlist = fdw_scan_tlist;
3787 node->fdw_recheck_quals = fdw_recheck_quals;
3788 /* fs_relids will be filled in by create_foreignscan_plan */
3789 node->fs_relids = NULL;
3790 /* fsSystemCol will be filled in by create_foreignscan_plan */
3791 node->fsSystemCol = false;
3797 make_append(List *appendplans, List *tlist)
3799 Append *node = makeNode(Append);
3800 Plan *plan = &node->plan;
3805 * Compute cost as sum of subplan costs. We charge nothing extra for the
3806 * Append itself, which perhaps is too optimistic, but since it doesn't do
3807 * any selection or projection, it is a pretty cheap node.
3809 * If you change this, see also create_append_path(). Also, the size
3810 * calculations should match set_append_rel_pathlist(). It'd be better
3811 * not to duplicate all this logic, but some callers of this function
3812 * aren't working from an appendrel or AppendPath, so there's noplace to
3813 * copy the data from.
3815 plan->startup_cost = 0;
3816 plan->total_cost = 0;
3817 plan->plan_rows = 0;
3819 foreach(subnode, appendplans)
3821 Plan *subplan = (Plan *) lfirst(subnode);
3823 if (subnode == list_head(appendplans)) /* first node? */
3824 plan->startup_cost = subplan->startup_cost;
3825 plan->total_cost += subplan->total_cost;
3826 plan->plan_rows += subplan->plan_rows;
3827 total_size += subplan->plan_width * subplan->plan_rows;
3829 if (plan->plan_rows > 0)
3830 plan->plan_width = rint(total_size / plan->plan_rows);
3832 plan->plan_width = 0;
3834 plan->targetlist = tlist;
3836 plan->lefttree = NULL;
3837 plan->righttree = NULL;
3838 node->appendplans = appendplans;
3844 make_recursive_union(List *tlist,
3851 RecursiveUnion *node = makeNode(RecursiveUnion);
3852 Plan *plan = &node->plan;
3853 int numCols = list_length(distinctList);
3855 cost_recursive_union(plan, lefttree, righttree);
3857 plan->targetlist = tlist;
3859 plan->lefttree = lefttree;
3860 plan->righttree = righttree;
3861 node->wtParam = wtParam;
3864 * convert SortGroupClause list into arrays of attr indexes and equality
3865 * operators, as wanted by executor
3867 node->numCols = numCols;
3871 AttrNumber *dupColIdx;
3875 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
3876 dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
3878 foreach(slitem, distinctList)
3880 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
3881 TargetEntry *tle = get_sortgroupclause_tle(sortcl,
3884 dupColIdx[keyno] = tle->resno;
3885 dupOperators[keyno] = sortcl->eqop;
3886 Assert(OidIsValid(dupOperators[keyno]));
3889 node->dupColIdx = dupColIdx;
3890 node->dupOperators = dupOperators;
3892 node->numGroups = numGroups;
3898 make_bitmap_and(List *bitmapplans)
3900 BitmapAnd *node = makeNode(BitmapAnd);
3901 Plan *plan = &node->plan;
3903 /* cost should be inserted by caller */
3904 plan->targetlist = NIL;
3906 plan->lefttree = NULL;
3907 plan->righttree = NULL;
3908 node->bitmapplans = bitmapplans;
3914 make_bitmap_or(List *bitmapplans)
3916 BitmapOr *node = makeNode(BitmapOr);
3917 Plan *plan = &node->plan;
3919 /* cost should be inserted by caller */
3920 plan->targetlist = NIL;
3922 plan->lefttree = NULL;
3923 plan->righttree = NULL;
3924 node->bitmapplans = bitmapplans;
3930 make_nestloop(List *tlist,
3938 NestLoop *node = makeNode(NestLoop);
3939 Plan *plan = &node->join.plan;
3941 /* cost should be inserted by caller */
3942 plan->targetlist = tlist;
3943 plan->qual = otherclauses;
3944 plan->lefttree = lefttree;
3945 plan->righttree = righttree;
3946 node->join.jointype = jointype;
3947 node->join.joinqual = joinclauses;
3948 node->nestParams = nestParams;
3954 make_hashjoin(List *tlist,
3962 HashJoin *node = makeNode(HashJoin);
3963 Plan *plan = &node->join.plan;
3965 /* cost should be inserted by caller */
3966 plan->targetlist = tlist;
3967 plan->qual = otherclauses;
3968 plan->lefttree = lefttree;
3969 plan->righttree = righttree;
3970 node->hashclauses = hashclauses;
3971 node->join.jointype = jointype;
3972 node->join.joinqual = joinclauses;
3978 make_hash(Plan *lefttree,
3980 AttrNumber skewColumn,
3983 int32 skewColTypmod)
3985 Hash *node = makeNode(Hash);
3986 Plan *plan = &node->plan;
3988 copy_plan_costsize(plan, lefttree);
3991 * For plausibility, make startup & total costs equal total cost of input
3992 * plan; this only affects EXPLAIN display not decisions.
3994 plan->startup_cost = plan->total_cost;
3995 plan->targetlist = lefttree->targetlist;
3997 plan->lefttree = lefttree;
3998 plan->righttree = NULL;
4000 node->skewTable = skewTable;
4001 node->skewColumn = skewColumn;
4002 node->skewInherit = skewInherit;
4003 node->skewColType = skewColType;
4004 node->skewColTypmod = skewColTypmod;
4010 make_mergejoin(List *tlist,
4015 Oid *mergecollations,
4016 int *mergestrategies,
4017 bool *mergenullsfirst,
4022 MergeJoin *node = makeNode(MergeJoin);
4023 Plan *plan = &node->join.plan;
4025 /* cost should be inserted by caller */
4026 plan->targetlist = tlist;
4027 plan->qual = otherclauses;
4028 plan->lefttree = lefttree;
4029 plan->righttree = righttree;
4030 node->mergeclauses = mergeclauses;
4031 node->mergeFamilies = mergefamilies;
4032 node->mergeCollations = mergecollations;
4033 node->mergeStrategies = mergestrategies;
4034 node->mergeNullsFirst = mergenullsfirst;
4035 node->join.jointype = jointype;
4036 node->join.joinqual = joinclauses;
4042 * make_sort --- basic routine to build a Sort plan node
4044 * Caller must have built the sortColIdx, sortOperators, collations, and
4045 * nullsFirst arrays already.
4046 * limit_tuples is as for cost_sort (in particular, pass -1 if no limit)
4049 make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
4050 AttrNumber *sortColIdx, Oid *sortOperators,
4051 Oid *collations, bool *nullsFirst,
4052 double limit_tuples)
4054 Sort *node = makeNode(Sort);
4055 Plan *plan = &node->plan;
4056 Path sort_path; /* dummy for result of cost_sort */
4058 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4059 cost_sort(&sort_path, root, NIL,
4060 lefttree->total_cost,
4061 lefttree->plan_rows,
4062 lefttree->plan_width,
4066 plan->startup_cost = sort_path.startup_cost;
4067 plan->total_cost = sort_path.total_cost;
4068 plan->targetlist = lefttree->targetlist;
4070 plan->lefttree = lefttree;
4071 plan->righttree = NULL;
4072 node->numCols = numCols;
4073 node->sortColIdx = sortColIdx;
4074 node->sortOperators = sortOperators;
4075 node->collations = collations;
4076 node->nullsFirst = nullsFirst;
4082 * prepare_sort_from_pathkeys
4083 * Prepare to sort according to given pathkeys
4085 * This is used to set up for both Sort and MergeAppend nodes. It calculates
4086 * the executor's representation of the sort key information, and adjusts the
4087 * plan targetlist if needed to add resjunk sort columns.
4090 * 'lefttree' is the plan node which yields input tuples
4091 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
4092 * 'relids' identifies the child relation being sorted, if any
4093 * 'reqColIdx' is NULL or an array of required sort key column numbers
4094 * 'adjust_tlist_in_place' is TRUE if lefttree must be modified in-place
4096 * We must convert the pathkey information into arrays of sort key column
4097 * numbers, sort operator OIDs, collation OIDs, and nulls-first flags,
4098 * which is the representation the executor wants. These are returned into
4099 * the output parameters *p_numsortkeys etc.
4101 * When looking for matches to an EquivalenceClass's members, we will only
4102 * consider child EC members if they match 'relids'. This protects against
4103 * possible incorrect matches to child expressions that contain no Vars.
4105 * If reqColIdx isn't NULL then it contains sort key column numbers that
4106 * we should match. This is used when making child plans for a MergeAppend;
4107 * it's an error if we can't match the columns.
4109 * If the pathkeys include expressions that aren't simple Vars, we will
4110 * usually need to add resjunk items to the input plan's targetlist to
4111 * compute these expressions, since the Sort/MergeAppend node itself won't
4112 * do any such calculations. If the input plan type isn't one that can do
4113 * projections, this means adding a Result node just to do the projection.
4114 * However, the caller can pass adjust_tlist_in_place = TRUE to force the
4115 * lefttree tlist to be modified in-place regardless of whether the node type
4116 * can project --- we use this for fixing the tlist of MergeAppend itself.
4118 * Returns the node which is to be the input to the Sort (either lefttree,
4119 * or a Result stacked atop lefttree).
4122 prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
4124 const AttrNumber *reqColIdx,
4125 bool adjust_tlist_in_place,
4127 AttrNumber **p_sortColIdx,
4128 Oid **p_sortOperators,
4130 bool **p_nullsFirst)
4132 List *tlist = lefttree->targetlist;
4135 AttrNumber *sortColIdx;
4141 * We will need at most list_length(pathkeys) sort columns; possibly less
4143 numsortkeys = list_length(pathkeys);
4144 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
4145 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
4146 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
4147 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
4151 foreach(i, pathkeys)
4153 PathKey *pathkey = (PathKey *) lfirst(i);
4154 EquivalenceClass *ec = pathkey->pk_eclass;
4155 EquivalenceMember *em;
4156 TargetEntry *tle = NULL;
4157 Oid pk_datatype = InvalidOid;
4161 if (ec->ec_has_volatile)
4164 * If the pathkey's EquivalenceClass is volatile, then it must
4165 * have come from an ORDER BY clause, and we have to match it to
4166 * that same targetlist entry.
4168 if (ec->ec_sortref == 0) /* can't happen */
4169 elog(ERROR, "volatile EquivalenceClass has no sortref");
4170 tle = get_sortgroupref_tle(ec->ec_sortref, tlist);
4172 Assert(list_length(ec->ec_members) == 1);
4173 pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
4175 else if (reqColIdx != NULL)
4178 * If we are given a sort column number to match, only consider
4179 * the single TLE at that position. It's possible that there is
4180 * no such TLE, in which case fall through and generate a resjunk
4181 * targetentry (we assume this must have happened in the parent
4182 * plan as well). If there is a TLE but it doesn't match the
4183 * pathkey's EC, we do the same, which is probably the wrong thing
4184 * but we'll leave it to caller to complain about the mismatch.
4186 tle = get_tle_by_resno(tlist, reqColIdx[numsortkeys]);
4189 em = find_ec_member_for_tle(ec, tle, relids);
4192 /* found expr at right place in tlist */
4193 pk_datatype = em->em_datatype;
4202 * Otherwise, we can sort by any non-constant expression listed in
4203 * the pathkey's EquivalenceClass. For now, we take the first
4204 * tlist item found in the EC. If there's no match, we'll generate
4205 * a resjunk entry using the first EC member that is an expression
4206 * in the input's vars. (The non-const restriction only matters
4207 * if the EC is below_outer_join; but if it isn't, it won't
4208 * contain consts anyway, else we'd have discarded the pathkey as
4211 * XXX if we have a choice, is there any way of figuring out which
4212 * might be cheapest to execute? (For example, int4lt is likely
4213 * much cheaper to execute than numericlt, but both might appear
4214 * in the same equivalence class...) Not clear that we ever will
4215 * have an interesting choice in practice, so it may not matter.
4219 tle = (TargetEntry *) lfirst(j);
4220 em = find_ec_member_for_tle(ec, tle, relids);
4223 /* found expr already in tlist */
4224 pk_datatype = em->em_datatype;
4234 * No matching tlist item; look for a computable expression. Note
4235 * that we treat Aggrefs as if they were variables; this is
4236 * necessary when attempting to sort the output from an Agg node
4237 * for use in a WindowFunc (since grouping_planner will have
4238 * treated the Aggrefs as variables, too).
4240 Expr *sortexpr = NULL;
4242 foreach(j, ec->ec_members)
4244 EquivalenceMember *em = (EquivalenceMember *) lfirst(j);
4249 * We shouldn't be trying to sort by an equivalence class that
4250 * contains a constant, so no need to consider such cases any
4253 if (em->em_is_const)
4257 * Ignore child members unless they match the rel being
4260 if (em->em_is_child &&
4261 !bms_equal(em->em_relids, relids))
4264 sortexpr = em->em_expr;
4265 exprvars = pull_var_clause((Node *) sortexpr,
4266 PVC_INCLUDE_AGGREGATES,
4267 PVC_INCLUDE_PLACEHOLDERS);
4268 foreach(k, exprvars)
4270 if (!tlist_member_ignore_relabel(lfirst(k), tlist))
4273 list_free(exprvars);
4276 pk_datatype = em->em_datatype;
4277 break; /* found usable expression */
4281 elog(ERROR, "could not find pathkey item to sort");
4284 * Do we need to insert a Result node?
4286 if (!adjust_tlist_in_place &&
4287 !is_projection_capable_plan(lefttree))
4289 /* copy needed so we don't modify input's tlist below */
4290 tlist = copyObject(tlist);
4291 lefttree = (Plan *) make_result(root, tlist, NULL,
4295 /* Don't bother testing is_projection_capable_plan again */
4296 adjust_tlist_in_place = true;
4299 * Add resjunk entry to input's tlist
4301 tle = makeTargetEntry(sortexpr,
4302 list_length(tlist) + 1,
4305 tlist = lappend(tlist, tle);
4306 lefttree->targetlist = tlist; /* just in case NIL before */
4310 * Look up the correct sort operator from the PathKey's slightly
4311 * abstracted representation.
4313 sortop = get_opfamily_member(pathkey->pk_opfamily,
4316 pathkey->pk_strategy);
4317 if (!OidIsValid(sortop)) /* should not happen */
4318 elog(ERROR, "could not find member %d(%u,%u) of opfamily %u",
4319 pathkey->pk_strategy, pk_datatype, pk_datatype,
4320 pathkey->pk_opfamily);
4322 /* Add the column to the sort arrays */
4323 sortColIdx[numsortkeys] = tle->resno;
4324 sortOperators[numsortkeys] = sortop;
4325 collations[numsortkeys] = ec->ec_collation;
4326 nullsFirst[numsortkeys] = pathkey->pk_nulls_first;
4330 /* Return results */
4331 *p_numsortkeys = numsortkeys;
4332 *p_sortColIdx = sortColIdx;
4333 *p_sortOperators = sortOperators;
4334 *p_collations = collations;
4335 *p_nullsFirst = nullsFirst;
4341 * find_ec_member_for_tle
4342 * Locate an EquivalenceClass member matching the given TLE, if any
4344 * Child EC members are ignored unless they match 'relids'.
4346 static EquivalenceMember *
4347 find_ec_member_for_tle(EquivalenceClass *ec,
4354 /* We ignore binary-compatible relabeling on both ends */
4356 while (tlexpr && IsA(tlexpr, RelabelType))
4357 tlexpr = ((RelabelType *) tlexpr)->arg;
4359 foreach(lc, ec->ec_members)
4361 EquivalenceMember *em = (EquivalenceMember *) lfirst(lc);
4365 * We shouldn't be trying to sort by an equivalence class that
4366 * contains a constant, so no need to consider such cases any further.
4368 if (em->em_is_const)
4372 * Ignore child members unless they match the rel being sorted.
4374 if (em->em_is_child &&
4375 !bms_equal(em->em_relids, relids))
4378 /* Match if same expression (after stripping relabel) */
4379 emexpr = em->em_expr;
4380 while (emexpr && IsA(emexpr, RelabelType))
4381 emexpr = ((RelabelType *) emexpr)->arg;
4383 if (equal(emexpr, tlexpr))
4391 * make_sort_from_pathkeys
4392 * Create sort plan to sort according to given pathkeys
4394 * 'lefttree' is the node which yields input tuples
4395 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
4396 * 'limit_tuples' is the bound on the number of output tuples;
4400 make_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
4401 double limit_tuples)
4404 AttrNumber *sortColIdx;
4409 /* Compute sort column info, and adjust lefttree as needed */
4410 lefttree = prepare_sort_from_pathkeys(root, lefttree, pathkeys,
4420 /* Now build the Sort node */
4421 return make_sort(root, lefttree, numsortkeys,
4422 sortColIdx, sortOperators, collations,
4423 nullsFirst, limit_tuples);
4427 * make_sort_from_sortclauses
4428 * Create sort plan to sort according to given sortclauses
4430 * 'sortcls' is a list of SortGroupClauses
4431 * 'lefttree' is the node which yields input tuples
4434 make_sort_from_sortclauses(PlannerInfo *root, List *sortcls, Plan *lefttree)
4436 List *sub_tlist = lefttree->targetlist;
4439 AttrNumber *sortColIdx;
4444 /* Convert list-ish representation to arrays wanted by executor */
4445 numsortkeys = list_length(sortcls);
4446 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
4447 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
4448 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
4449 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
4454 SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
4455 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
4457 sortColIdx[numsortkeys] = tle->resno;
4458 sortOperators[numsortkeys] = sortcl->sortop;
4459 collations[numsortkeys] = exprCollation((Node *) tle->expr);
4460 nullsFirst[numsortkeys] = sortcl->nulls_first;
4464 return make_sort(root, lefttree, numsortkeys,
4465 sortColIdx, sortOperators, collations,
4470 * make_sort_from_groupcols
4471 * Create sort plan to sort based on grouping columns
4473 * 'groupcls' is the list of SortGroupClauses
4474 * 'grpColIdx' gives the column numbers to use
4476 * This might look like it could be merged with make_sort_from_sortclauses,
4477 * but presently we *must* use the grpColIdx[] array to locate sort columns,
4478 * because the child plan's tlist is not marked with ressortgroupref info
4479 * appropriate to the grouping node. So, only the sort ordering info
4480 * is used from the SortGroupClause entries.
4483 make_sort_from_groupcols(PlannerInfo *root,
4485 AttrNumber *grpColIdx,
4488 List *sub_tlist = lefttree->targetlist;
4491 AttrNumber *sortColIdx;
4496 /* Convert list-ish representation to arrays wanted by executor */
4497 numsortkeys = list_length(groupcls);
4498 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
4499 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
4500 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
4501 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
4504 foreach(l, groupcls)
4506 SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
4507 TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[numsortkeys]);
4510 elog(ERROR, "could not retrieve tle for sort-from-groupcols");
4512 sortColIdx[numsortkeys] = tle->resno;
4513 sortOperators[numsortkeys] = grpcl->sortop;
4514 collations[numsortkeys] = exprCollation((Node *) tle->expr);
4515 nullsFirst[numsortkeys] = grpcl->nulls_first;
4519 return make_sort(root, lefttree, numsortkeys,
4520 sortColIdx, sortOperators, collations,
4525 make_material(Plan *lefttree)
4527 Material *node = makeNode(Material);
4528 Plan *plan = &node->plan;
4530 /* cost should be inserted by caller */
4531 plan->targetlist = lefttree->targetlist;
4533 plan->lefttree = lefttree;
4534 plan->righttree = NULL;
4540 * materialize_finished_plan: stick a Material node atop a completed plan
4542 * There are a couple of places where we want to attach a Material node
4543 * after completion of subquery_planner(), without any MaterialPath path.
4546 materialize_finished_plan(Plan *subplan)
4549 Path matpath; /* dummy for result of cost_material */
4551 matplan = (Plan *) make_material(subplan);
4554 cost_material(&matpath,
4555 subplan->startup_cost,
4556 subplan->total_cost,
4558 subplan->plan_width);
4559 matplan->startup_cost = matpath.startup_cost;
4560 matplan->total_cost = matpath.total_cost;
4561 matplan->plan_rows = subplan->plan_rows;
4562 matplan->plan_width = subplan->plan_width;
4568 make_agg(PlannerInfo *root, List *tlist, List *qual,
4569 AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
4570 int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators,
4571 List *groupingSets, long numGroups, bool combineStates,
4572 bool finalizeAggs, Plan *lefttree)
4574 Agg *node = makeNode(Agg);
4575 Plan *plan = &node->plan;
4576 Path agg_path; /* dummy for result of cost_agg */
4579 node->aggstrategy = aggstrategy;
4580 node->numCols = numGroupCols;
4581 node->combineStates = combineStates;
4582 node->finalizeAggs = finalizeAggs;
4583 node->grpColIdx = grpColIdx;
4584 node->grpOperators = grpOperators;
4585 node->numGroups = numGroups;
4587 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4588 cost_agg(&agg_path, root,
4589 aggstrategy, aggcosts,
4590 numGroupCols, numGroups,
4591 lefttree->startup_cost,
4592 lefttree->total_cost,
4593 lefttree->plan_rows);
4594 plan->startup_cost = agg_path.startup_cost;
4595 plan->total_cost = agg_path.total_cost;
4598 * We will produce a single output tuple if not grouping, and a tuple per
4601 if (aggstrategy == AGG_PLAIN)
4602 plan->plan_rows = groupingSets ? list_length(groupingSets) : 1;
4604 plan->plan_rows = numGroups;
4606 node->groupingSets = groupingSets;
4609 * We also need to account for the cost of evaluation of the qual (ie, the
4610 * HAVING clause) and the tlist. Note that cost_qual_eval doesn't charge
4611 * anything for Aggref nodes; this is okay since they are really
4612 * comparable to Vars.
4614 * See notes in add_tlist_costs_to_plan about why only make_agg,
4615 * make_windowagg and make_group worry about tlist eval cost.
4619 cost_qual_eval(&qual_cost, qual, root);
4620 plan->startup_cost += qual_cost.startup;
4621 plan->total_cost += qual_cost.startup;
4622 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
4624 add_tlist_costs_to_plan(root, plan, tlist);
4627 plan->targetlist = tlist;
4629 plan->lefttree = lefttree;
4630 plan->righttree = NULL;
4636 make_windowagg(PlannerInfo *root, List *tlist,
4637 List *windowFuncs, Index winref,
4638 int partNumCols, AttrNumber *partColIdx, Oid *partOperators,
4639 int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators,
4640 int frameOptions, Node *startOffset, Node *endOffset,
4643 WindowAgg *node = makeNode(WindowAgg);
4644 Plan *plan = &node->plan;
4645 Path windowagg_path; /* dummy for result of cost_windowagg */
4647 node->winref = winref;
4648 node->partNumCols = partNumCols;
4649 node->partColIdx = partColIdx;
4650 node->partOperators = partOperators;
4651 node->ordNumCols = ordNumCols;
4652 node->ordColIdx = ordColIdx;
4653 node->ordOperators = ordOperators;
4654 node->frameOptions = frameOptions;
4655 node->startOffset = startOffset;
4656 node->endOffset = endOffset;
4658 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4659 cost_windowagg(&windowagg_path, root,
4660 windowFuncs, partNumCols, ordNumCols,
4661 lefttree->startup_cost,
4662 lefttree->total_cost,
4663 lefttree->plan_rows);
4664 plan->startup_cost = windowagg_path.startup_cost;
4665 plan->total_cost = windowagg_path.total_cost;
4668 * We also need to account for the cost of evaluation of the tlist.
4670 * See notes in add_tlist_costs_to_plan about why only make_agg,
4671 * make_windowagg and make_group worry about tlist eval cost.
4673 add_tlist_costs_to_plan(root, plan, tlist);
4675 plan->targetlist = tlist;
4676 plan->lefttree = lefttree;
4677 plan->righttree = NULL;
4678 /* WindowAgg nodes never have a qual clause */
4685 make_group(PlannerInfo *root,
4689 AttrNumber *grpColIdx,
4694 Group *node = makeNode(Group);
4695 Plan *plan = &node->plan;
4696 Path group_path; /* dummy for result of cost_group */
4699 node->numCols = numGroupCols;
4700 node->grpColIdx = grpColIdx;
4701 node->grpOperators = grpOperators;
4703 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4704 cost_group(&group_path, root,
4705 numGroupCols, numGroups,
4706 lefttree->startup_cost,
4707 lefttree->total_cost,
4708 lefttree->plan_rows);
4709 plan->startup_cost = group_path.startup_cost;
4710 plan->total_cost = group_path.total_cost;
4712 /* One output tuple per estimated result group */
4713 plan->plan_rows = numGroups;
4716 * We also need to account for the cost of evaluation of the qual (ie, the
4717 * HAVING clause) and the tlist.
4719 * XXX this double-counts the cost of evaluation of any expressions used
4720 * for grouping, since in reality those will have been evaluated at a
4721 * lower plan level and will only be copied by the Group node. Worth
4724 * See notes in add_tlist_costs_to_plan about why only make_agg,
4725 * make_windowagg and make_group worry about tlist eval cost.
4729 cost_qual_eval(&qual_cost, qual, root);
4730 plan->startup_cost += qual_cost.startup;
4731 plan->total_cost += qual_cost.startup;
4732 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
4734 add_tlist_costs_to_plan(root, plan, tlist);
4737 plan->targetlist = tlist;
4738 plan->lefttree = lefttree;
4739 plan->righttree = NULL;
4745 * distinctList is a list of SortGroupClauses, identifying the targetlist items
4746 * that should be considered by the Unique filter. The input path must
4747 * already be sorted accordingly.
4750 make_unique(Plan *lefttree, List *distinctList)
4752 Unique *node = makeNode(Unique);
4753 Plan *plan = &node->plan;
4754 int numCols = list_length(distinctList);
4756 AttrNumber *uniqColIdx;
4760 copy_plan_costsize(plan, lefttree);
4763 * Charge one cpu_operator_cost per comparison per input tuple. We assume
4764 * all columns get compared at most of the tuples. (XXX probably this is
4767 plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols;
4770 * plan->plan_rows is left as a copy of the input subplan's plan_rows; ie,
4771 * we assume the filter removes nothing. The caller must alter this if he
4772 * has a better idea.
4775 plan->targetlist = lefttree->targetlist;
4777 plan->lefttree = lefttree;
4778 plan->righttree = NULL;
4781 * convert SortGroupClause list into arrays of attr indexes and equality
4782 * operators, as wanted by executor
4784 Assert(numCols > 0);
4785 uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
4786 uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
4788 foreach(slitem, distinctList)
4790 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
4791 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
4793 uniqColIdx[keyno] = tle->resno;
4794 uniqOperators[keyno] = sortcl->eqop;
4795 Assert(OidIsValid(uniqOperators[keyno]));
4799 node->numCols = numCols;
4800 node->uniqColIdx = uniqColIdx;
4801 node->uniqOperators = uniqOperators;
4807 make_gather(List *qptlist,
4813 Gather *node = makeNode(Gather);
4814 Plan *plan = &node->plan;
4816 /* cost should be inserted by caller */
4817 plan->targetlist = qptlist;
4818 plan->qual = qpqual;
4819 plan->lefttree = subplan;
4820 plan->righttree = NULL;
4821 node->num_workers = nworkers;
4822 node->single_copy = single_copy;
4828 * distinctList is a list of SortGroupClauses, identifying the targetlist
4829 * items that should be considered by the SetOp filter. The input path must
4830 * already be sorted accordingly.
4833 make_setop(SetOpCmd cmd, SetOpStrategy strategy, Plan *lefttree,
4834 List *distinctList, AttrNumber flagColIdx, int firstFlag,
4835 long numGroups, double outputRows)
4837 SetOp *node = makeNode(SetOp);
4838 Plan *plan = &node->plan;
4839 int numCols = list_length(distinctList);
4841 AttrNumber *dupColIdx;
4845 copy_plan_costsize(plan, lefttree);
4846 plan->plan_rows = outputRows;
4849 * Charge one cpu_operator_cost per comparison per input tuple. We assume
4850 * all columns get compared at most of the tuples.
4852 plan->total_cost += cpu_operator_cost * lefttree->plan_rows * numCols;
4854 plan->targetlist = lefttree->targetlist;
4856 plan->lefttree = lefttree;
4857 plan->righttree = NULL;
4860 * convert SortGroupClause list into arrays of attr indexes and equality
4861 * operators, as wanted by executor
4863 Assert(numCols > 0);
4864 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
4865 dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
4867 foreach(slitem, distinctList)
4869 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
4870 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
4872 dupColIdx[keyno] = tle->resno;
4873 dupOperators[keyno] = sortcl->eqop;
4874 Assert(OidIsValid(dupOperators[keyno]));
4879 node->strategy = strategy;
4880 node->numCols = numCols;
4881 node->dupColIdx = dupColIdx;
4882 node->dupOperators = dupOperators;
4883 node->flagColIdx = flagColIdx;
4884 node->firstFlag = firstFlag;
4885 node->numGroups = numGroups;
4892 * Build a LockRows plan node
4895 make_lockrows(Plan *lefttree, List *rowMarks, int epqParam)
4897 LockRows *node = makeNode(LockRows);
4898 Plan *plan = &node->plan;
4900 copy_plan_costsize(plan, lefttree);
4902 /* charge cpu_tuple_cost to reflect locking costs (underestimate?) */
4903 plan->total_cost += cpu_tuple_cost * plan->plan_rows;
4905 plan->targetlist = lefttree->targetlist;
4907 plan->lefttree = lefttree;
4908 plan->righttree = NULL;
4910 node->rowMarks = rowMarks;
4911 node->epqParam = epqParam;
4917 * Note: offset_est and count_est are passed in to save having to repeat
4918 * work already done to estimate the values of the limitOffset and limitCount
4919 * expressions. Their values are as returned by preprocess_limit (0 means
4920 * "not relevant", -1 means "couldn't estimate"). Keep the code below in sync
4921 * with that function!
4924 make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount,
4925 int64 offset_est, int64 count_est)
4927 Limit *node = makeNode(Limit);
4928 Plan *plan = &node->plan;
4930 copy_plan_costsize(plan, lefttree);
4933 * Adjust the output rows count and costs according to the offset/limit.
4934 * This is only a cosmetic issue if we are at top level, but if we are
4935 * building a subquery then it's important to report correct info to the
4938 * When the offset or count couldn't be estimated, use 10% of the
4939 * estimated number of rows emitted from the subplan.
4941 if (offset_est != 0)
4946 offset_rows = (double) offset_est;
4948 offset_rows = clamp_row_est(lefttree->plan_rows * 0.10);
4949 if (offset_rows > plan->plan_rows)
4950 offset_rows = plan->plan_rows;
4951 if (plan->plan_rows > 0)
4952 plan->startup_cost +=
4953 (plan->total_cost - plan->startup_cost)
4954 * offset_rows / plan->plan_rows;
4955 plan->plan_rows -= offset_rows;
4956 if (plan->plan_rows < 1)
4957 plan->plan_rows = 1;
4965 count_rows = (double) count_est;
4967 count_rows = clamp_row_est(lefttree->plan_rows * 0.10);
4968 if (count_rows > plan->plan_rows)
4969 count_rows = plan->plan_rows;
4970 if (plan->plan_rows > 0)
4971 plan->total_cost = plan->startup_cost +
4972 (plan->total_cost - plan->startup_cost)
4973 * count_rows / plan->plan_rows;
4974 plan->plan_rows = count_rows;
4975 if (plan->plan_rows < 1)
4976 plan->plan_rows = 1;
4979 plan->targetlist = lefttree->targetlist;
4981 plan->lefttree = lefttree;
4982 plan->righttree = NULL;
4984 node->limitOffset = limitOffset;
4985 node->limitCount = limitCount;
4992 * Build a Result plan node
4994 * If we have a subplan, assume that any evaluation costs for the gating qual
4995 * were already factored into the subplan's startup cost, and just copy the
4996 * subplan cost. If there's no subplan, we should include the qual eval
4997 * cost. In either case, tlist eval cost is not to be included here.
5000 make_result(PlannerInfo *root,
5002 Node *resconstantqual,
5005 Result *node = makeNode(Result);
5006 Plan *plan = &node->plan;
5009 copy_plan_costsize(plan, subplan);
5012 plan->startup_cost = 0;
5013 plan->total_cost = cpu_tuple_cost;
5014 plan->plan_rows = 1; /* wrong if we have a set-valued function? */
5015 plan->plan_width = 0; /* XXX is it worth being smarter? */
5016 if (resconstantqual)
5020 cost_qual_eval(&qual_cost, (List *) resconstantqual, root);
5021 /* resconstantqual is evaluated once at startup */
5022 plan->startup_cost += qual_cost.startup + qual_cost.per_tuple;
5023 plan->total_cost += qual_cost.startup + qual_cost.per_tuple;
5027 plan->targetlist = tlist;
5029 plan->lefttree = subplan;
5030 plan->righttree = NULL;
5031 node->resconstantqual = resconstantqual;
5038 * Build a ModifyTable plan node
5040 * Currently, we don't charge anything extra for the actual table modification
5041 * work, nor for the WITH CHECK OPTIONS or RETURNING expressions if any. It
5042 * would only be window dressing, since these are always top-level nodes and
5043 * there is no way for the costs to change any higher-level planning choices.
5044 * But we might want to make it look better sometime.
5047 make_modifytable(PlannerInfo *root,
5048 CmdType operation, bool canSetTag,
5049 Index nominalRelation,
5050 List *resultRelations, List *subplans,
5051 List *withCheckOptionLists, List *returningLists,
5052 List *rowMarks, OnConflictExpr *onconflict, int epqParam)
5054 ModifyTable *node = makeNode(ModifyTable);
5055 Plan *plan = &node->plan;
5057 List *fdw_private_list;
5062 Assert(list_length(resultRelations) == list_length(subplans));
5063 Assert(withCheckOptionLists == NIL ||
5064 list_length(resultRelations) == list_length(withCheckOptionLists));
5065 Assert(returningLists == NIL ||
5066 list_length(resultRelations) == list_length(returningLists));
5069 * Compute cost as sum of subplan costs.
5071 plan->startup_cost = 0;
5072 plan->total_cost = 0;
5073 plan->plan_rows = 0;
5075 foreach(subnode, subplans)
5077 Plan *subplan = (Plan *) lfirst(subnode);
5079 if (subnode == list_head(subplans)) /* first node? */
5080 plan->startup_cost = subplan->startup_cost;
5081 plan->total_cost += subplan->total_cost;
5082 plan->plan_rows += subplan->plan_rows;
5083 total_size += subplan->plan_width * subplan->plan_rows;
5085 if (plan->plan_rows > 0)
5086 plan->plan_width = rint(total_size / plan->plan_rows);
5088 plan->plan_width = 0;
5090 node->plan.lefttree = NULL;
5091 node->plan.righttree = NULL;
5092 node->plan.qual = NIL;
5093 /* setrefs.c will fill in the targetlist, if needed */
5094 node->plan.targetlist = NIL;
5096 node->operation = operation;
5097 node->canSetTag = canSetTag;
5098 node->nominalRelation = nominalRelation;
5099 node->resultRelations = resultRelations;
5100 node->resultRelIndex = -1; /* will be set correctly in setrefs.c */
5101 node->plans = subplans;
5104 node->onConflictAction = ONCONFLICT_NONE;
5105 node->onConflictSet = NIL;
5106 node->onConflictWhere = NULL;
5107 node->arbiterIndexes = NIL;
5108 node->exclRelRTI = 0;
5109 node->exclRelTlist = NIL;
5113 node->onConflictAction = onconflict->action;
5114 node->onConflictSet = onconflict->onConflictSet;
5115 node->onConflictWhere = onconflict->onConflictWhere;
5118 * If a set of unique index inference elements was provided (an
5119 * INSERT...ON CONFLICT "inference specification"), then infer
5120 * appropriate unique indexes (or throw an error if none are
5123 node->arbiterIndexes = infer_arbiter_indexes(root);
5125 node->exclRelRTI = onconflict->exclRelIndex;
5126 node->exclRelTlist = onconflict->exclRelTlist;
5128 node->withCheckOptionLists = withCheckOptionLists;
5129 node->returningLists = returningLists;
5130 node->rowMarks = rowMarks;
5131 node->epqParam = epqParam;
5134 * For each result relation that is a foreign table, allow the FDW to
5135 * construct private plan data, and accumulate it all into a list.
5137 fdw_private_list = NIL;
5139 foreach(lc, resultRelations)
5141 Index rti = lfirst_int(lc);
5142 FdwRoutine *fdwroutine;
5146 * If possible, we want to get the FdwRoutine from our RelOptInfo for
5147 * the table. But sometimes we don't have a RelOptInfo and must get
5148 * it the hard way. (In INSERT, the target relation is not scanned,
5149 * so it's not a baserel; and there are also corner cases for
5150 * updatable views where the target rel isn't a baserel.)
5152 if (rti < root->simple_rel_array_size &&
5153 root->simple_rel_array[rti] != NULL)
5155 RelOptInfo *resultRel = root->simple_rel_array[rti];
5157 fdwroutine = resultRel->fdwroutine;
5161 RangeTblEntry *rte = planner_rt_fetch(rti, root);
5163 Assert(rte->rtekind == RTE_RELATION);
5164 if (rte->relkind == RELKIND_FOREIGN_TABLE)
5165 fdwroutine = GetFdwRoutineByRelId(rte->relid);
5170 if (fdwroutine != NULL &&
5171 fdwroutine->PlanForeignModify != NULL)
5172 fdw_private = fdwroutine->PlanForeignModify(root, node, rti, i);
5175 fdw_private_list = lappend(fdw_private_list, fdw_private);
5178 node->fdwPrivLists = fdw_private_list;
5184 * is_projection_capable_plan
5185 * Check whether a given Plan node is able to do projection.
5188 is_projection_capable_plan(Plan *plan)
5190 /* Most plan types can project, so just list the ones that can't */
5191 switch (nodeTag(plan))
5203 case T_RecursiveUnion: