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-2012, 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/skey.h"
23 #include "foreign/fdwapi.h"
24 #include "miscadmin.h"
25 #include "nodes/makefuncs.h"
26 #include "nodes/nodeFuncs.h"
27 #include "optimizer/clauses.h"
28 #include "optimizer/cost.h"
29 #include "optimizer/paths.h"
30 #include "optimizer/placeholder.h"
31 #include "optimizer/plancat.h"
32 #include "optimizer/planmain.h"
33 #include "optimizer/planner.h"
34 #include "optimizer/predtest.h"
35 #include "optimizer/restrictinfo.h"
36 #include "optimizer/subselect.h"
37 #include "optimizer/tlist.h"
38 #include "optimizer/var.h"
39 #include "parser/parse_clause.h"
40 #include "parser/parsetree.h"
41 #include "utils/lsyscache.h"
44 static Plan *create_plan_recurse(PlannerInfo *root, Path *best_path);
45 static Plan *create_scan_plan(PlannerInfo *root, Path *best_path);
46 static List *build_relation_tlist(RelOptInfo *rel);
47 static bool use_physical_tlist(PlannerInfo *root, RelOptInfo *rel);
48 static void disuse_physical_tlist(Plan *plan, Path *path);
49 static Plan *create_gating_plan(PlannerInfo *root, Plan *plan, List *quals);
50 static Plan *create_join_plan(PlannerInfo *root, JoinPath *best_path);
51 static Plan *create_append_plan(PlannerInfo *root, AppendPath *best_path);
52 static Plan *create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path);
53 static Result *create_result_plan(PlannerInfo *root, ResultPath *best_path);
54 static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path);
55 static Plan *create_unique_plan(PlannerInfo *root, UniquePath *best_path);
56 static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path,
57 List *tlist, List *scan_clauses);
58 static Scan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path,
59 List *tlist, List *scan_clauses, bool indexonly);
60 static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
61 BitmapHeapPath *best_path,
62 List *tlist, List *scan_clauses);
63 static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
64 List **qual, List **indexqual, List **indexECs);
65 static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
66 List *tlist, List *scan_clauses);
67 static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
68 List *tlist, List *scan_clauses);
69 static FunctionScan *create_functionscan_plan(PlannerInfo *root, Path *best_path,
70 List *tlist, List *scan_clauses);
71 static ValuesScan *create_valuesscan_plan(PlannerInfo *root, Path *best_path,
72 List *tlist, List *scan_clauses);
73 static CteScan *create_ctescan_plan(PlannerInfo *root, Path *best_path,
74 List *tlist, List *scan_clauses);
75 static WorkTableScan *create_worktablescan_plan(PlannerInfo *root, Path *best_path,
76 List *tlist, List *scan_clauses);
77 static ForeignScan *create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
78 List *tlist, List *scan_clauses);
79 static NestLoop *create_nestloop_plan(PlannerInfo *root, NestPath *best_path,
80 Plan *outer_plan, Plan *inner_plan);
81 static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path,
82 Plan *outer_plan, Plan *inner_plan);
83 static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path,
84 Plan *outer_plan, Plan *inner_plan);
85 static Node *replace_nestloop_params(PlannerInfo *root, Node *expr);
86 static Node *replace_nestloop_params_mutator(Node *node, PlannerInfo *root);
87 static void process_subquery_nestloop_params(PlannerInfo *root,
88 List *subplan_params);
89 static List *fix_indexqual_references(PlannerInfo *root, IndexPath *index_path);
90 static List *fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path);
91 static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol);
92 static List *get_switched_clauses(List *clauses, Relids outerrelids);
93 static List *order_qual_clauses(PlannerInfo *root, List *clauses);
94 static void copy_path_costsize(Plan *dest, Path *src);
95 static void copy_plan_costsize(Plan *dest, Plan *src);
96 static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
97 static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
98 Oid indexid, List *indexqual, List *indexqualorig,
99 List *indexorderby, List *indexorderbyorig,
100 ScanDirection indexscandir);
101 static IndexOnlyScan *make_indexonlyscan(List *qptlist, List *qpqual,
102 Index scanrelid, Oid indexid,
103 List *indexqual, List *indexorderby,
105 ScanDirection indexscandir);
106 static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid,
108 List *indexqualorig);
109 static BitmapHeapScan *make_bitmap_heapscan(List *qptlist,
112 List *bitmapqualorig,
114 static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
116 static FunctionScan *make_functionscan(List *qptlist, List *qpqual,
117 Index scanrelid, Node *funcexpr, List *funccolnames,
118 List *funccoltypes, List *funccoltypmods,
119 List *funccolcollations);
120 static ValuesScan *make_valuesscan(List *qptlist, List *qpqual,
121 Index scanrelid, List *values_lists);
122 static CteScan *make_ctescan(List *qptlist, List *qpqual,
123 Index scanrelid, int ctePlanId, int cteParam);
124 static WorkTableScan *make_worktablescan(List *qptlist, List *qpqual,
125 Index scanrelid, int wtParam);
126 static BitmapAnd *make_bitmap_and(List *bitmapplans);
127 static BitmapOr *make_bitmap_or(List *bitmapplans);
128 static NestLoop *make_nestloop(List *tlist,
129 List *joinclauses, List *otherclauses, List *nestParams,
130 Plan *lefttree, Plan *righttree,
132 static HashJoin *make_hashjoin(List *tlist,
133 List *joinclauses, List *otherclauses,
135 Plan *lefttree, Plan *righttree,
137 static Hash *make_hash(Plan *lefttree,
139 AttrNumber skewColumn,
142 int32 skewColTypmod);
143 static MergeJoin *make_mergejoin(List *tlist,
144 List *joinclauses, List *otherclauses,
147 Oid *mergecollations,
148 int *mergestrategies,
149 bool *mergenullsfirst,
150 Plan *lefttree, Plan *righttree,
152 static Sort *make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
153 AttrNumber *sortColIdx, Oid *sortOperators,
154 Oid *collations, bool *nullsFirst,
155 double limit_tuples);
156 static Plan *prepare_sort_from_pathkeys(PlannerInfo *root,
157 Plan *lefttree, List *pathkeys,
159 const AttrNumber *reqColIdx,
160 bool adjust_tlist_in_place,
162 AttrNumber **p_sortColIdx,
163 Oid **p_sortOperators,
165 bool **p_nullsFirst);
166 static EquivalenceMember *find_ec_member_for_tle(EquivalenceClass *ec,
169 static Material *make_material(Plan *lefttree);
174 * Creates the access plan for a query by recursively processing the
175 * desired tree of pathnodes, starting at the node 'best_path'. For
176 * every pathnode found, we create a corresponding plan node containing
177 * appropriate id, target list, and qualification information.
179 * The tlists and quals in the plan tree are still in planner format,
180 * ie, Vars still correspond to the parser's numbering. This will be
181 * fixed later by setrefs.c.
183 * best_path is the best access path
185 * Returns a Plan tree.
188 create_plan(PlannerInfo *root, Path *best_path)
192 /* plan_params should not be in use in current query level */
193 Assert(root->plan_params == NIL);
195 /* Initialize this module's private workspace in PlannerInfo */
196 root->curOuterRels = NULL;
197 root->curOuterParams = NIL;
199 /* Recursively process the path tree */
200 plan = create_plan_recurse(root, best_path);
202 /* Check we successfully assigned all NestLoopParams to plan nodes */
203 if (root->curOuterParams != NIL)
204 elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
207 * Reset plan_params to ensure param IDs used for nestloop params are not
210 root->plan_params = NIL;
216 * create_plan_recurse
217 * Recursive guts of create_plan().
220 create_plan_recurse(PlannerInfo *root, Path *best_path)
224 switch (best_path->pathtype)
228 case T_IndexOnlyScan:
229 case T_BitmapHeapScan:
235 case T_WorkTableScan:
237 plan = create_scan_plan(root, best_path);
242 plan = create_join_plan(root,
243 (JoinPath *) best_path);
246 plan = create_append_plan(root,
247 (AppendPath *) best_path);
250 plan = create_merge_append_plan(root,
251 (MergeAppendPath *) best_path);
254 plan = (Plan *) create_result_plan(root,
255 (ResultPath *) best_path);
258 plan = (Plan *) create_material_plan(root,
259 (MaterialPath *) best_path);
262 plan = create_unique_plan(root,
263 (UniquePath *) best_path);
266 elog(ERROR, "unrecognized node type: %d",
267 (int) best_path->pathtype);
268 plan = NULL; /* keep compiler quiet */
277 * Create a scan plan for the parent relation of 'best_path'.
280 create_scan_plan(PlannerInfo *root, Path *best_path)
282 RelOptInfo *rel = best_path->parent;
288 * For table scans, rather than using the relation targetlist (which is
289 * only those Vars actually needed by the query), we prefer to generate a
290 * tlist containing all Vars in order. This will allow the executor to
291 * optimize away projection of the table tuples, if possible. (Note that
292 * planner.c may replace the tlist we generate here, forcing projection to
295 if (use_physical_tlist(root, rel))
297 if (best_path->pathtype == T_IndexOnlyScan)
299 /* For index-only scan, the preferred tlist is the index's */
300 tlist = copyObject(((IndexPath *) best_path)->indexinfo->indextlist);
304 tlist = build_physical_tlist(root, rel);
305 /* if fail because of dropped cols, use regular method */
307 tlist = build_relation_tlist(rel);
312 tlist = build_relation_tlist(rel);
315 * If it's a parameterized otherrel, there might be lateral references
316 * in the tlist, which need to be replaced with Params. This cannot
317 * happen for regular baserels, though. Note use_physical_tlist()
318 * always fails for otherrels, so we don't need to check this above.
320 if (rel->reloptkind != RELOPT_BASEREL && best_path->param_info)
321 tlist = (List *) replace_nestloop_params(root, (Node *) tlist);
325 * Extract the relevant restriction clauses from the parent relation. The
326 * executor must apply all these restrictions during the scan, except for
327 * pseudoconstants which we'll take care of below.
329 scan_clauses = rel->baserestrictinfo;
332 * If this is a parameterized scan, we also need to enforce all the join
333 * clauses available from the outer relation(s).
335 * For paranoia's sake, don't modify the stored baserestrictinfo list.
337 if (best_path->param_info)
338 scan_clauses = list_concat(list_copy(scan_clauses),
339 best_path->param_info->ppi_clauses);
341 switch (best_path->pathtype)
344 plan = (Plan *) create_seqscan_plan(root,
351 plan = (Plan *) create_indexscan_plan(root,
352 (IndexPath *) best_path,
358 case T_IndexOnlyScan:
359 plan = (Plan *) create_indexscan_plan(root,
360 (IndexPath *) best_path,
366 case T_BitmapHeapScan:
367 plan = (Plan *) create_bitmap_scan_plan(root,
368 (BitmapHeapPath *) best_path,
374 plan = (Plan *) create_tidscan_plan(root,
375 (TidPath *) best_path,
381 plan = (Plan *) create_subqueryscan_plan(root,
388 plan = (Plan *) create_functionscan_plan(root,
395 plan = (Plan *) create_valuesscan_plan(root,
402 plan = (Plan *) create_ctescan_plan(root,
408 case T_WorkTableScan:
409 plan = (Plan *) create_worktablescan_plan(root,
416 plan = (Plan *) create_foreignscan_plan(root,
417 (ForeignPath *) best_path,
423 elog(ERROR, "unrecognized node type: %d",
424 (int) best_path->pathtype);
425 plan = NULL; /* keep compiler quiet */
430 * If there are any pseudoconstant clauses attached to this node, insert a
431 * gating Result node that evaluates the pseudoconstants as one-time
434 if (root->hasPseudoConstantQuals)
435 plan = create_gating_plan(root, plan, scan_clauses);
441 * Build a target list (ie, a list of TargetEntry) for a relation.
444 build_relation_tlist(RelOptInfo *rel)
450 foreach(v, rel->reltargetlist)
452 /* Do we really need to copy here? Not sure */
453 Node *node = (Node *) copyObject(lfirst(v));
455 tlist = lappend(tlist, makeTargetEntry((Expr *) node,
466 * Decide whether to use a tlist matching relation structure,
467 * rather than only those Vars actually referenced.
470 use_physical_tlist(PlannerInfo *root, RelOptInfo *rel)
476 * We can do this for real relation scans, subquery scans, function scans,
477 * values scans, and CTE scans (but not for, eg, joins).
479 if (rel->rtekind != RTE_RELATION &&
480 rel->rtekind != RTE_SUBQUERY &&
481 rel->rtekind != RTE_FUNCTION &&
482 rel->rtekind != RTE_VALUES &&
483 rel->rtekind != RTE_CTE)
487 * Can't do it with inheritance cases either (mainly because Append
490 if (rel->reloptkind != RELOPT_BASEREL)
494 * Can't do it if any system columns or whole-row Vars are requested.
495 * (This could possibly be fixed but would take some fragile assumptions
496 * in setrefs.c, I think.)
498 for (i = rel->min_attr; i <= 0; i++)
500 if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
505 * Can't do it if the rel is required to emit any placeholder expressions,
508 foreach(lc, root->placeholder_list)
510 PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
512 if (bms_nonempty_difference(phinfo->ph_needed, rel->relids) &&
513 bms_is_subset(phinfo->ph_eval_at, rel->relids))
521 * disuse_physical_tlist
522 * Switch a plan node back to emitting only Vars actually referenced.
524 * If the plan node immediately above a scan would prefer to get only
525 * needed Vars and not a physical tlist, it must call this routine to
526 * undo the decision made by use_physical_tlist(). Currently, Hash, Sort,
527 * and Material nodes want this, so they don't have to store useless columns.
530 disuse_physical_tlist(Plan *plan, Path *path)
532 /* Only need to undo it for path types handled by create_scan_plan() */
533 switch (path->pathtype)
537 case T_IndexOnlyScan:
538 case T_BitmapHeapScan:
544 case T_WorkTableScan:
546 plan->targetlist = build_relation_tlist(path->parent);
555 * Deal with pseudoconstant qual clauses
557 * If the node's quals list includes any pseudoconstant quals, put them
558 * into a gating Result node atop the already-built plan. Otherwise,
559 * return the plan as-is.
561 * Note that we don't change cost or size estimates when doing gating.
562 * The costs of qual eval were already folded into the plan's startup cost.
563 * Leaving the size alone amounts to assuming that the gating qual will
564 * succeed, which is the conservative estimate for planning upper queries.
565 * We certainly don't want to assume the output size is zero (unless the
566 * gating qual is actually constant FALSE, and that case is dealt with in
567 * clausesel.c). Interpolating between the two cases is silly, because
568 * it doesn't reflect what will really happen at runtime, and besides which
569 * in most cases we have only a very bad idea of the probability of the gating
573 create_gating_plan(PlannerInfo *root, Plan *plan, List *quals)
575 List *pseudoconstants;
577 /* Sort into desirable execution order while still in RestrictInfo form */
578 quals = order_qual_clauses(root, quals);
580 /* Pull out any pseudoconstant quals from the RestrictInfo list */
581 pseudoconstants = extract_actual_clauses(quals, true);
583 if (!pseudoconstants)
586 return (Plan *) make_result(root,
588 (Node *) pseudoconstants,
594 * Create a join plan for 'best_path' and (recursively) plans for its
595 * inner and outer paths.
598 create_join_plan(PlannerInfo *root, JoinPath *best_path)
603 Relids saveOuterRels = root->curOuterRels;
605 outer_plan = create_plan_recurse(root, best_path->outerjoinpath);
607 /* For a nestloop, include outer relids in curOuterRels for inner side */
608 if (best_path->path.pathtype == T_NestLoop)
609 root->curOuterRels = bms_union(root->curOuterRels,
610 best_path->outerjoinpath->parent->relids);
612 inner_plan = create_plan_recurse(root, best_path->innerjoinpath);
614 switch (best_path->path.pathtype)
617 plan = (Plan *) create_mergejoin_plan(root,
618 (MergePath *) best_path,
623 plan = (Plan *) create_hashjoin_plan(root,
624 (HashPath *) best_path,
629 /* Restore curOuterRels */
630 bms_free(root->curOuterRels);
631 root->curOuterRels = saveOuterRels;
633 plan = (Plan *) create_nestloop_plan(root,
634 (NestPath *) best_path,
639 elog(ERROR, "unrecognized node type: %d",
640 (int) best_path->path.pathtype);
641 plan = NULL; /* keep compiler quiet */
646 * If there are any pseudoconstant clauses attached to this node, insert a
647 * gating Result node that evaluates the pseudoconstants as one-time
650 if (root->hasPseudoConstantQuals)
651 plan = create_gating_plan(root, plan, best_path->joinrestrictinfo);
656 * * Expensive function pullups may have pulled local predicates * into
657 * this path node. Put them in the qpqual of the plan node. * JMH,
660 if (get_loc_restrictinfo(best_path) != NIL)
661 set_qpqual((Plan) plan,
662 list_concat(get_qpqual((Plan) plan),
663 get_actual_clauses(get_loc_restrictinfo(best_path))));
671 * Create an Append plan for 'best_path' and (recursively) plans
674 * Returns a Plan node.
677 create_append_plan(PlannerInfo *root, AppendPath *best_path)
680 List *tlist = build_relation_tlist(best_path->path.parent);
681 List *subplans = NIL;
685 * It is possible for the subplans list to contain only one entry, or even
686 * no entries. Handle these cases specially.
688 * XXX ideally, if there's just one entry, we'd not bother to generate an
689 * Append node but just return the single child. At the moment this does
690 * not work because the varno of the child scan plan won't match the
691 * parent-rel Vars it'll be asked to emit.
693 if (best_path->subpaths == NIL)
695 /* Generate a Result plan with constant-FALSE gating qual */
696 return (Plan *) make_result(root,
698 (Node *) list_make1(makeBoolConst(false,
703 /* Normal case with multiple subpaths */
704 foreach(subpaths, best_path->subpaths)
706 Path *subpath = (Path *) lfirst(subpaths);
708 subplans = lappend(subplans, create_plan_recurse(root, subpath));
711 plan = make_append(subplans, tlist);
713 return (Plan *) plan;
717 * create_merge_append_plan
718 * Create a MergeAppend plan for 'best_path' and (recursively) plans
721 * Returns a Plan node.
724 create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path)
726 MergeAppend *node = makeNode(MergeAppend);
727 Plan *plan = &node->plan;
728 List *tlist = build_relation_tlist(best_path->path.parent);
729 List *pathkeys = best_path->path.pathkeys;
730 List *subplans = NIL;
734 * We don't have the actual creation of the MergeAppend node split out
735 * into a separate make_xxx function. This is because we want to run
736 * prepare_sort_from_pathkeys on it before we do so on the individual
737 * child plans, to make cross-checking the sort info easier.
739 copy_path_costsize(plan, (Path *) best_path);
740 plan->targetlist = tlist;
742 plan->lefttree = NULL;
743 plan->righttree = NULL;
745 /* Compute sort column info, and adjust MergeAppend's tlist as needed */
746 (void) prepare_sort_from_pathkeys(root, plan, pathkeys,
752 &node->sortOperators,
757 * Now prepare the child plans. We must apply prepare_sort_from_pathkeys
758 * even to subplans that don't need an explicit sort, to make sure they
759 * are returning the same sort key columns the MergeAppend expects.
761 foreach(subpaths, best_path->subpaths)
763 Path *subpath = (Path *) lfirst(subpaths);
766 AttrNumber *sortColIdx;
771 /* Build the child plan */
772 subplan = create_plan_recurse(root, subpath);
774 /* Compute sort column info, and adjust subplan's tlist as needed */
775 subplan = prepare_sort_from_pathkeys(root, subplan, pathkeys,
776 subpath->parent->relids,
786 * Check that we got the same sort key information. We just Assert
787 * that the sortops match, since those depend only on the pathkeys;
788 * but it seems like a good idea to check the sort column numbers
789 * explicitly, to ensure the tlists really do match up.
791 Assert(numsortkeys == node->numCols);
792 if (memcmp(sortColIdx, node->sortColIdx,
793 numsortkeys * sizeof(AttrNumber)) != 0)
794 elog(ERROR, "MergeAppend child's targetlist doesn't match MergeAppend");
795 Assert(memcmp(sortOperators, node->sortOperators,
796 numsortkeys * sizeof(Oid)) == 0);
797 Assert(memcmp(collations, node->collations,
798 numsortkeys * sizeof(Oid)) == 0);
799 Assert(memcmp(nullsFirst, node->nullsFirst,
800 numsortkeys * sizeof(bool)) == 0);
802 /* Now, insert a Sort node if subplan isn't sufficiently ordered */
803 if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
804 subplan = (Plan *) make_sort(root, subplan, numsortkeys,
805 sortColIdx, sortOperators,
806 collations, nullsFirst,
807 best_path->limit_tuples);
809 subplans = lappend(subplans, subplan);
812 node->mergeplans = subplans;
814 return (Plan *) node;
819 * Create a Result plan for 'best_path'.
820 * This is only used for the case of a query with an empty jointree.
822 * Returns a Plan node.
825 create_result_plan(PlannerInfo *root, ResultPath *best_path)
830 /* The tlist will be installed later, since we have no RelOptInfo */
831 Assert(best_path->path.parent == NULL);
834 /* best_path->quals is just bare clauses */
836 quals = order_qual_clauses(root, best_path->quals);
838 return make_result(root, tlist, (Node *) quals, NULL);
842 * create_material_plan
843 * Create a Material plan for 'best_path' and (recursively) plans
846 * Returns a Plan node.
849 create_material_plan(PlannerInfo *root, MaterialPath *best_path)
854 subplan = create_plan_recurse(root, best_path->subpath);
856 /* We don't want any excess columns in the materialized tuples */
857 disuse_physical_tlist(subplan, best_path->subpath);
859 plan = make_material(subplan);
861 copy_path_costsize(&plan->plan, (Path *) best_path);
868 * Create a Unique plan for 'best_path' and (recursively) plans
871 * Returns a Plan node.
874 create_unique_plan(PlannerInfo *root, UniquePath *best_path)
884 AttrNumber *groupColIdx;
888 subplan = create_plan_recurse(root, best_path->subpath);
890 /* Done if we don't need to do any actual unique-ifying */
891 if (best_path->umethod == UNIQUE_PATH_NOOP)
895 * As constructed, the subplan has a "flat" tlist containing just the Vars
896 * needed here and at upper levels. The values we are supposed to
897 * unique-ify may be expressions in these variables. We have to add any
898 * such expressions to the subplan's tlist.
900 * The subplan may have a "physical" tlist if it is a simple scan plan. If
901 * we're going to sort, this should be reduced to the regular tlist, so
902 * that we don't sort more data than we need to. For hashing, the tlist
903 * should be left as-is if we don't need to add any expressions; but if we
904 * do have to add expressions, then a projection step will be needed at
905 * runtime anyway, so we may as well remove unneeded items. Therefore
906 * newtlist starts from build_relation_tlist() not just a copy of the
907 * subplan's tlist; and we don't install it into the subplan unless we are
908 * sorting or stuff has to be added.
910 in_operators = best_path->in_operators;
911 uniq_exprs = best_path->uniq_exprs;
913 /* initialize modified subplan tlist as just the "required" vars */
914 newtlist = build_relation_tlist(best_path->path.parent);
915 nextresno = list_length(newtlist) + 1;
918 foreach(l, uniq_exprs)
920 Node *uniqexpr = lfirst(l);
923 tle = tlist_member(uniqexpr, newtlist);
926 tle = makeTargetEntry((Expr *) uniqexpr,
930 newtlist = lappend(newtlist, tle);
936 if (newitems || best_path->umethod == UNIQUE_PATH_SORT)
939 * If the top plan node can't do projections, we need to add a Result
940 * node to help it along.
942 if (!is_projection_capable_plan(subplan))
943 subplan = (Plan *) make_result(root, newtlist, NULL, subplan);
945 subplan->targetlist = newtlist;
949 * Build control information showing which subplan output columns are to
950 * be examined by the grouping step. Unfortunately we can't merge this
951 * with the previous loop, since we didn't then know which version of the
952 * subplan tlist we'd end up using.
954 newtlist = subplan->targetlist;
955 numGroupCols = list_length(uniq_exprs);
956 groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber));
959 foreach(l, uniq_exprs)
961 Node *uniqexpr = lfirst(l);
964 tle = tlist_member(uniqexpr, newtlist);
965 if (!tle) /* shouldn't happen */
966 elog(ERROR, "failed to find unique expression in subplan tlist");
967 groupColIdx[groupColPos++] = tle->resno;
970 if (best_path->umethod == UNIQUE_PATH_HASH)
975 numGroups = (long) Min(best_path->path.rows, (double) LONG_MAX);
978 * Get the hashable equality operators for the Agg node to use.
979 * Normally these are the same as the IN clause operators, but if
980 * those are cross-type operators then the equality operators are the
981 * ones for the IN clause operators' RHS datatype.
983 groupOperators = (Oid *) palloc(numGroupCols * sizeof(Oid));
985 foreach(l, in_operators)
987 Oid in_oper = lfirst_oid(l);
990 if (!get_compatible_hash_operators(in_oper, NULL, &eq_oper))
991 elog(ERROR, "could not find compatible hash operator for operator %u",
993 groupOperators[groupColPos++] = eq_oper;
997 * Since the Agg node is going to project anyway, we can give it the
998 * minimum output tlist, without any stuff we might have added to the
1001 plan = (Plan *) make_agg(root,
1002 build_relation_tlist(best_path->path.parent),
1014 List *sortList = NIL;
1016 /* Create an ORDER BY list to sort the input compatibly */
1018 foreach(l, in_operators)
1020 Oid in_oper = lfirst_oid(l);
1024 SortGroupClause *sortcl;
1026 sortop = get_ordering_op_for_equality_op(in_oper, false);
1027 if (!OidIsValid(sortop)) /* shouldn't happen */
1028 elog(ERROR, "could not find ordering operator for equality operator %u",
1032 * The Unique node will need equality operators. Normally these
1033 * are the same as the IN clause operators, but if those are
1034 * cross-type operators then the equality operators are the ones
1035 * for the IN clause operators' RHS datatype.
1037 eqop = get_equality_op_for_ordering_op(sortop, NULL);
1038 if (!OidIsValid(eqop)) /* shouldn't happen */
1039 elog(ERROR, "could not find equality operator for ordering operator %u",
1042 tle = get_tle_by_resno(subplan->targetlist,
1043 groupColIdx[groupColPos]);
1044 Assert(tle != NULL);
1046 sortcl = makeNode(SortGroupClause);
1047 sortcl->tleSortGroupRef = assignSortGroupRef(tle,
1048 subplan->targetlist);
1049 sortcl->eqop = eqop;
1050 sortcl->sortop = sortop;
1051 sortcl->nulls_first = false;
1052 sortcl->hashable = false; /* no need to make this accurate */
1053 sortList = lappend(sortList, sortcl);
1056 plan = (Plan *) make_sort_from_sortclauses(root, sortList, subplan);
1057 plan = (Plan *) make_unique(plan, sortList);
1060 /* Adjust output size estimate (other fields should be OK already) */
1061 plan->plan_rows = best_path->path.rows;
1067 /*****************************************************************************
1069 * BASE-RELATION SCAN METHODS
1071 *****************************************************************************/
1075 * create_seqscan_plan
1076 * Returns a seqscan plan for the base relation scanned by 'best_path'
1077 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1080 create_seqscan_plan(PlannerInfo *root, Path *best_path,
1081 List *tlist, List *scan_clauses)
1084 Index scan_relid = best_path->parent->relid;
1086 /* it should be a base rel... */
1087 Assert(scan_relid > 0);
1088 Assert(best_path->parent->rtekind == RTE_RELATION);
1090 /* Sort clauses into best execution order */
1091 scan_clauses = order_qual_clauses(root, scan_clauses);
1093 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1094 scan_clauses = extract_actual_clauses(scan_clauses, false);
1096 /* Replace any outer-relation variables with nestloop params */
1097 if (best_path->param_info)
1099 scan_clauses = (List *)
1100 replace_nestloop_params(root, (Node *) scan_clauses);
1103 scan_plan = make_seqscan(tlist,
1107 copy_path_costsize(&scan_plan->plan, best_path);
1113 * create_indexscan_plan
1114 * Returns an indexscan plan for the base relation scanned by 'best_path'
1115 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1117 * We use this for both plain IndexScans and IndexOnlyScans, because the
1118 * qual preprocessing work is the same for both. Note that the caller tells
1119 * us which to build --- we don't look at best_path->path.pathtype, because
1120 * create_bitmap_subplan needs to be able to override the prior decision.
1123 create_indexscan_plan(PlannerInfo *root,
1124 IndexPath *best_path,
1130 List *indexquals = best_path->indexquals;
1131 List *indexorderbys = best_path->indexorderbys;
1132 Index baserelid = best_path->path.parent->relid;
1133 Oid indexoid = best_path->indexinfo->indexoid;
1135 List *stripped_indexquals;
1136 List *fixed_indexquals;
1137 List *fixed_indexorderbys;
1140 /* it should be a base rel... */
1141 Assert(baserelid > 0);
1142 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1145 * Build "stripped" indexquals structure (no RestrictInfos) to pass to
1146 * executor as indexqualorig
1148 stripped_indexquals = get_actual_clauses(indexquals);
1151 * The executor needs a copy with the indexkey on the left of each clause
1152 * and with index Vars substituted for table ones.
1154 fixed_indexquals = fix_indexqual_references(root, best_path);
1157 * Likewise fix up index attr references in the ORDER BY expressions.
1159 fixed_indexorderbys = fix_indexorderby_references(root, best_path);
1162 * The qpqual list must contain all restrictions not automatically handled
1163 * by the index, other than pseudoconstant clauses which will be handled
1164 * by a separate gating plan node. All the predicates in the indexquals
1165 * will be checked (either by the index itself, or by nodeIndexscan.c),
1166 * but if there are any "special" operators involved then they must be
1167 * included in qpqual. The upshot is that qpqual must contain
1168 * scan_clauses minus whatever appears in indexquals.
1170 * In normal cases simple pointer equality checks will be enough to spot
1171 * duplicate RestrictInfos, so we try that first.
1173 * Another common case is that a scan_clauses entry is generated from the
1174 * same EquivalenceClass as some indexqual, and is therefore redundant
1175 * with it, though not equal. (This happens when indxpath.c prefers a
1176 * different derived equality than what generate_join_implied_equalities
1177 * picked for a parameterized scan's ppi_clauses.)
1179 * In some situations (particularly with OR'd index conditions) we may
1180 * have scan_clauses that are not equal to, but are logically implied by,
1181 * the index quals; so we also try a predicate_implied_by() check to see
1182 * if we can discard quals that way. (predicate_implied_by assumes its
1183 * first input contains only immutable functions, so we have to check
1186 * We can also discard quals that are implied by a partial index's
1187 * predicate, but only in a plain SELECT; when scanning a target relation
1188 * of UPDATE/DELETE/SELECT FOR UPDATE, we must leave such quals in the
1189 * plan so that they'll be properly rechecked by EvalPlanQual testing.
1192 foreach(l, scan_clauses)
1194 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1196 Assert(IsA(rinfo, RestrictInfo));
1197 if (rinfo->pseudoconstant)
1198 continue; /* we may drop pseudoconstants here */
1199 if (list_member_ptr(indexquals, rinfo))
1200 continue; /* simple duplicate */
1201 if (is_redundant_derived_clause(rinfo, indexquals))
1202 continue; /* derived from same EquivalenceClass */
1203 if (!contain_mutable_functions((Node *) rinfo->clause))
1205 List *clausel = list_make1(rinfo->clause);
1207 if (predicate_implied_by(clausel, indexquals))
1208 continue; /* provably implied by indexquals */
1209 if (best_path->indexinfo->indpred)
1211 if (baserelid != root->parse->resultRelation &&
1212 get_parse_rowmark(root->parse, baserelid) == NULL)
1213 if (predicate_implied_by(clausel,
1214 best_path->indexinfo->indpred))
1215 continue; /* implied by index predicate */
1218 qpqual = lappend(qpqual, rinfo);
1221 /* Sort clauses into best execution order */
1222 qpqual = order_qual_clauses(root, qpqual);
1224 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1225 qpqual = extract_actual_clauses(qpqual, false);
1228 * We have to replace any outer-relation variables with nestloop params in
1229 * the indexqualorig, qpqual, and indexorderbyorig expressions. A bit
1230 * annoying to have to do this separately from the processing in
1231 * fix_indexqual_references --- rethink this when generalizing the inner
1232 * indexscan support. But note we can't really do this earlier because
1233 * it'd break the comparisons to predicates above ... (or would it? Those
1234 * wouldn't have outer refs)
1236 if (best_path->path.param_info)
1238 stripped_indexquals = (List *)
1239 replace_nestloop_params(root, (Node *) stripped_indexquals);
1241 replace_nestloop_params(root, (Node *) qpqual);
1242 indexorderbys = (List *)
1243 replace_nestloop_params(root, (Node *) indexorderbys);
1246 /* Finally ready to build the plan node */
1248 scan_plan = (Scan *) make_indexonlyscan(tlist,
1253 fixed_indexorderbys,
1254 best_path->indexinfo->indextlist,
1255 best_path->indexscandir);
1257 scan_plan = (Scan *) make_indexscan(tlist,
1262 stripped_indexquals,
1263 fixed_indexorderbys,
1265 best_path->indexscandir);
1267 copy_path_costsize(&scan_plan->plan, &best_path->path);
1273 * create_bitmap_scan_plan
1274 * Returns a bitmap scan plan for the base relation scanned by 'best_path'
1275 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1277 static BitmapHeapScan *
1278 create_bitmap_scan_plan(PlannerInfo *root,
1279 BitmapHeapPath *best_path,
1283 Index baserelid = best_path->path.parent->relid;
1284 Plan *bitmapqualplan;
1285 List *bitmapqualorig;
1290 BitmapHeapScan *scan_plan;
1292 /* it should be a base rel... */
1293 Assert(baserelid > 0);
1294 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1296 /* Process the bitmapqual tree into a Plan tree and qual lists */
1297 bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
1298 &bitmapqualorig, &indexquals,
1302 * The qpqual list must contain all restrictions not automatically handled
1303 * by the index, other than pseudoconstant clauses which will be handled
1304 * by a separate gating plan node. All the predicates in the indexquals
1305 * will be checked (either by the index itself, or by
1306 * nodeBitmapHeapscan.c), but if there are any "special" operators
1307 * involved then they must be added to qpqual. The upshot is that qpqual
1308 * must contain scan_clauses minus whatever appears in indexquals.
1310 * This loop is similar to the comparable code in create_indexscan_plan(),
1311 * but with some differences because it has to compare the scan clauses to
1312 * stripped (no RestrictInfos) indexquals. See comments there for more
1315 * In normal cases simple equal() checks will be enough to spot duplicate
1316 * clauses, so we try that first. We next see if the scan clause is
1317 * redundant with any top-level indexqual by virtue of being generated
1318 * from the same EC. After that, try predicate_implied_by().
1320 * Unlike create_indexscan_plan(), we need take no special thought here
1321 * for partial index predicates; this is because the predicate conditions
1322 * are already listed in bitmapqualorig and indexquals. Bitmap scans have
1323 * to do it that way because predicate conditions need to be rechecked if
1324 * the scan becomes lossy, so they have to be included in bitmapqualorig.
1327 foreach(l, scan_clauses)
1329 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1330 Node *clause = (Node *) rinfo->clause;
1332 Assert(IsA(rinfo, RestrictInfo));
1333 if (rinfo->pseudoconstant)
1334 continue; /* we may drop pseudoconstants here */
1335 if (list_member(indexquals, clause))
1336 continue; /* simple duplicate */
1337 if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
1338 continue; /* derived from same EquivalenceClass */
1339 if (!contain_mutable_functions(clause))
1341 List *clausel = list_make1(clause);
1343 if (predicate_implied_by(clausel, indexquals))
1344 continue; /* provably implied by indexquals */
1346 qpqual = lappend(qpqual, rinfo);
1349 /* Sort clauses into best execution order */
1350 qpqual = order_qual_clauses(root, qpqual);
1352 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1353 qpqual = extract_actual_clauses(qpqual, false);
1356 * When dealing with special operators, we will at this point have
1357 * duplicate clauses in qpqual and bitmapqualorig. We may as well drop
1358 * 'em from bitmapqualorig, since there's no point in making the tests
1361 bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
1364 * We have to replace any outer-relation variables with nestloop params in
1365 * the qpqual and bitmapqualorig expressions. (This was already done for
1366 * expressions attached to plan nodes in the bitmapqualplan tree.)
1368 if (best_path->path.param_info)
1371 replace_nestloop_params(root, (Node *) qpqual);
1372 bitmapqualorig = (List *)
1373 replace_nestloop_params(root, (Node *) bitmapqualorig);
1376 /* Finally ready to build the plan node */
1377 scan_plan = make_bitmap_heapscan(tlist,
1383 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
1389 * Given a bitmapqual tree, generate the Plan tree that implements it
1391 * As byproducts, we also return in *qual and *indexqual the qual lists
1392 * (in implicit-AND form, without RestrictInfos) describing the original index
1393 * conditions and the generated indexqual conditions. (These are the same in
1394 * simple cases, but when special index operators are involved, the former
1395 * list includes the special conditions while the latter includes the actual
1396 * indexable conditions derived from them.) Both lists include partial-index
1397 * predicates, because we have to recheck predicates as well as index
1398 * conditions if the bitmap scan becomes lossy.
1400 * In addition, we return a list of EquivalenceClass pointers for all the
1401 * top-level indexquals that were possibly-redundantly derived from ECs.
1402 * This allows removal of scan_clauses that are redundant with such quals.
1403 * (We do not attempt to detect such redundancies for quals that are within
1404 * OR subtrees. This could be done in a less hacky way if we returned the
1405 * indexquals in RestrictInfo form, but that would be slower and still pretty
1406 * messy, since we'd have to build new RestrictInfos in many cases.)
1408 * Note: if you find yourself changing this, you probably need to change
1409 * make_restrictinfo_from_bitmapqual too.
1412 create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
1413 List **qual, List **indexqual, List **indexECs)
1417 if (IsA(bitmapqual, BitmapAndPath))
1419 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
1420 List *subplans = NIL;
1421 List *subquals = NIL;
1422 List *subindexquals = NIL;
1423 List *subindexECs = NIL;
1427 * There may well be redundant quals among the subplans, since a
1428 * top-level WHERE qual might have gotten used to form several
1429 * different index quals. We don't try exceedingly hard to eliminate
1430 * redundancies, but we do eliminate obvious duplicates by using
1431 * list_concat_unique.
1433 foreach(l, apath->bitmapquals)
1440 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1441 &subqual, &subindexqual,
1443 subplans = lappend(subplans, subplan);
1444 subquals = list_concat_unique(subquals, subqual);
1445 subindexquals = list_concat_unique(subindexquals, subindexqual);
1446 /* Duplicates in indexECs aren't worth getting rid of */
1447 subindexECs = list_concat(subindexECs, subindexEC);
1449 plan = (Plan *) make_bitmap_and(subplans);
1450 plan->startup_cost = apath->path.startup_cost;
1451 plan->total_cost = apath->path.total_cost;
1453 clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
1454 plan->plan_width = 0; /* meaningless */
1456 *indexqual = subindexquals;
1457 *indexECs = subindexECs;
1459 else if (IsA(bitmapqual, BitmapOrPath))
1461 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
1462 List *subplans = NIL;
1463 List *subquals = NIL;
1464 List *subindexquals = NIL;
1465 bool const_true_subqual = false;
1466 bool const_true_subindexqual = false;
1470 * Here, we only detect qual-free subplans. A qual-free subplan would
1471 * cause us to generate "... OR true ..." which we may as well reduce
1472 * to just "true". We do not try to eliminate redundant subclauses
1473 * because (a) it's not as likely as in the AND case, and (b) we might
1474 * well be working with hundreds or even thousands of OR conditions,
1475 * perhaps from a long IN list. The performance of list_append_unique
1476 * would be unacceptable.
1478 foreach(l, opath->bitmapquals)
1485 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1486 &subqual, &subindexqual,
1488 subplans = lappend(subplans, subplan);
1490 const_true_subqual = true;
1491 else if (!const_true_subqual)
1492 subquals = lappend(subquals,
1493 make_ands_explicit(subqual));
1494 if (subindexqual == NIL)
1495 const_true_subindexqual = true;
1496 else if (!const_true_subindexqual)
1497 subindexquals = lappend(subindexquals,
1498 make_ands_explicit(subindexqual));
1502 * In the presence of ScalarArrayOpExpr quals, we might have built
1503 * BitmapOrPaths with just one subpath; don't add an OR step.
1505 if (list_length(subplans) == 1)
1507 plan = (Plan *) linitial(subplans);
1511 plan = (Plan *) make_bitmap_or(subplans);
1512 plan->startup_cost = opath->path.startup_cost;
1513 plan->total_cost = opath->path.total_cost;
1515 clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
1516 plan->plan_width = 0; /* meaningless */
1520 * If there were constant-TRUE subquals, the OR reduces to constant
1521 * TRUE. Also, avoid generating one-element ORs, which could happen
1522 * due to redundancy elimination or ScalarArrayOpExpr quals.
1524 if (const_true_subqual)
1526 else if (list_length(subquals) <= 1)
1529 *qual = list_make1(make_orclause(subquals));
1530 if (const_true_subindexqual)
1532 else if (list_length(subindexquals) <= 1)
1533 *indexqual = subindexquals;
1535 *indexqual = list_make1(make_orclause(subindexquals));
1538 else if (IsA(bitmapqual, IndexPath))
1540 IndexPath *ipath = (IndexPath *) bitmapqual;
1545 /* Use the regular indexscan plan build machinery... */
1546 iscan = (IndexScan *) create_indexscan_plan(root, ipath,
1548 Assert(IsA(iscan, IndexScan));
1549 /* then convert to a bitmap indexscan */
1550 plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
1553 iscan->indexqualorig);
1554 plan->startup_cost = 0.0;
1555 plan->total_cost = ipath->indextotalcost;
1557 clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
1558 plan->plan_width = 0; /* meaningless */
1559 *qual = get_actual_clauses(ipath->indexclauses);
1560 *indexqual = get_actual_clauses(ipath->indexquals);
1561 foreach(l, ipath->indexinfo->indpred)
1563 Expr *pred = (Expr *) lfirst(l);
1566 * We know that the index predicate must have been implied by the
1567 * query condition as a whole, but it may or may not be implied by
1568 * the conditions that got pushed into the bitmapqual. Avoid
1569 * generating redundant conditions.
1571 if (!predicate_implied_by(list_make1(pred), ipath->indexclauses))
1573 *qual = lappend(*qual, pred);
1574 *indexqual = lappend(*indexqual, pred);
1578 foreach(l, ipath->indexquals)
1580 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1582 if (rinfo->parent_ec)
1583 subindexECs = lappend(subindexECs, rinfo->parent_ec);
1585 *indexECs = subindexECs;
1589 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
1590 plan = NULL; /* keep compiler quiet */
1597 * create_tidscan_plan
1598 * Returns a tidscan plan for the base relation scanned by 'best_path'
1599 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1602 create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
1603 List *tlist, List *scan_clauses)
1606 Index scan_relid = best_path->path.parent->relid;
1607 List *tidquals = best_path->tidquals;
1610 /* it should be a base rel... */
1611 Assert(scan_relid > 0);
1612 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1614 /* Sort clauses into best execution order */
1615 scan_clauses = order_qual_clauses(root, scan_clauses);
1617 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1618 scan_clauses = extract_actual_clauses(scan_clauses, false);
1620 /* Replace any outer-relation variables with nestloop params */
1621 if (best_path->path.param_info)
1624 replace_nestloop_params(root, (Node *) tidquals);
1625 scan_clauses = (List *)
1626 replace_nestloop_params(root, (Node *) scan_clauses);
1630 * Remove any clauses that are TID quals. This is a bit tricky since the
1631 * tidquals list has implicit OR semantics.
1633 ortidquals = tidquals;
1634 if (list_length(ortidquals) > 1)
1635 ortidquals = list_make1(make_orclause(ortidquals));
1636 scan_clauses = list_difference(scan_clauses, ortidquals);
1638 scan_plan = make_tidscan(tlist,
1643 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
1649 * create_subqueryscan_plan
1650 * Returns a subqueryscan plan for the base relation scanned by 'best_path'
1651 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1653 static SubqueryScan *
1654 create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
1655 List *tlist, List *scan_clauses)
1657 SubqueryScan *scan_plan;
1658 Index scan_relid = best_path->parent->relid;
1660 /* it should be a subquery base rel... */
1661 Assert(scan_relid > 0);
1662 Assert(best_path->parent->rtekind == RTE_SUBQUERY);
1664 /* Sort clauses into best execution order */
1665 scan_clauses = order_qual_clauses(root, scan_clauses);
1667 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1668 scan_clauses = extract_actual_clauses(scan_clauses, false);
1670 /* Replace any outer-relation variables with nestloop params */
1671 if (best_path->param_info)
1673 scan_clauses = (List *)
1674 replace_nestloop_params(root, (Node *) scan_clauses);
1675 process_subquery_nestloop_params(root,
1676 best_path->parent->subplan_params);
1679 scan_plan = make_subqueryscan(tlist,
1682 best_path->parent->subplan);
1684 copy_path_costsize(&scan_plan->scan.plan, best_path);
1690 * create_functionscan_plan
1691 * Returns a functionscan plan for the base relation scanned by 'best_path'
1692 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1694 static FunctionScan *
1695 create_functionscan_plan(PlannerInfo *root, Path *best_path,
1696 List *tlist, List *scan_clauses)
1698 FunctionScan *scan_plan;
1699 Index scan_relid = best_path->parent->relid;
1703 /* it should be a function base rel... */
1704 Assert(scan_relid > 0);
1705 rte = planner_rt_fetch(scan_relid, root);
1706 Assert(rte->rtekind == RTE_FUNCTION);
1707 funcexpr = rte->funcexpr;
1709 /* Sort clauses into best execution order */
1710 scan_clauses = order_qual_clauses(root, scan_clauses);
1712 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1713 scan_clauses = extract_actual_clauses(scan_clauses, false);
1715 /* Replace any outer-relation variables with nestloop params */
1716 if (best_path->param_info)
1718 scan_clauses = (List *)
1719 replace_nestloop_params(root, (Node *) scan_clauses);
1720 /* The func expression itself could contain nestloop params, too */
1721 funcexpr = replace_nestloop_params(root, funcexpr);
1724 scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
1726 rte->eref->colnames,
1728 rte->funccoltypmods,
1729 rte->funccolcollations);
1731 copy_path_costsize(&scan_plan->scan.plan, best_path);
1737 * create_valuesscan_plan
1738 * Returns a valuesscan plan for the base relation scanned by 'best_path'
1739 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1742 create_valuesscan_plan(PlannerInfo *root, Path *best_path,
1743 List *tlist, List *scan_clauses)
1745 ValuesScan *scan_plan;
1746 Index scan_relid = best_path->parent->relid;
1750 /* it should be a values base rel... */
1751 Assert(scan_relid > 0);
1752 rte = planner_rt_fetch(scan_relid, root);
1753 Assert(rte->rtekind == RTE_VALUES);
1754 values_lists = rte->values_lists;
1756 /* Sort clauses into best execution order */
1757 scan_clauses = order_qual_clauses(root, scan_clauses);
1759 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1760 scan_clauses = extract_actual_clauses(scan_clauses, false);
1762 /* Replace any outer-relation variables with nestloop params */
1763 if (best_path->param_info)
1765 scan_clauses = (List *)
1766 replace_nestloop_params(root, (Node *) scan_clauses);
1767 /* The values lists could contain nestloop params, too */
1768 values_lists = (List *)
1769 replace_nestloop_params(root, (Node *) values_lists);
1772 scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid,
1775 copy_path_costsize(&scan_plan->scan.plan, best_path);
1781 * create_ctescan_plan
1782 * Returns a ctescan plan for the base relation scanned by 'best_path'
1783 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1786 create_ctescan_plan(PlannerInfo *root, Path *best_path,
1787 List *tlist, List *scan_clauses)
1790 Index scan_relid = best_path->parent->relid;
1792 SubPlan *ctesplan = NULL;
1795 PlannerInfo *cteroot;
1800 Assert(scan_relid > 0);
1801 rte = planner_rt_fetch(scan_relid, root);
1802 Assert(rte->rtekind == RTE_CTE);
1803 Assert(!rte->self_reference);
1806 * Find the referenced CTE, and locate the SubPlan previously made for it.
1808 levelsup = rte->ctelevelsup;
1810 while (levelsup-- > 0)
1812 cteroot = cteroot->parent_root;
1813 if (!cteroot) /* shouldn't happen */
1814 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
1818 * Note: cte_plan_ids can be shorter than cteList, if we are still working
1819 * on planning the CTEs (ie, this is a side-reference from another CTE).
1820 * So we mustn't use forboth here.
1823 foreach(lc, cteroot->parse->cteList)
1825 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
1827 if (strcmp(cte->ctename, rte->ctename) == 0)
1831 if (lc == NULL) /* shouldn't happen */
1832 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
1833 if (ndx >= list_length(cteroot->cte_plan_ids))
1834 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
1835 plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
1836 Assert(plan_id > 0);
1837 foreach(lc, cteroot->init_plans)
1839 ctesplan = (SubPlan *) lfirst(lc);
1840 if (ctesplan->plan_id == plan_id)
1843 if (lc == NULL) /* shouldn't happen */
1844 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
1847 * We need the CTE param ID, which is the sole member of the SubPlan's
1850 cte_param_id = linitial_int(ctesplan->setParam);
1852 /* Sort clauses into best execution order */
1853 scan_clauses = order_qual_clauses(root, scan_clauses);
1855 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1856 scan_clauses = extract_actual_clauses(scan_clauses, false);
1858 /* Replace any outer-relation variables with nestloop params */
1859 if (best_path->param_info)
1861 scan_clauses = (List *)
1862 replace_nestloop_params(root, (Node *) scan_clauses);
1865 scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
1866 plan_id, cte_param_id);
1868 copy_path_costsize(&scan_plan->scan.plan, best_path);
1874 * create_worktablescan_plan
1875 * Returns a worktablescan plan for the base relation scanned by 'best_path'
1876 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1878 static WorkTableScan *
1879 create_worktablescan_plan(PlannerInfo *root, Path *best_path,
1880 List *tlist, List *scan_clauses)
1882 WorkTableScan *scan_plan;
1883 Index scan_relid = best_path->parent->relid;
1886 PlannerInfo *cteroot;
1888 Assert(scan_relid > 0);
1889 rte = planner_rt_fetch(scan_relid, root);
1890 Assert(rte->rtekind == RTE_CTE);
1891 Assert(rte->self_reference);
1894 * We need to find the worktable param ID, which is in the plan level
1895 * that's processing the recursive UNION, which is one level *below* where
1896 * the CTE comes from.
1898 levelsup = rte->ctelevelsup;
1899 if (levelsup == 0) /* shouldn't happen */
1900 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
1903 while (levelsup-- > 0)
1905 cteroot = cteroot->parent_root;
1906 if (!cteroot) /* shouldn't happen */
1907 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
1909 if (cteroot->wt_param_id < 0) /* shouldn't happen */
1910 elog(ERROR, "could not find param ID for CTE \"%s\"", rte->ctename);
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);
1925 scan_plan = make_worktablescan(tlist, scan_clauses, scan_relid,
1926 cteroot->wt_param_id);
1928 copy_path_costsize(&scan_plan->scan.plan, best_path);
1934 * create_foreignscan_plan
1935 * Returns a foreignscan plan for the base relation scanned by 'best_path'
1936 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1938 static ForeignScan *
1939 create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
1940 List *tlist, List *scan_clauses)
1942 ForeignScan *scan_plan;
1943 RelOptInfo *rel = best_path->path.parent;
1944 Index scan_relid = rel->relid;
1948 /* it should be a base rel... */
1949 Assert(scan_relid > 0);
1950 Assert(rel->rtekind == RTE_RELATION);
1951 rte = planner_rt_fetch(scan_relid, root);
1952 Assert(rte->rtekind == RTE_RELATION);
1955 * Sort clauses into best execution order. We do this first since the FDW
1956 * might have more info than we do and wish to adjust the ordering.
1958 scan_clauses = order_qual_clauses(root, scan_clauses);
1961 * Let the FDW perform its processing on the restriction clauses and
1962 * generate the plan node. Note that the FDW might remove restriction
1963 * clauses that it intends to execute remotely, or even add more (if it
1964 * has selected some join clauses for remote use but also wants them
1965 * rechecked locally).
1967 scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rte->relid,
1969 tlist, scan_clauses);
1971 /* Copy cost data from Path to Plan; no need to make FDW do this */
1972 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
1975 * Replace any outer-relation variables with nestloop params in the qual
1976 * and fdw_exprs expressions. We do this last so that the FDW doesn't
1977 * have to be involved. (Note that parts of fdw_exprs could have come
1978 * from join clauses, so doing this beforehand on the scan_clauses
1981 if (best_path->path.param_info)
1983 scan_plan->scan.plan.qual = (List *)
1984 replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
1985 scan_plan->fdw_exprs = (List *)
1986 replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
1990 * Detect whether any system columns are requested from rel. This is a
1991 * bit of a kluge and might go away someday, so we intentionally leave it
1992 * out of the API presented to FDWs.
1994 scan_plan->fsSystemCol = false;
1995 for (i = rel->min_attr; i < 0; i++)
1997 if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
1999 scan_plan->fsSystemCol = true;
2008 /*****************************************************************************
2012 *****************************************************************************/
2015 create_nestloop_plan(PlannerInfo *root,
2016 NestPath *best_path,
2020 NestLoop *join_plan;
2021 List *tlist = build_relation_tlist(best_path->path.parent);
2022 List *joinrestrictclauses = best_path->joinrestrictinfo;
2031 /* Sort join qual clauses into best execution order */
2032 joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
2034 /* Get the join qual clauses (in plain expression form) */
2035 /* Any pseudoconstant clauses are ignored here */
2036 if (IS_OUTER_JOIN(best_path->jointype))
2038 extract_actual_join_clauses(joinrestrictclauses,
2039 &joinclauses, &otherclauses);
2043 /* We can treat all clauses alike for an inner join */
2044 joinclauses = extract_actual_clauses(joinrestrictclauses, false);
2048 /* Replace any outer-relation variables with nestloop params */
2049 if (best_path->path.param_info)
2051 joinclauses = (List *)
2052 replace_nestloop_params(root, (Node *) joinclauses);
2053 otherclauses = (List *)
2054 replace_nestloop_params(root, (Node *) otherclauses);
2058 * Identify any nestloop parameters that should be supplied by this join
2059 * node, and move them from root->curOuterParams to the nestParams list.
2061 outerrelids = best_path->outerjoinpath->parent->relids;
2064 for (cell = list_head(root->curOuterParams); cell; cell = next)
2066 NestLoopParam *nlp = (NestLoopParam *) lfirst(cell);
2069 if (IsA(nlp->paramval, Var) &&
2070 bms_is_member(nlp->paramval->varno, outerrelids))
2072 root->curOuterParams = list_delete_cell(root->curOuterParams,
2074 nestParams = lappend(nestParams, nlp);
2076 else if (IsA(nlp->paramval, PlaceHolderVar) &&
2077 bms_overlap(((PlaceHolderVar *) nlp->paramval)->phrels,
2079 bms_is_subset(find_placeholder_info(root,
2080 (PlaceHolderVar *) nlp->paramval,
2084 root->curOuterParams = list_delete_cell(root->curOuterParams,
2086 nestParams = lappend(nestParams, nlp);
2092 join_plan = make_nestloop(tlist,
2098 best_path->jointype);
2100 copy_path_costsize(&join_plan->join.plan, &best_path->path);
2106 create_mergejoin_plan(PlannerInfo *root,
2107 MergePath *best_path,
2111 List *tlist = build_relation_tlist(best_path->jpath.path.parent);
2115 List *outerpathkeys;
2116 List *innerpathkeys;
2119 Oid *mergecollations;
2120 int *mergestrategies;
2121 bool *mergenullsfirst;
2122 MergeJoin *join_plan;
2128 /* Sort join qual clauses into best execution order */
2129 /* NB: do NOT reorder the mergeclauses */
2130 joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
2132 /* Get the join qual clauses (in plain expression form) */
2133 /* Any pseudoconstant clauses are ignored here */
2134 if (IS_OUTER_JOIN(best_path->jpath.jointype))
2136 extract_actual_join_clauses(joinclauses,
2137 &joinclauses, &otherclauses);
2141 /* We can treat all clauses alike for an inner join */
2142 joinclauses = extract_actual_clauses(joinclauses, false);
2147 * Remove the mergeclauses from the list of join qual clauses, leaving the
2148 * list of quals that must be checked as qpquals.
2150 mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
2151 joinclauses = list_difference(joinclauses, mergeclauses);
2154 * Replace any outer-relation variables with nestloop params. There
2155 * should not be any in the mergeclauses.
2157 if (best_path->jpath.path.param_info)
2159 joinclauses = (List *)
2160 replace_nestloop_params(root, (Node *) joinclauses);
2161 otherclauses = (List *)
2162 replace_nestloop_params(root, (Node *) otherclauses);
2166 * Rearrange mergeclauses, if needed, so that the outer variable is always
2167 * on the left; mark the mergeclause restrictinfos with correct
2168 * outer_is_left status.
2170 mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
2171 best_path->jpath.outerjoinpath->parent->relids);
2174 * Create explicit sort nodes for the outer and inner paths if necessary.
2175 * Make sure there are no excess columns in the inputs if sorting.
2177 if (best_path->outersortkeys)
2179 disuse_physical_tlist(outer_plan, best_path->jpath.outerjoinpath);
2180 outer_plan = (Plan *)
2181 make_sort_from_pathkeys(root,
2183 best_path->outersortkeys,
2185 outerpathkeys = best_path->outersortkeys;
2188 outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
2190 if (best_path->innersortkeys)
2192 disuse_physical_tlist(inner_plan, best_path->jpath.innerjoinpath);
2193 inner_plan = (Plan *)
2194 make_sort_from_pathkeys(root,
2196 best_path->innersortkeys,
2198 innerpathkeys = best_path->innersortkeys;
2201 innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
2204 * If specified, add a materialize node to shield the inner plan from the
2205 * need to handle mark/restore.
2207 if (best_path->materialize_inner)
2209 Plan *matplan = (Plan *) make_material(inner_plan);
2212 * We assume the materialize will not spill to disk, and therefore
2213 * charge just cpu_operator_cost per tuple. (Keep this estimate in
2214 * sync with final_cost_mergejoin.)
2216 copy_plan_costsize(matplan, inner_plan);
2217 matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
2219 inner_plan = matplan;
2223 * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
2224 * executor. The information is in the pathkeys for the two inputs, but
2225 * we need to be careful about the possibility of mergeclauses sharing a
2226 * pathkey (compare find_mergeclauses_for_pathkeys()).
2228 nClauses = list_length(mergeclauses);
2229 Assert(nClauses == list_length(best_path->path_mergeclauses));
2230 mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
2231 mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
2232 mergestrategies = (int *) palloc(nClauses * sizeof(int));
2233 mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
2235 lop = list_head(outerpathkeys);
2236 lip = list_head(innerpathkeys);
2238 foreach(lc, best_path->path_mergeclauses)
2240 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2241 EquivalenceClass *oeclass;
2242 EquivalenceClass *ieclass;
2245 EquivalenceClass *opeclass;
2246 EquivalenceClass *ipeclass;
2249 /* fetch outer/inner eclass from mergeclause */
2250 Assert(IsA(rinfo, RestrictInfo));
2251 if (rinfo->outer_is_left)
2253 oeclass = rinfo->left_ec;
2254 ieclass = rinfo->right_ec;
2258 oeclass = rinfo->right_ec;
2259 ieclass = rinfo->left_ec;
2261 Assert(oeclass != NULL);
2262 Assert(ieclass != NULL);
2265 * For debugging purposes, we check that the eclasses match the paths'
2266 * pathkeys. In typical cases the merge clauses are one-to-one with
2267 * the pathkeys, but when dealing with partially redundant query
2268 * conditions, we might have clauses that re-reference earlier path
2269 * keys. The case that we need to reject is where a pathkey is
2270 * entirely skipped over.
2272 * lop and lip reference the first as-yet-unused pathkey elements;
2273 * it's okay to match them, or any element before them. If they're
2274 * NULL then we have found all pathkey elements to be used.
2278 opathkey = (PathKey *) lfirst(lop);
2279 opeclass = opathkey->pk_eclass;
2280 if (oeclass == opeclass)
2282 /* fast path for typical case */
2287 /* redundant clauses ... must match something before lop */
2288 foreach(l2, outerpathkeys)
2292 opathkey = (PathKey *) lfirst(l2);
2293 opeclass = opathkey->pk_eclass;
2294 if (oeclass == opeclass)
2297 if (oeclass != opeclass)
2298 elog(ERROR, "outer pathkeys do not match mergeclauses");
2303 /* redundant clauses ... must match some already-used pathkey */
2306 foreach(l2, outerpathkeys)
2308 opathkey = (PathKey *) lfirst(l2);
2309 opeclass = opathkey->pk_eclass;
2310 if (oeclass == opeclass)
2314 elog(ERROR, "outer pathkeys do not match mergeclauses");
2319 ipathkey = (PathKey *) lfirst(lip);
2320 ipeclass = ipathkey->pk_eclass;
2321 if (ieclass == ipeclass)
2323 /* fast path for typical case */
2328 /* redundant clauses ... must match something before lip */
2329 foreach(l2, innerpathkeys)
2333 ipathkey = (PathKey *) lfirst(l2);
2334 ipeclass = ipathkey->pk_eclass;
2335 if (ieclass == ipeclass)
2338 if (ieclass != ipeclass)
2339 elog(ERROR, "inner pathkeys do not match mergeclauses");
2344 /* redundant clauses ... must match some already-used pathkey */
2347 foreach(l2, innerpathkeys)
2349 ipathkey = (PathKey *) lfirst(l2);
2350 ipeclass = ipathkey->pk_eclass;
2351 if (ieclass == ipeclass)
2355 elog(ERROR, "inner pathkeys do not match mergeclauses");
2358 /* pathkeys should match each other too (more debugging) */
2359 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
2360 opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
2361 opathkey->pk_strategy != ipathkey->pk_strategy ||
2362 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
2363 elog(ERROR, "left and right pathkeys do not match in mergejoin");
2365 /* OK, save info for executor */
2366 mergefamilies[i] = opathkey->pk_opfamily;
2367 mergecollations[i] = opathkey->pk_eclass->ec_collation;
2368 mergestrategies[i] = opathkey->pk_strategy;
2369 mergenullsfirst[i] = opathkey->pk_nulls_first;
2374 * Note: it is not an error if we have additional pathkey elements (i.e.,
2375 * lop or lip isn't NULL here). The input paths might be better-sorted
2376 * than we need for the current mergejoin.
2380 * Now we can build the mergejoin node.
2382 join_plan = make_mergejoin(tlist,
2392 best_path->jpath.jointype);
2394 /* Costs of sort and material steps are included in path cost already */
2395 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
2401 create_hashjoin_plan(PlannerInfo *root,
2402 HashPath *best_path,
2406 List *tlist = build_relation_tlist(best_path->jpath.path.parent);
2410 Oid skewTable = InvalidOid;
2411 AttrNumber skewColumn = InvalidAttrNumber;
2412 bool skewInherit = false;
2413 Oid skewColType = InvalidOid;
2414 int32 skewColTypmod = -1;
2415 HashJoin *join_plan;
2418 /* Sort join qual clauses into best execution order */
2419 joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
2420 /* There's no point in sorting the hash clauses ... */
2422 /* Get the join qual clauses (in plain expression form) */
2423 /* Any pseudoconstant clauses are ignored here */
2424 if (IS_OUTER_JOIN(best_path->jpath.jointype))
2426 extract_actual_join_clauses(joinclauses,
2427 &joinclauses, &otherclauses);
2431 /* We can treat all clauses alike for an inner join */
2432 joinclauses = extract_actual_clauses(joinclauses, false);
2437 * Remove the hashclauses from the list of join qual clauses, leaving the
2438 * list of quals that must be checked as qpquals.
2440 hashclauses = get_actual_clauses(best_path->path_hashclauses);
2441 joinclauses = list_difference(joinclauses, hashclauses);
2444 * Replace any outer-relation variables with nestloop params. There
2445 * should not be any in the hashclauses.
2447 if (best_path->jpath.path.param_info)
2449 joinclauses = (List *)
2450 replace_nestloop_params(root, (Node *) joinclauses);
2451 otherclauses = (List *)
2452 replace_nestloop_params(root, (Node *) otherclauses);
2456 * Rearrange hashclauses, if needed, so that the outer variable is always
2459 hashclauses = get_switched_clauses(best_path->path_hashclauses,
2460 best_path->jpath.outerjoinpath->parent->relids);
2462 /* We don't want any excess columns in the hashed tuples */
2463 disuse_physical_tlist(inner_plan, best_path->jpath.innerjoinpath);
2465 /* If we expect batching, suppress excess columns in outer tuples too */
2466 if (best_path->num_batches > 1)
2467 disuse_physical_tlist(outer_plan, best_path->jpath.outerjoinpath);
2470 * If there is a single join clause and we can identify the outer variable
2471 * as a simple column reference, supply its identity for possible use in
2472 * skew optimization. (Note: in principle we could do skew optimization
2473 * with multiple join clauses, but we'd have to be able to determine the
2474 * most common combinations of outer values, which we don't currently have
2475 * enough stats for.)
2477 if (list_length(hashclauses) == 1)
2479 OpExpr *clause = (OpExpr *) linitial(hashclauses);
2482 Assert(is_opclause(clause));
2483 node = (Node *) linitial(clause->args);
2484 if (IsA(node, RelabelType))
2485 node = (Node *) ((RelabelType *) node)->arg;
2488 Var *var = (Var *) node;
2491 rte = root->simple_rte_array[var->varno];
2492 if (rte->rtekind == RTE_RELATION)
2494 skewTable = rte->relid;
2495 skewColumn = var->varattno;
2496 skewInherit = rte->inh;
2497 skewColType = var->vartype;
2498 skewColTypmod = var->vartypmod;
2504 * Build the hash node and hash join node.
2506 hash_plan = make_hash(inner_plan,
2512 join_plan = make_hashjoin(tlist,
2518 best_path->jpath.jointype);
2520 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
2526 /*****************************************************************************
2528 * SUPPORTING ROUTINES
2530 *****************************************************************************/
2533 * replace_nestloop_params
2534 * Replace outer-relation Vars and PlaceHolderVars in the given expression
2535 * with nestloop Params
2537 * All Vars and PlaceHolderVars belonging to the relation(s) identified by
2538 * root->curOuterRels are replaced by Params, and entries are added to
2539 * root->curOuterParams if not already present.
2542 replace_nestloop_params(PlannerInfo *root, Node *expr)
2544 /* No setup needed for tree walk, so away we go */
2545 return replace_nestloop_params_mutator(expr, root);
2549 replace_nestloop_params_mutator(Node *node, PlannerInfo *root)
2555 Var *var = (Var *) node;
2560 /* Upper-level Vars should be long gone at this point */
2561 Assert(var->varlevelsup == 0);
2562 /* If not to be replaced, we can just return the Var unmodified */
2563 if (!bms_is_member(var->varno, root->curOuterRels))
2565 /* Create a Param representing the Var */
2566 param = assign_nestloop_param_var(root, var);
2567 /* Is this param already listed in root->curOuterParams? */
2568 foreach(lc, root->curOuterParams)
2570 nlp = (NestLoopParam *) lfirst(lc);
2571 if (nlp->paramno == param->paramid)
2573 Assert(equal(var, nlp->paramval));
2574 /* Present, so we can just return the Param */
2575 return (Node *) param;
2579 nlp = makeNode(NestLoopParam);
2580 nlp->paramno = param->paramid;
2581 nlp->paramval = var;
2582 root->curOuterParams = lappend(root->curOuterParams, nlp);
2583 /* And return the replacement Param */
2584 return (Node *) param;
2586 if (IsA(node, PlaceHolderVar))
2588 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2593 /* Upper-level PlaceHolderVars should be long gone at this point */
2594 Assert(phv->phlevelsup == 0);
2597 * If not to be replaced, just return the PlaceHolderVar unmodified.
2598 * We use bms_overlap as a cheap/quick test to see if the PHV might be
2599 * evaluated in the outer rels, and then grab its PlaceHolderInfo to
2602 if (!bms_overlap(phv->phrels, root->curOuterRels))
2604 if (!bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
2605 root->curOuterRels))
2607 /* Create a Param representing the PlaceHolderVar */
2608 param = assign_nestloop_param_placeholdervar(root, phv);
2609 /* Is this param already listed in root->curOuterParams? */
2610 foreach(lc, root->curOuterParams)
2612 nlp = (NestLoopParam *) lfirst(lc);
2613 if (nlp->paramno == param->paramid)
2615 Assert(equal(phv, nlp->paramval));
2616 /* Present, so we can just return the Param */
2617 return (Node *) param;
2621 nlp = makeNode(NestLoopParam);
2622 nlp->paramno = param->paramid;
2623 nlp->paramval = (Var *) phv;
2624 root->curOuterParams = lappend(root->curOuterParams, nlp);
2625 /* And return the replacement Param */
2626 return (Node *) param;
2628 return expression_tree_mutator(node,
2629 replace_nestloop_params_mutator,
2634 * process_subquery_nestloop_params
2635 * Handle params of a parameterized subquery that need to be fed
2636 * from an outer nestloop.
2638 * Currently, that would be *all* params that a subquery in FROM has demanded
2639 * from the current query level, since they must be LATERAL references.
2641 * The subplan's references to the outer variables are already represented
2642 * as PARAM_EXEC Params, so we need not modify the subplan here. What we
2643 * do need to do is add entries to root->curOuterParams to signal the parent
2644 * nestloop plan node that it must provide these values.
2647 process_subquery_nestloop_params(PlannerInfo *root, List *subplan_params)
2651 foreach(ppl, subplan_params)
2653 PlannerParamItem *pitem = (PlannerParamItem *) lfirst(ppl);
2655 if (IsA(pitem->item, Var))
2657 Var *var = (Var *) pitem->item;
2661 /* If not from a nestloop outer rel, complain */
2662 if (!bms_is_member(var->varno, root->curOuterRels))
2663 elog(ERROR, "non-LATERAL parameter required by subquery");
2664 /* Is this param already listed in root->curOuterParams? */
2665 foreach(lc, root->curOuterParams)
2667 nlp = (NestLoopParam *) lfirst(lc);
2668 if (nlp->paramno == pitem->paramId)
2670 Assert(equal(var, nlp->paramval));
2671 /* Present, so nothing to do */
2678 nlp = makeNode(NestLoopParam);
2679 nlp->paramno = pitem->paramId;
2680 nlp->paramval = copyObject(var);
2681 root->curOuterParams = lappend(root->curOuterParams, nlp);
2684 else if (IsA(pitem->item, PlaceHolderVar))
2686 PlaceHolderVar *phv = (PlaceHolderVar *) pitem->item;
2690 /* If not from a nestloop outer rel, complain */
2691 if (!bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
2692 root->curOuterRels))
2693 elog(ERROR, "non-LATERAL parameter required by subquery");
2694 /* Is this param already listed in root->curOuterParams? */
2695 foreach(lc, root->curOuterParams)
2697 nlp = (NestLoopParam *) lfirst(lc);
2698 if (nlp->paramno == pitem->paramId)
2700 Assert(equal(phv, nlp->paramval));
2701 /* Present, so nothing to do */
2708 nlp = makeNode(NestLoopParam);
2709 nlp->paramno = pitem->paramId;
2710 nlp->paramval = copyObject(phv);
2711 root->curOuterParams = lappend(root->curOuterParams, nlp);
2715 elog(ERROR, "unexpected type of subquery parameter");
2720 * fix_indexqual_references
2721 * Adjust indexqual clauses to the form the executor's indexqual
2724 * We have four tasks here:
2725 * * Remove RestrictInfo nodes from the input clauses.
2726 * * Replace any outer-relation Var or PHV nodes with nestloop Params.
2727 * (XXX eventually, that responsibility should go elsewhere?)
2728 * * Index keys must be represented by Var nodes with varattno set to the
2729 * index's attribute number, not the attribute number in the original rel.
2730 * * If the index key is on the right, commute the clause to put it on the
2733 * The result is a modified copy of the path's indexquals list --- the
2734 * original is not changed. Note also that the copy shares no substructure
2735 * with the original; this is needed in case there is a subplan in it (we need
2736 * two separate copies of the subplan tree, or things will go awry).
2739 fix_indexqual_references(PlannerInfo *root, IndexPath *index_path)
2741 IndexOptInfo *index = index_path->indexinfo;
2742 List *fixed_indexquals;
2746 fixed_indexquals = NIL;
2748 forboth(lcc, index_path->indexquals, lci, index_path->indexqualcols)
2750 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcc);
2751 int indexcol = lfirst_int(lci);
2754 Assert(IsA(rinfo, RestrictInfo));
2757 * Replace any outer-relation variables with nestloop params.
2759 * This also makes a copy of the clause, so it's safe to modify it
2762 clause = replace_nestloop_params(root, (Node *) rinfo->clause);
2764 if (IsA(clause, OpExpr))
2766 OpExpr *op = (OpExpr *) clause;
2768 if (list_length(op->args) != 2)
2769 elog(ERROR, "indexqual clause is not binary opclause");
2772 * Check to see if the indexkey is on the right; if so, commute
2773 * the clause. The indexkey should be the side that refers to
2774 * (only) the base relation.
2776 if (!bms_equal(rinfo->left_relids, index->rel->relids))
2780 * Now replace the indexkey expression with an index Var.
2782 linitial(op->args) = fix_indexqual_operand(linitial(op->args),
2786 else if (IsA(clause, RowCompareExpr))
2788 RowCompareExpr *rc = (RowCompareExpr *) clause;
2796 * Re-discover which index columns are used in the rowcompare.
2798 newrc = adjust_rowcompare_for_index(rc,
2805 * Trouble if adjust_rowcompare_for_index thought the
2806 * RowCompareExpr didn't match the index as-is; the clause should
2807 * have gone through that routine already.
2809 if (newrc != (Expr *) rc)
2810 elog(ERROR, "inconsistent results from adjust_rowcompare_for_index");
2813 * Check to see if the indexkey is on the right; if so, commute
2817 CommuteRowCompareExpr(rc);
2820 * Now replace the indexkey expressions with index Vars.
2822 Assert(list_length(rc->largs) == list_length(indexcolnos));
2823 forboth(lca, rc->largs, lcai, indexcolnos)
2825 lfirst(lca) = fix_indexqual_operand(lfirst(lca),
2830 else if (IsA(clause, ScalarArrayOpExpr))
2832 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
2834 /* Never need to commute... */
2836 /* Replace the indexkey expression with an index Var. */
2837 linitial(saop->args) = fix_indexqual_operand(linitial(saop->args),
2841 else if (IsA(clause, NullTest))
2843 NullTest *nt = (NullTest *) clause;
2845 /* Replace the indexkey expression with an index Var. */
2846 nt->arg = (Expr *) fix_indexqual_operand((Node *) nt->arg,
2851 elog(ERROR, "unsupported indexqual type: %d",
2852 (int) nodeTag(clause));
2854 fixed_indexquals = lappend(fixed_indexquals, clause);
2857 return fixed_indexquals;
2861 * fix_indexorderby_references
2862 * Adjust indexorderby clauses to the form the executor's index
2865 * This is a simplified version of fix_indexqual_references. The input does
2866 * not have RestrictInfo nodes, and we assume that indxpath.c already
2867 * commuted the clauses to put the index keys on the left. Also, we don't
2868 * bother to support any cases except simple OpExprs, since nothing else
2869 * is allowed for ordering operators.
2872 fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path)
2874 IndexOptInfo *index = index_path->indexinfo;
2875 List *fixed_indexorderbys;
2879 fixed_indexorderbys = NIL;
2881 forboth(lcc, index_path->indexorderbys, lci, index_path->indexorderbycols)
2883 Node *clause = (Node *) lfirst(lcc);
2884 int indexcol = lfirst_int(lci);
2887 * Replace any outer-relation variables with nestloop params.
2889 * This also makes a copy of the clause, so it's safe to modify it
2892 clause = replace_nestloop_params(root, clause);
2894 if (IsA(clause, OpExpr))
2896 OpExpr *op = (OpExpr *) clause;
2898 if (list_length(op->args) != 2)
2899 elog(ERROR, "indexorderby clause is not binary opclause");
2902 * Now replace the indexkey expression with an index Var.
2904 linitial(op->args) = fix_indexqual_operand(linitial(op->args),
2909 elog(ERROR, "unsupported indexorderby type: %d",
2910 (int) nodeTag(clause));
2912 fixed_indexorderbys = lappend(fixed_indexorderbys, clause);
2915 return fixed_indexorderbys;
2919 * fix_indexqual_operand
2920 * Convert an indexqual expression to a Var referencing the index column.
2922 * We represent index keys by Var nodes having varno == INDEX_VAR and varattno
2923 * equal to the index's attribute number (index column position).
2925 * Most of the code here is just for sanity cross-checking that the given
2926 * expression actually matches the index column it's claimed to.
2929 fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol)
2933 ListCell *indexpr_item;
2936 * Remove any binary-compatible relabeling of the indexkey
2938 if (IsA(node, RelabelType))
2939 node = (Node *) ((RelabelType *) node)->arg;
2941 Assert(indexcol >= 0 && indexcol < index->ncolumns);
2943 if (index->indexkeys[indexcol] != 0)
2945 /* It's a simple index column */
2946 if (IsA(node, Var) &&
2947 ((Var *) node)->varno == index->rel->relid &&
2948 ((Var *) node)->varattno == index->indexkeys[indexcol])
2950 result = (Var *) copyObject(node);
2951 result->varno = INDEX_VAR;
2952 result->varattno = indexcol + 1;
2953 return (Node *) result;
2956 elog(ERROR, "index key does not match expected index column");
2959 /* It's an index expression, so find and cross-check the expression */
2960 indexpr_item = list_head(index->indexprs);
2961 for (pos = 0; pos < index->ncolumns; pos++)
2963 if (index->indexkeys[pos] == 0)
2965 if (indexpr_item == NULL)
2966 elog(ERROR, "too few entries in indexprs list");
2967 if (pos == indexcol)
2971 indexkey = (Node *) lfirst(indexpr_item);
2972 if (indexkey && IsA(indexkey, RelabelType))
2973 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
2974 if (equal(node, indexkey))
2976 result = makeVar(INDEX_VAR, indexcol + 1,
2977 exprType(lfirst(indexpr_item)), -1,
2978 exprCollation(lfirst(indexpr_item)),
2980 return (Node *) result;
2983 elog(ERROR, "index key does not match expected index column");
2985 indexpr_item = lnext(indexpr_item);
2990 elog(ERROR, "index key does not match expected index column");
2991 return NULL; /* keep compiler quiet */
2995 * get_switched_clauses
2996 * Given a list of merge or hash joinclauses (as RestrictInfo nodes),
2997 * extract the bare clauses, and rearrange the elements within the
2998 * clauses, if needed, so the outer join variable is on the left and
2999 * the inner is on the right. The original clause data structure is not
3000 * touched; a modified list is returned. We do, however, set the transient
3001 * outer_is_left field in each RestrictInfo to show which side was which.
3004 get_switched_clauses(List *clauses, Relids outerrelids)
3011 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
3012 OpExpr *clause = (OpExpr *) restrictinfo->clause;
3014 Assert(is_opclause(clause));
3015 if (bms_is_subset(restrictinfo->right_relids, outerrelids))
3018 * Duplicate just enough of the structure to allow commuting the
3019 * clause without changing the original list. Could use
3020 * copyObject, but a complete deep copy is overkill.
3022 OpExpr *temp = makeNode(OpExpr);
3024 temp->opno = clause->opno;
3025 temp->opfuncid = InvalidOid;
3026 temp->opresulttype = clause->opresulttype;
3027 temp->opretset = clause->opretset;
3028 temp->opcollid = clause->opcollid;
3029 temp->inputcollid = clause->inputcollid;
3030 temp->args = list_copy(clause->args);
3031 temp->location = clause->location;
3032 /* Commute it --- note this modifies the temp node in-place. */
3033 CommuteOpExpr(temp);
3034 t_list = lappend(t_list, temp);
3035 restrictinfo->outer_is_left = false;
3039 Assert(bms_is_subset(restrictinfo->left_relids, outerrelids));
3040 t_list = lappend(t_list, clause);
3041 restrictinfo->outer_is_left = true;
3048 * order_qual_clauses
3049 * Given a list of qual clauses that will all be evaluated at the same
3050 * plan node, sort the list into the order we want to check the quals
3053 * Ideally the order should be driven by a combination of execution cost and
3054 * selectivity, but it's not immediately clear how to account for both,
3055 * and given the uncertainty of the estimates the reliability of the decisions
3056 * would be doubtful anyway. So we just order by estimated per-tuple cost,
3057 * being careful not to change the order when (as is often the case) the
3058 * estimates are identical.
3060 * Although this will work on either bare clauses or RestrictInfos, it's
3061 * much faster to apply it to RestrictInfos, since it can re-use cost
3062 * information that is cached in RestrictInfos.
3064 * Note: some callers pass lists that contain entries that will later be
3065 * removed; this is the easiest way to let this routine see RestrictInfos
3066 * instead of bare clauses. It's OK because we only sort by cost, but
3067 * a cost/selectivity combination would likely do the wrong thing.
3070 order_qual_clauses(PlannerInfo *root, List *clauses)
3077 int nitems = list_length(clauses);
3083 /* No need to work hard for 0 or 1 clause */
3088 * Collect the items and costs into an array. This is to avoid repeated
3089 * cost_qual_eval work if the inputs aren't RestrictInfos.
3091 items = (QualItem *) palloc(nitems * sizeof(QualItem));
3093 foreach(lc, clauses)
3095 Node *clause = (Node *) lfirst(lc);
3098 cost_qual_eval_node(&qcost, clause, root);
3099 items[i].clause = clause;
3100 items[i].cost = qcost.per_tuple;
3105 * Sort. We don't use qsort() because it's not guaranteed stable for
3106 * equal keys. The expected number of entries is small enough that a
3107 * simple insertion sort should be good enough.
3109 for (i = 1; i < nitems; i++)
3111 QualItem newitem = items[i];
3114 /* insert newitem into the already-sorted subarray */
3115 for (j = i; j > 0; j--)
3117 if (newitem.cost >= items[j - 1].cost)
3119 items[j] = items[j - 1];
3124 /* Convert back to a list */
3126 for (i = 0; i < nitems; i++)
3127 result = lappend(result, items[i].clause);
3133 * Copy cost and size info from a Path node to the Plan node created from it.
3134 * The executor usually won't use this info, but it's needed by EXPLAIN.
3137 copy_path_costsize(Plan *dest, Path *src)
3141 dest->startup_cost = src->startup_cost;
3142 dest->total_cost = src->total_cost;
3143 dest->plan_rows = src->rows;
3144 dest->plan_width = src->parent->width;
3148 dest->startup_cost = 0;
3149 dest->total_cost = 0;
3150 dest->plan_rows = 0;
3151 dest->plan_width = 0;
3156 * Copy cost and size info from a lower plan node to an inserted node.
3157 * (Most callers alter the info after copying it.)
3160 copy_plan_costsize(Plan *dest, Plan *src)
3164 dest->startup_cost = src->startup_cost;
3165 dest->total_cost = src->total_cost;
3166 dest->plan_rows = src->plan_rows;
3167 dest->plan_width = src->plan_width;
3171 dest->startup_cost = 0;
3172 dest->total_cost = 0;
3173 dest->plan_rows = 0;
3174 dest->plan_width = 0;
3179 /*****************************************************************************
3181 * PLAN NODE BUILDING ROUTINES
3183 * Some of these are exported because they are called to build plan nodes
3184 * in contexts where we're not deriving the plan node from a path node.
3186 *****************************************************************************/
3189 make_seqscan(List *qptlist,
3193 SeqScan *node = makeNode(SeqScan);
3194 Plan *plan = &node->plan;
3196 /* cost should be inserted by caller */
3197 plan->targetlist = qptlist;
3198 plan->qual = qpqual;
3199 plan->lefttree = NULL;
3200 plan->righttree = NULL;
3201 node->scanrelid = scanrelid;
3207 make_indexscan(List *qptlist,
3212 List *indexqualorig,
3214 List *indexorderbyorig,
3215 ScanDirection indexscandir)
3217 IndexScan *node = makeNode(IndexScan);
3218 Plan *plan = &node->scan.plan;
3220 /* cost should be inserted by caller */
3221 plan->targetlist = qptlist;
3222 plan->qual = qpqual;
3223 plan->lefttree = NULL;
3224 plan->righttree = NULL;
3225 node->scan.scanrelid = scanrelid;
3226 node->indexid = indexid;
3227 node->indexqual = indexqual;
3228 node->indexqualorig = indexqualorig;
3229 node->indexorderby = indexorderby;
3230 node->indexorderbyorig = indexorderbyorig;
3231 node->indexorderdir = indexscandir;
3236 static IndexOnlyScan *
3237 make_indexonlyscan(List *qptlist,
3244 ScanDirection indexscandir)
3246 IndexOnlyScan *node = makeNode(IndexOnlyScan);
3247 Plan *plan = &node->scan.plan;
3249 /* cost should be inserted by caller */
3250 plan->targetlist = qptlist;
3251 plan->qual = qpqual;
3252 plan->lefttree = NULL;
3253 plan->righttree = NULL;
3254 node->scan.scanrelid = scanrelid;
3255 node->indexid = indexid;
3256 node->indexqual = indexqual;
3257 node->indexorderby = indexorderby;
3258 node->indextlist = indextlist;
3259 node->indexorderdir = indexscandir;
3264 static BitmapIndexScan *
3265 make_bitmap_indexscan(Index scanrelid,
3268 List *indexqualorig)
3270 BitmapIndexScan *node = makeNode(BitmapIndexScan);
3271 Plan *plan = &node->scan.plan;
3273 /* cost should be inserted by caller */
3274 plan->targetlist = NIL; /* not used */
3275 plan->qual = NIL; /* not used */
3276 plan->lefttree = NULL;
3277 plan->righttree = NULL;
3278 node->scan.scanrelid = scanrelid;
3279 node->indexid = indexid;
3280 node->indexqual = indexqual;
3281 node->indexqualorig = indexqualorig;
3286 static BitmapHeapScan *
3287 make_bitmap_heapscan(List *qptlist,
3290 List *bitmapqualorig,
3293 BitmapHeapScan *node = makeNode(BitmapHeapScan);
3294 Plan *plan = &node->scan.plan;
3296 /* cost should be inserted by caller */
3297 plan->targetlist = qptlist;
3298 plan->qual = qpqual;
3299 plan->lefttree = lefttree;
3300 plan->righttree = NULL;
3301 node->scan.scanrelid = scanrelid;
3302 node->bitmapqualorig = bitmapqualorig;
3308 make_tidscan(List *qptlist,
3313 TidScan *node = makeNode(TidScan);
3314 Plan *plan = &node->scan.plan;
3316 /* cost should be inserted by caller */
3317 plan->targetlist = qptlist;
3318 plan->qual = qpqual;
3319 plan->lefttree = NULL;
3320 plan->righttree = NULL;
3321 node->scan.scanrelid = scanrelid;
3322 node->tidquals = tidquals;
3328 make_subqueryscan(List *qptlist,
3333 SubqueryScan *node = makeNode(SubqueryScan);
3334 Plan *plan = &node->scan.plan;
3337 * Cost is figured here for the convenience of prepunion.c. Note this is
3338 * only correct for the case where qpqual is empty; otherwise caller
3339 * should overwrite cost with a better estimate.
3341 copy_plan_costsize(plan, subplan);
3342 plan->total_cost += cpu_tuple_cost * subplan->plan_rows;
3344 plan->targetlist = qptlist;
3345 plan->qual = qpqual;
3346 plan->lefttree = NULL;
3347 plan->righttree = NULL;
3348 node->scan.scanrelid = scanrelid;
3349 node->subplan = subplan;
3354 static FunctionScan *
3355 make_functionscan(List *qptlist,
3361 List *funccoltypmods,
3362 List *funccolcollations)
3364 FunctionScan *node = makeNode(FunctionScan);
3365 Plan *plan = &node->scan.plan;
3367 /* cost should be inserted by caller */
3368 plan->targetlist = qptlist;
3369 plan->qual = qpqual;
3370 plan->lefttree = NULL;
3371 plan->righttree = NULL;
3372 node->scan.scanrelid = scanrelid;
3373 node->funcexpr = funcexpr;
3374 node->funccolnames = funccolnames;
3375 node->funccoltypes = funccoltypes;
3376 node->funccoltypmods = funccoltypmods;
3377 node->funccolcollations = funccolcollations;
3383 make_valuesscan(List *qptlist,
3388 ValuesScan *node = makeNode(ValuesScan);
3389 Plan *plan = &node->scan.plan;
3391 /* cost should be inserted by caller */
3392 plan->targetlist = qptlist;
3393 plan->qual = qpqual;
3394 plan->lefttree = NULL;
3395 plan->righttree = NULL;
3396 node->scan.scanrelid = scanrelid;
3397 node->values_lists = values_lists;
3403 make_ctescan(List *qptlist,
3409 CteScan *node = makeNode(CteScan);
3410 Plan *plan = &node->scan.plan;
3412 /* cost should be inserted by caller */
3413 plan->targetlist = qptlist;
3414 plan->qual = qpqual;
3415 plan->lefttree = NULL;
3416 plan->righttree = NULL;
3417 node->scan.scanrelid = scanrelid;
3418 node->ctePlanId = ctePlanId;
3419 node->cteParam = cteParam;
3424 static WorkTableScan *
3425 make_worktablescan(List *qptlist,
3430 WorkTableScan *node = makeNode(WorkTableScan);
3431 Plan *plan = &node->scan.plan;
3433 /* cost should be inserted by caller */
3434 plan->targetlist = qptlist;
3435 plan->qual = qpqual;
3436 plan->lefttree = NULL;
3437 plan->righttree = NULL;
3438 node->scan.scanrelid = scanrelid;
3439 node->wtParam = wtParam;
3445 make_foreignscan(List *qptlist,
3451 ForeignScan *node = makeNode(ForeignScan);
3452 Plan *plan = &node->scan.plan;
3454 /* cost will be filled in by create_foreignscan_plan */
3455 plan->targetlist = qptlist;
3456 plan->qual = qpqual;
3457 plan->lefttree = NULL;
3458 plan->righttree = NULL;
3459 node->scan.scanrelid = scanrelid;
3460 node->fdw_exprs = fdw_exprs;
3461 node->fdw_private = fdw_private;
3462 /* fsSystemCol will be filled in by create_foreignscan_plan */
3463 node->fsSystemCol = false;
3469 make_append(List *appendplans, List *tlist)
3471 Append *node = makeNode(Append);
3472 Plan *plan = &node->plan;
3477 * Compute cost as sum of subplan costs. We charge nothing extra for the
3478 * Append itself, which perhaps is too optimistic, but since it doesn't do
3479 * any selection or projection, it is a pretty cheap node.
3481 * If you change this, see also create_append_path(). Also, the size
3482 * calculations should match set_append_rel_pathlist(). It'd be better
3483 * not to duplicate all this logic, but some callers of this function
3484 * aren't working from an appendrel or AppendPath, so there's noplace to
3485 * copy the data from.
3487 plan->startup_cost = 0;
3488 plan->total_cost = 0;
3489 plan->plan_rows = 0;
3491 foreach(subnode, appendplans)
3493 Plan *subplan = (Plan *) lfirst(subnode);
3495 if (subnode == list_head(appendplans)) /* first node? */
3496 plan->startup_cost = subplan->startup_cost;
3497 plan->total_cost += subplan->total_cost;
3498 plan->plan_rows += subplan->plan_rows;
3499 total_size += subplan->plan_width * subplan->plan_rows;
3501 if (plan->plan_rows > 0)
3502 plan->plan_width = rint(total_size / plan->plan_rows);
3504 plan->plan_width = 0;
3506 plan->targetlist = tlist;
3508 plan->lefttree = NULL;
3509 plan->righttree = NULL;
3510 node->appendplans = appendplans;
3516 make_recursive_union(List *tlist,
3523 RecursiveUnion *node = makeNode(RecursiveUnion);
3524 Plan *plan = &node->plan;
3525 int numCols = list_length(distinctList);
3527 cost_recursive_union(plan, lefttree, righttree);
3529 plan->targetlist = tlist;
3531 plan->lefttree = lefttree;
3532 plan->righttree = righttree;
3533 node->wtParam = wtParam;
3536 * convert SortGroupClause list into arrays of attr indexes and equality
3537 * operators, as wanted by executor
3539 node->numCols = numCols;
3543 AttrNumber *dupColIdx;
3547 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
3548 dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
3550 foreach(slitem, distinctList)
3552 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
3553 TargetEntry *tle = get_sortgroupclause_tle(sortcl,
3556 dupColIdx[keyno] = tle->resno;
3557 dupOperators[keyno] = sortcl->eqop;
3558 Assert(OidIsValid(dupOperators[keyno]));
3561 node->dupColIdx = dupColIdx;
3562 node->dupOperators = dupOperators;
3564 node->numGroups = numGroups;
3570 make_bitmap_and(List *bitmapplans)
3572 BitmapAnd *node = makeNode(BitmapAnd);
3573 Plan *plan = &node->plan;
3575 /* cost should be inserted by caller */
3576 plan->targetlist = NIL;
3578 plan->lefttree = NULL;
3579 plan->righttree = NULL;
3580 node->bitmapplans = bitmapplans;
3586 make_bitmap_or(List *bitmapplans)
3588 BitmapOr *node = makeNode(BitmapOr);
3589 Plan *plan = &node->plan;
3591 /* cost should be inserted by caller */
3592 plan->targetlist = NIL;
3594 plan->lefttree = NULL;
3595 plan->righttree = NULL;
3596 node->bitmapplans = bitmapplans;
3602 make_nestloop(List *tlist,
3610 NestLoop *node = makeNode(NestLoop);
3611 Plan *plan = &node->join.plan;
3613 /* cost should be inserted by caller */
3614 plan->targetlist = tlist;
3615 plan->qual = otherclauses;
3616 plan->lefttree = lefttree;
3617 plan->righttree = righttree;
3618 node->join.jointype = jointype;
3619 node->join.joinqual = joinclauses;
3620 node->nestParams = nestParams;
3626 make_hashjoin(List *tlist,
3634 HashJoin *node = makeNode(HashJoin);
3635 Plan *plan = &node->join.plan;
3637 /* cost should be inserted by caller */
3638 plan->targetlist = tlist;
3639 plan->qual = otherclauses;
3640 plan->lefttree = lefttree;
3641 plan->righttree = righttree;
3642 node->hashclauses = hashclauses;
3643 node->join.jointype = jointype;
3644 node->join.joinqual = joinclauses;
3650 make_hash(Plan *lefttree,
3652 AttrNumber skewColumn,
3655 int32 skewColTypmod)
3657 Hash *node = makeNode(Hash);
3658 Plan *plan = &node->plan;
3660 copy_plan_costsize(plan, lefttree);
3663 * For plausibility, make startup & total costs equal total cost of input
3664 * plan; this only affects EXPLAIN display not decisions.
3666 plan->startup_cost = plan->total_cost;
3667 plan->targetlist = lefttree->targetlist;
3669 plan->lefttree = lefttree;
3670 plan->righttree = NULL;
3672 node->skewTable = skewTable;
3673 node->skewColumn = skewColumn;
3674 node->skewInherit = skewInherit;
3675 node->skewColType = skewColType;
3676 node->skewColTypmod = skewColTypmod;
3682 make_mergejoin(List *tlist,
3687 Oid *mergecollations,
3688 int *mergestrategies,
3689 bool *mergenullsfirst,
3694 MergeJoin *node = makeNode(MergeJoin);
3695 Plan *plan = &node->join.plan;
3697 /* cost should be inserted by caller */
3698 plan->targetlist = tlist;
3699 plan->qual = otherclauses;
3700 plan->lefttree = lefttree;
3701 plan->righttree = righttree;
3702 node->mergeclauses = mergeclauses;
3703 node->mergeFamilies = mergefamilies;
3704 node->mergeCollations = mergecollations;
3705 node->mergeStrategies = mergestrategies;
3706 node->mergeNullsFirst = mergenullsfirst;
3707 node->join.jointype = jointype;
3708 node->join.joinqual = joinclauses;
3714 * make_sort --- basic routine to build a Sort plan node
3716 * Caller must have built the sortColIdx, sortOperators, collations, and
3717 * nullsFirst arrays already.
3718 * limit_tuples is as for cost_sort (in particular, pass -1 if no limit)
3721 make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
3722 AttrNumber *sortColIdx, Oid *sortOperators,
3723 Oid *collations, bool *nullsFirst,
3724 double limit_tuples)
3726 Sort *node = makeNode(Sort);
3727 Plan *plan = &node->plan;
3728 Path sort_path; /* dummy for result of cost_sort */
3730 copy_plan_costsize(plan, lefttree); /* only care about copying size */
3731 cost_sort(&sort_path, root, NIL,
3732 lefttree->total_cost,
3733 lefttree->plan_rows,
3734 lefttree->plan_width,
3738 plan->startup_cost = sort_path.startup_cost;
3739 plan->total_cost = sort_path.total_cost;
3740 plan->targetlist = lefttree->targetlist;
3742 plan->lefttree = lefttree;
3743 plan->righttree = NULL;
3744 node->numCols = numCols;
3745 node->sortColIdx = sortColIdx;
3746 node->sortOperators = sortOperators;
3747 node->collations = collations;
3748 node->nullsFirst = nullsFirst;
3754 * prepare_sort_from_pathkeys
3755 * Prepare to sort according to given pathkeys
3757 * This is used to set up for both Sort and MergeAppend nodes. It calculates
3758 * the executor's representation of the sort key information, and adjusts the
3759 * plan targetlist if needed to add resjunk sort columns.
3762 * 'lefttree' is the plan node which yields input tuples
3763 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
3764 * 'relids' identifies the child relation being sorted, if any
3765 * 'reqColIdx' is NULL or an array of required sort key column numbers
3766 * 'adjust_tlist_in_place' is TRUE if lefttree must be modified in-place
3768 * We must convert the pathkey information into arrays of sort key column
3769 * numbers, sort operator OIDs, collation OIDs, and nulls-first flags,
3770 * which is the representation the executor wants. These are returned into
3771 * the output parameters *p_numsortkeys etc.
3773 * When looking for matches to an EquivalenceClass's members, we will only
3774 * consider child EC members if they match 'relids'. This protects against
3775 * possible incorrect matches to child expressions that contain no Vars.
3777 * If reqColIdx isn't NULL then it contains sort key column numbers that
3778 * we should match. This is used when making child plans for a MergeAppend;
3779 * it's an error if we can't match the columns.
3781 * If the pathkeys include expressions that aren't simple Vars, we will
3782 * usually need to add resjunk items to the input plan's targetlist to
3783 * compute these expressions, since the Sort/MergeAppend node itself won't
3784 * do any such calculations. If the input plan type isn't one that can do
3785 * projections, this means adding a Result node just to do the projection.
3786 * However, the caller can pass adjust_tlist_in_place = TRUE to force the
3787 * lefttree tlist to be modified in-place regardless of whether the node type
3788 * can project --- we use this for fixing the tlist of MergeAppend itself.
3790 * Returns the node which is to be the input to the Sort (either lefttree,
3791 * or a Result stacked atop lefttree).
3794 prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
3796 const AttrNumber *reqColIdx,
3797 bool adjust_tlist_in_place,
3799 AttrNumber **p_sortColIdx,
3800 Oid **p_sortOperators,
3802 bool **p_nullsFirst)
3804 List *tlist = lefttree->targetlist;
3807 AttrNumber *sortColIdx;
3813 * We will need at most list_length(pathkeys) sort columns; possibly less
3815 numsortkeys = list_length(pathkeys);
3816 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
3817 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
3818 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
3819 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
3823 foreach(i, pathkeys)
3825 PathKey *pathkey = (PathKey *) lfirst(i);
3826 EquivalenceClass *ec = pathkey->pk_eclass;
3827 EquivalenceMember *em;
3828 TargetEntry *tle = NULL;
3829 Oid pk_datatype = InvalidOid;
3833 if (ec->ec_has_volatile)
3836 * If the pathkey's EquivalenceClass is volatile, then it must
3837 * have come from an ORDER BY clause, and we have to match it to
3838 * that same targetlist entry.
3840 if (ec->ec_sortref == 0) /* can't happen */
3841 elog(ERROR, "volatile EquivalenceClass has no sortref");
3842 tle = get_sortgroupref_tle(ec->ec_sortref, tlist);
3844 Assert(list_length(ec->ec_members) == 1);
3845 pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
3847 else if (reqColIdx != NULL)
3850 * If we are given a sort column number to match, only consider
3851 * the single TLE at that position. It's possible that there is
3852 * no such TLE, in which case fall through and generate a resjunk
3853 * targetentry (we assume this must have happened in the parent
3854 * plan as well). If there is a TLE but it doesn't match the
3855 * pathkey's EC, we do the same, which is probably the wrong thing
3856 * but we'll leave it to caller to complain about the mismatch.
3858 tle = get_tle_by_resno(tlist, reqColIdx[numsortkeys]);
3861 em = find_ec_member_for_tle(ec, tle, relids);
3864 /* found expr at right place in tlist */
3865 pk_datatype = em->em_datatype;
3874 * Otherwise, we can sort by any non-constant expression listed in
3875 * the pathkey's EquivalenceClass. For now, we take the first
3876 * tlist item found in the EC. If there's no match, we'll generate
3877 * a resjunk entry using the first EC member that is an expression
3878 * in the input's vars. (The non-const restriction only matters
3879 * if the EC is below_outer_join; but if it isn't, it won't
3880 * contain consts anyway, else we'd have discarded the pathkey as
3883 * XXX if we have a choice, is there any way of figuring out which
3884 * might be cheapest to execute? (For example, int4lt is likely
3885 * much cheaper to execute than numericlt, but both might appear
3886 * in the same equivalence class...) Not clear that we ever will
3887 * have an interesting choice in practice, so it may not matter.
3891 tle = (TargetEntry *) lfirst(j);
3892 em = find_ec_member_for_tle(ec, tle, relids);
3895 /* found expr already in tlist */
3896 pk_datatype = em->em_datatype;
3906 * No matching tlist item; look for a computable expression. Note
3907 * that we treat Aggrefs as if they were variables; this is
3908 * necessary when attempting to sort the output from an Agg node
3909 * for use in a WindowFunc (since grouping_planner will have
3910 * treated the Aggrefs as variables, too).
3912 Expr *sortexpr = NULL;
3914 foreach(j, ec->ec_members)
3916 EquivalenceMember *em = (EquivalenceMember *) lfirst(j);
3921 * We shouldn't be trying to sort by an equivalence class that
3922 * contains a constant, so no need to consider such cases any
3925 if (em->em_is_const)
3929 * Ignore child members unless they match the rel being
3932 if (em->em_is_child &&
3933 !bms_equal(em->em_relids, relids))
3936 sortexpr = em->em_expr;
3937 exprvars = pull_var_clause((Node *) sortexpr,
3938 PVC_INCLUDE_AGGREGATES,
3939 PVC_INCLUDE_PLACEHOLDERS);
3940 foreach(k, exprvars)
3942 if (!tlist_member_ignore_relabel(lfirst(k), tlist))
3945 list_free(exprvars);
3948 pk_datatype = em->em_datatype;
3949 break; /* found usable expression */
3953 elog(ERROR, "could not find pathkey item to sort");
3956 * Do we need to insert a Result node?
3958 if (!adjust_tlist_in_place &&
3959 !is_projection_capable_plan(lefttree))
3961 /* copy needed so we don't modify input's tlist below */
3962 tlist = copyObject(tlist);
3963 lefttree = (Plan *) make_result(root, tlist, NULL,
3967 /* Don't bother testing is_projection_capable_plan again */
3968 adjust_tlist_in_place = true;
3971 * Add resjunk entry to input's tlist
3973 tle = makeTargetEntry(sortexpr,
3974 list_length(tlist) + 1,
3977 tlist = lappend(tlist, tle);
3978 lefttree->targetlist = tlist; /* just in case NIL before */
3982 * Look up the correct sort operator from the PathKey's slightly
3983 * abstracted representation.
3985 sortop = get_opfamily_member(pathkey->pk_opfamily,
3988 pathkey->pk_strategy);
3989 if (!OidIsValid(sortop)) /* should not happen */
3990 elog(ERROR, "could not find member %d(%u,%u) of opfamily %u",
3991 pathkey->pk_strategy, pk_datatype, pk_datatype,
3992 pathkey->pk_opfamily);
3994 /* Add the column to the sort arrays */
3995 sortColIdx[numsortkeys] = tle->resno;
3996 sortOperators[numsortkeys] = sortop;
3997 collations[numsortkeys] = ec->ec_collation;
3998 nullsFirst[numsortkeys] = pathkey->pk_nulls_first;
4002 /* Return results */
4003 *p_numsortkeys = numsortkeys;
4004 *p_sortColIdx = sortColIdx;
4005 *p_sortOperators = sortOperators;
4006 *p_collations = collations;
4007 *p_nullsFirst = nullsFirst;
4013 * find_ec_member_for_tle
4014 * Locate an EquivalenceClass member matching the given TLE, if any
4016 * Child EC members are ignored unless they match 'relids'.
4018 static EquivalenceMember *
4019 find_ec_member_for_tle(EquivalenceClass *ec,
4026 /* We ignore binary-compatible relabeling on both ends */
4028 while (tlexpr && IsA(tlexpr, RelabelType))
4029 tlexpr = ((RelabelType *) tlexpr)->arg;
4031 foreach(lc, ec->ec_members)
4033 EquivalenceMember *em = (EquivalenceMember *) lfirst(lc);
4037 * We shouldn't be trying to sort by an equivalence class that
4038 * contains a constant, so no need to consider such cases any further.
4040 if (em->em_is_const)
4044 * Ignore child members unless they match the rel being sorted.
4046 if (em->em_is_child &&
4047 !bms_equal(em->em_relids, relids))
4050 /* Match if same expression (after stripping relabel) */
4051 emexpr = em->em_expr;
4052 while (emexpr && IsA(emexpr, RelabelType))
4053 emexpr = ((RelabelType *) emexpr)->arg;
4055 if (equal(emexpr, tlexpr))
4063 * make_sort_from_pathkeys
4064 * Create sort plan to sort according to given pathkeys
4066 * 'lefttree' is the node which yields input tuples
4067 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
4068 * 'limit_tuples' is the bound on the number of output tuples;
4072 make_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
4073 double limit_tuples)
4076 AttrNumber *sortColIdx;
4081 /* Compute sort column info, and adjust lefttree as needed */
4082 lefttree = prepare_sort_from_pathkeys(root, lefttree, pathkeys,
4092 /* Now build the Sort node */
4093 return make_sort(root, lefttree, numsortkeys,
4094 sortColIdx, sortOperators, collations,
4095 nullsFirst, limit_tuples);
4099 * make_sort_from_sortclauses
4100 * Create sort plan to sort according to given sortclauses
4102 * 'sortcls' is a list of SortGroupClauses
4103 * 'lefttree' is the node which yields input tuples
4106 make_sort_from_sortclauses(PlannerInfo *root, List *sortcls, Plan *lefttree)
4108 List *sub_tlist = lefttree->targetlist;
4111 AttrNumber *sortColIdx;
4116 /* Convert list-ish representation to arrays wanted by executor */
4117 numsortkeys = list_length(sortcls);
4118 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
4119 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
4120 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
4121 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
4126 SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
4127 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
4129 sortColIdx[numsortkeys] = tle->resno;
4130 sortOperators[numsortkeys] = sortcl->sortop;
4131 collations[numsortkeys] = exprCollation((Node *) tle->expr);
4132 nullsFirst[numsortkeys] = sortcl->nulls_first;
4136 return make_sort(root, lefttree, numsortkeys,
4137 sortColIdx, sortOperators, collations,
4142 * make_sort_from_groupcols
4143 * Create sort plan to sort based on grouping columns
4145 * 'groupcls' is the list of SortGroupClauses
4146 * 'grpColIdx' gives the column numbers to use
4148 * This might look like it could be merged with make_sort_from_sortclauses,
4149 * but presently we *must* use the grpColIdx[] array to locate sort columns,
4150 * because the child plan's tlist is not marked with ressortgroupref info
4151 * appropriate to the grouping node. So, only the sort ordering info
4152 * is used from the SortGroupClause entries.
4155 make_sort_from_groupcols(PlannerInfo *root,
4157 AttrNumber *grpColIdx,
4160 List *sub_tlist = lefttree->targetlist;
4163 AttrNumber *sortColIdx;
4168 /* Convert list-ish representation to arrays wanted by executor */
4169 numsortkeys = list_length(groupcls);
4170 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
4171 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
4172 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
4173 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
4176 foreach(l, groupcls)
4178 SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
4179 TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[numsortkeys]);
4181 sortColIdx[numsortkeys] = tle->resno;
4182 sortOperators[numsortkeys] = grpcl->sortop;
4183 collations[numsortkeys] = exprCollation((Node *) tle->expr);
4184 nullsFirst[numsortkeys] = grpcl->nulls_first;
4188 return make_sort(root, lefttree, numsortkeys,
4189 sortColIdx, sortOperators, collations,
4194 make_material(Plan *lefttree)
4196 Material *node = makeNode(Material);
4197 Plan *plan = &node->plan;
4199 /* cost should be inserted by caller */
4200 plan->targetlist = lefttree->targetlist;
4202 plan->lefttree = lefttree;
4203 plan->righttree = NULL;
4209 * materialize_finished_plan: stick a Material node atop a completed plan
4211 * There are a couple of places where we want to attach a Material node
4212 * after completion of subquery_planner(). This currently requires hackery.
4213 * Since subquery_planner has already run SS_finalize_plan on the subplan
4214 * tree, we have to kluge up parameter lists for the Material node.
4215 * Possibly this could be fixed by postponing SS_finalize_plan processing
4216 * until setrefs.c is run?
4219 materialize_finished_plan(Plan *subplan)
4222 Path matpath; /* dummy for result of cost_material */
4224 matplan = (Plan *) make_material(subplan);
4227 cost_material(&matpath,
4228 subplan->startup_cost,
4229 subplan->total_cost,
4231 subplan->plan_width);
4232 matplan->startup_cost = matpath.startup_cost;
4233 matplan->total_cost = matpath.total_cost;
4234 matplan->plan_rows = subplan->plan_rows;
4235 matplan->plan_width = subplan->plan_width;
4237 /* parameter kluge --- see comments above */
4238 matplan->extParam = bms_copy(subplan->extParam);
4239 matplan->allParam = bms_copy(subplan->allParam);
4245 make_agg(PlannerInfo *root, List *tlist, List *qual,
4246 AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
4247 int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators,
4251 Agg *node = makeNode(Agg);
4252 Plan *plan = &node->plan;
4253 Path agg_path; /* dummy for result of cost_agg */
4256 node->aggstrategy = aggstrategy;
4257 node->numCols = numGroupCols;
4258 node->grpColIdx = grpColIdx;
4259 node->grpOperators = grpOperators;
4260 node->numGroups = numGroups;
4262 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4263 cost_agg(&agg_path, root,
4264 aggstrategy, aggcosts,
4265 numGroupCols, numGroups,
4266 lefttree->startup_cost,
4267 lefttree->total_cost,
4268 lefttree->plan_rows);
4269 plan->startup_cost = agg_path.startup_cost;
4270 plan->total_cost = agg_path.total_cost;
4273 * We will produce a single output tuple if not grouping, and a tuple per
4276 if (aggstrategy == AGG_PLAIN)
4277 plan->plan_rows = 1;
4279 plan->plan_rows = numGroups;
4282 * We also need to account for the cost of evaluation of the qual (ie, the
4283 * HAVING clause) and the tlist. Note that cost_qual_eval doesn't charge
4284 * anything for Aggref nodes; this is okay since they are really
4285 * comparable to Vars.
4287 * See notes in add_tlist_costs_to_plan about why only make_agg,
4288 * make_windowagg and make_group worry about tlist eval cost.
4292 cost_qual_eval(&qual_cost, qual, root);
4293 plan->startup_cost += qual_cost.startup;
4294 plan->total_cost += qual_cost.startup;
4295 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
4297 add_tlist_costs_to_plan(root, plan, tlist);
4300 plan->targetlist = tlist;
4301 plan->lefttree = lefttree;
4302 plan->righttree = NULL;
4308 make_windowagg(PlannerInfo *root, List *tlist,
4309 List *windowFuncs, Index winref,
4310 int partNumCols, AttrNumber *partColIdx, Oid *partOperators,
4311 int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators,
4312 int frameOptions, Node *startOffset, Node *endOffset,
4315 WindowAgg *node = makeNode(WindowAgg);
4316 Plan *plan = &node->plan;
4317 Path windowagg_path; /* dummy for result of cost_windowagg */
4319 node->winref = winref;
4320 node->partNumCols = partNumCols;
4321 node->partColIdx = partColIdx;
4322 node->partOperators = partOperators;
4323 node->ordNumCols = ordNumCols;
4324 node->ordColIdx = ordColIdx;
4325 node->ordOperators = ordOperators;
4326 node->frameOptions = frameOptions;
4327 node->startOffset = startOffset;
4328 node->endOffset = endOffset;
4330 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4331 cost_windowagg(&windowagg_path, root,
4332 windowFuncs, partNumCols, ordNumCols,
4333 lefttree->startup_cost,
4334 lefttree->total_cost,
4335 lefttree->plan_rows);
4336 plan->startup_cost = windowagg_path.startup_cost;
4337 plan->total_cost = windowagg_path.total_cost;
4340 * We also need to account for the cost of evaluation of the tlist.
4342 * See notes in add_tlist_costs_to_plan about why only make_agg,
4343 * make_windowagg and make_group worry about tlist eval cost.
4345 add_tlist_costs_to_plan(root, plan, tlist);
4347 plan->targetlist = tlist;
4348 plan->lefttree = lefttree;
4349 plan->righttree = NULL;
4350 /* WindowAgg nodes never have a qual clause */
4357 make_group(PlannerInfo *root,
4361 AttrNumber *grpColIdx,
4366 Group *node = makeNode(Group);
4367 Plan *plan = &node->plan;
4368 Path group_path; /* dummy for result of cost_group */
4371 node->numCols = numGroupCols;
4372 node->grpColIdx = grpColIdx;
4373 node->grpOperators = grpOperators;
4375 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4376 cost_group(&group_path, root,
4377 numGroupCols, numGroups,
4378 lefttree->startup_cost,
4379 lefttree->total_cost,
4380 lefttree->plan_rows);
4381 plan->startup_cost = group_path.startup_cost;
4382 plan->total_cost = group_path.total_cost;
4384 /* One output tuple per estimated result group */
4385 plan->plan_rows = numGroups;
4388 * We also need to account for the cost of evaluation of the qual (ie, the
4389 * HAVING clause) and the tlist.
4391 * XXX this double-counts the cost of evaluation of any expressions used
4392 * for grouping, since in reality those will have been evaluated at a
4393 * lower plan level and will only be copied by the Group node. Worth
4396 * See notes in add_tlist_costs_to_plan about why only make_agg,
4397 * make_windowagg and make_group worry about tlist eval cost.
4401 cost_qual_eval(&qual_cost, qual, root);
4402 plan->startup_cost += qual_cost.startup;
4403 plan->total_cost += qual_cost.startup;
4404 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
4406 add_tlist_costs_to_plan(root, plan, tlist);
4409 plan->targetlist = tlist;
4410 plan->lefttree = lefttree;
4411 plan->righttree = NULL;
4417 * distinctList is a list of SortGroupClauses, identifying the targetlist items
4418 * that should be considered by the Unique filter. The input path must
4419 * already be sorted accordingly.
4422 make_unique(Plan *lefttree, List *distinctList)
4424 Unique *node = makeNode(Unique);
4425 Plan *plan = &node->plan;
4426 int numCols = list_length(distinctList);
4428 AttrNumber *uniqColIdx;
4432 copy_plan_costsize(plan, lefttree);
4435 * Charge one cpu_operator_cost per comparison per input tuple. We assume
4436 * all columns get compared at most of the tuples. (XXX probably this is
4439 plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols;
4442 * plan->plan_rows is left as a copy of the input subplan's plan_rows; ie,
4443 * we assume the filter removes nothing. The caller must alter this if he
4444 * has a better idea.
4447 plan->targetlist = lefttree->targetlist;
4449 plan->lefttree = lefttree;
4450 plan->righttree = NULL;
4453 * convert SortGroupClause list into arrays of attr indexes and equality
4454 * operators, as wanted by executor
4456 Assert(numCols > 0);
4457 uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
4458 uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
4460 foreach(slitem, distinctList)
4462 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
4463 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
4465 uniqColIdx[keyno] = tle->resno;
4466 uniqOperators[keyno] = sortcl->eqop;
4467 Assert(OidIsValid(uniqOperators[keyno]));
4471 node->numCols = numCols;
4472 node->uniqColIdx = uniqColIdx;
4473 node->uniqOperators = uniqOperators;
4479 * distinctList is a list of SortGroupClauses, identifying the targetlist
4480 * items that should be considered by the SetOp filter. The input path must
4481 * already be sorted accordingly.
4484 make_setop(SetOpCmd cmd, SetOpStrategy strategy, Plan *lefttree,
4485 List *distinctList, AttrNumber flagColIdx, int firstFlag,
4486 long numGroups, double outputRows)
4488 SetOp *node = makeNode(SetOp);
4489 Plan *plan = &node->plan;
4490 int numCols = list_length(distinctList);
4492 AttrNumber *dupColIdx;
4496 copy_plan_costsize(plan, lefttree);
4497 plan->plan_rows = outputRows;
4500 * Charge one cpu_operator_cost per comparison per input tuple. We assume
4501 * all columns get compared at most of the tuples.
4503 plan->total_cost += cpu_operator_cost * lefttree->plan_rows * numCols;
4505 plan->targetlist = lefttree->targetlist;
4507 plan->lefttree = lefttree;
4508 plan->righttree = NULL;
4511 * convert SortGroupClause list into arrays of attr indexes and equality
4512 * operators, as wanted by executor
4514 Assert(numCols > 0);
4515 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
4516 dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
4518 foreach(slitem, distinctList)
4520 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
4521 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
4523 dupColIdx[keyno] = tle->resno;
4524 dupOperators[keyno] = sortcl->eqop;
4525 Assert(OidIsValid(dupOperators[keyno]));
4530 node->strategy = strategy;
4531 node->numCols = numCols;
4532 node->dupColIdx = dupColIdx;
4533 node->dupOperators = dupOperators;
4534 node->flagColIdx = flagColIdx;
4535 node->firstFlag = firstFlag;
4536 node->numGroups = numGroups;
4543 * Build a LockRows plan node
4546 make_lockrows(Plan *lefttree, List *rowMarks, int epqParam)
4548 LockRows *node = makeNode(LockRows);
4549 Plan *plan = &node->plan;
4551 copy_plan_costsize(plan, lefttree);
4553 /* charge cpu_tuple_cost to reflect locking costs (underestimate?) */
4554 plan->total_cost += cpu_tuple_cost * plan->plan_rows;
4556 plan->targetlist = lefttree->targetlist;
4558 plan->lefttree = lefttree;
4559 plan->righttree = NULL;
4561 node->rowMarks = rowMarks;
4562 node->epqParam = epqParam;
4568 * Note: offset_est and count_est are passed in to save having to repeat
4569 * work already done to estimate the values of the limitOffset and limitCount
4570 * expressions. Their values are as returned by preprocess_limit (0 means
4571 * "not relevant", -1 means "couldn't estimate"). Keep the code below in sync
4572 * with that function!
4575 make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount,
4576 int64 offset_est, int64 count_est)
4578 Limit *node = makeNode(Limit);
4579 Plan *plan = &node->plan;
4581 copy_plan_costsize(plan, lefttree);
4584 * Adjust the output rows count and costs according to the offset/limit.
4585 * This is only a cosmetic issue if we are at top level, but if we are
4586 * building a subquery then it's important to report correct info to the
4589 * When the offset or count couldn't be estimated, use 10% of the
4590 * estimated number of rows emitted from the subplan.
4592 if (offset_est != 0)
4597 offset_rows = (double) offset_est;
4599 offset_rows = clamp_row_est(lefttree->plan_rows * 0.10);
4600 if (offset_rows > plan->plan_rows)
4601 offset_rows = plan->plan_rows;
4602 if (plan->plan_rows > 0)
4603 plan->startup_cost +=
4604 (plan->total_cost - plan->startup_cost)
4605 * offset_rows / plan->plan_rows;
4606 plan->plan_rows -= offset_rows;
4607 if (plan->plan_rows < 1)
4608 plan->plan_rows = 1;
4616 count_rows = (double) count_est;
4618 count_rows = clamp_row_est(lefttree->plan_rows * 0.10);
4619 if (count_rows > plan->plan_rows)
4620 count_rows = plan->plan_rows;
4621 if (plan->plan_rows > 0)
4622 plan->total_cost = plan->startup_cost +
4623 (plan->total_cost - plan->startup_cost)
4624 * count_rows / plan->plan_rows;
4625 plan->plan_rows = count_rows;
4626 if (plan->plan_rows < 1)
4627 plan->plan_rows = 1;
4630 plan->targetlist = lefttree->targetlist;
4632 plan->lefttree = lefttree;
4633 plan->righttree = NULL;
4635 node->limitOffset = limitOffset;
4636 node->limitCount = limitCount;
4643 * Build a Result plan node
4645 * If we have a subplan, assume that any evaluation costs for the gating qual
4646 * were already factored into the subplan's startup cost, and just copy the
4647 * subplan cost. If there's no subplan, we should include the qual eval
4648 * cost. In either case, tlist eval cost is not to be included here.
4651 make_result(PlannerInfo *root,
4653 Node *resconstantqual,
4656 Result *node = makeNode(Result);
4657 Plan *plan = &node->plan;
4660 copy_plan_costsize(plan, subplan);
4663 plan->startup_cost = 0;
4664 plan->total_cost = cpu_tuple_cost;
4665 plan->plan_rows = 1; /* wrong if we have a set-valued function? */
4666 plan->plan_width = 0; /* XXX is it worth being smarter? */
4667 if (resconstantqual)
4671 cost_qual_eval(&qual_cost, (List *) resconstantqual, root);
4672 /* resconstantqual is evaluated once at startup */
4673 plan->startup_cost += qual_cost.startup + qual_cost.per_tuple;
4674 plan->total_cost += qual_cost.startup + qual_cost.per_tuple;
4678 plan->targetlist = tlist;
4680 plan->lefttree = subplan;
4681 plan->righttree = NULL;
4682 node->resconstantqual = resconstantqual;
4689 * Build a ModifyTable plan node
4691 * Currently, we don't charge anything extra for the actual table modification
4692 * work, nor for the RETURNING expressions if any. It would only be window
4693 * dressing, since these are always top-level nodes and there is no way for
4694 * the costs to change any higher-level planning choices. But we might want
4695 * to make it look better sometime.
4698 make_modifytable(CmdType operation, bool canSetTag,
4699 List *resultRelations,
4700 List *subplans, List *returningLists,
4701 List *rowMarks, int epqParam)
4703 ModifyTable *node = makeNode(ModifyTable);
4704 Plan *plan = &node->plan;
4708 Assert(list_length(resultRelations) == list_length(subplans));
4709 Assert(returningLists == NIL ||
4710 list_length(resultRelations) == list_length(returningLists));
4713 * Compute cost as sum of subplan costs.
4715 plan->startup_cost = 0;
4716 plan->total_cost = 0;
4717 plan->plan_rows = 0;
4719 foreach(subnode, subplans)
4721 Plan *subplan = (Plan *) lfirst(subnode);
4723 if (subnode == list_head(subplans)) /* first node? */
4724 plan->startup_cost = subplan->startup_cost;
4725 plan->total_cost += subplan->total_cost;
4726 plan->plan_rows += subplan->plan_rows;
4727 total_size += subplan->plan_width * subplan->plan_rows;
4729 if (plan->plan_rows > 0)
4730 plan->plan_width = rint(total_size / plan->plan_rows);
4732 plan->plan_width = 0;
4734 node->plan.lefttree = NULL;
4735 node->plan.righttree = NULL;
4736 node->plan.qual = NIL;
4737 /* setrefs.c will fill in the targetlist, if needed */
4738 node->plan.targetlist = NIL;
4740 node->operation = operation;
4741 node->canSetTag = canSetTag;
4742 node->resultRelations = resultRelations;
4743 node->resultRelIndex = -1; /* will be set correctly in setrefs.c */
4744 node->plans = subplans;
4745 node->returningLists = returningLists;
4746 node->rowMarks = rowMarks;
4747 node->epqParam = epqParam;
4753 * is_projection_capable_plan
4754 * Check whether a given Plan node is able to do projection.
4757 is_projection_capable_plan(Plan *plan)
4759 /* Most plan types can project, so just list the ones that can't */
4760 switch (nodeTag(plan))
4772 case T_RecursiveUnion: