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-2015, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
13 * src/backend/optimizer/plan/createplan.c
15 *-------------------------------------------------------------------------
22 #include "access/stratnum.h"
23 #include "access/sysattr.h"
24 #include "catalog/pg_class.h"
25 #include "catalog/pg_operator.h"
26 #include "foreign/fdwapi.h"
27 #include "miscadmin.h"
28 #include "nodes/makefuncs.h"
29 #include "nodes/nodeFuncs.h"
30 #include "optimizer/clauses.h"
31 #include "optimizer/cost.h"
32 #include "optimizer/paths.h"
33 #include "optimizer/placeholder.h"
34 #include "optimizer/plancat.h"
35 #include "optimizer/planmain.h"
36 #include "optimizer/planner.h"
37 #include "optimizer/predtest.h"
38 #include "optimizer/prep.h"
39 #include "optimizer/restrictinfo.h"
40 #include "optimizer/subselect.h"
41 #include "optimizer/tlist.h"
42 #include "optimizer/var.h"
43 #include "parser/parse_clause.h"
44 #include "parser/parsetree.h"
45 #include "utils/lsyscache.h"
48 static Plan *create_plan_recurse(PlannerInfo *root, Path *best_path);
49 static Plan *create_scan_plan(PlannerInfo *root, Path *best_path);
50 static List *build_path_tlist(PlannerInfo *root, Path *path);
51 static bool use_physical_tlist(PlannerInfo *root, RelOptInfo *rel);
52 static void disuse_physical_tlist(PlannerInfo *root, Plan *plan, Path *path);
53 static Plan *create_gating_plan(PlannerInfo *root, Plan *plan, List *quals);
54 static Plan *create_join_plan(PlannerInfo *root, JoinPath *best_path);
55 static Plan *create_append_plan(PlannerInfo *root, AppendPath *best_path);
56 static Plan *create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path);
57 static Result *create_result_plan(PlannerInfo *root, ResultPath *best_path);
58 static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path);
59 static Plan *create_unique_plan(PlannerInfo *root, UniquePath *best_path);
60 static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path,
61 List *tlist, List *scan_clauses);
62 static SampleScan *create_samplescan_plan(PlannerInfo *root, Path *best_path,
63 List *tlist, List *scan_clauses);
64 static Scan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path,
65 List *tlist, List *scan_clauses, bool indexonly);
66 static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
67 BitmapHeapPath *best_path,
68 List *tlist, List *scan_clauses);
69 static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
70 List **qual, List **indexqual, List **indexECs);
71 static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
72 List *tlist, List *scan_clauses);
73 static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
74 List *tlist, List *scan_clauses);
75 static FunctionScan *create_functionscan_plan(PlannerInfo *root, Path *best_path,
76 List *tlist, List *scan_clauses);
77 static ValuesScan *create_valuesscan_plan(PlannerInfo *root, Path *best_path,
78 List *tlist, List *scan_clauses);
79 static CteScan *create_ctescan_plan(PlannerInfo *root, Path *best_path,
80 List *tlist, List *scan_clauses);
81 static WorkTableScan *create_worktablescan_plan(PlannerInfo *root, Path *best_path,
82 List *tlist, List *scan_clauses);
83 static ForeignScan *create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
84 List *tlist, List *scan_clauses);
85 static CustomScan *create_customscan_plan(PlannerInfo *root,
86 CustomPath *best_path,
87 List *tlist, List *scan_clauses);
88 static NestLoop *create_nestloop_plan(PlannerInfo *root, NestPath *best_path,
89 Plan *outer_plan, Plan *inner_plan);
90 static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path,
91 Plan *outer_plan, Plan *inner_plan);
92 static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path,
93 Plan *outer_plan, Plan *inner_plan);
94 static Node *replace_nestloop_params(PlannerInfo *root, Node *expr);
95 static Node *replace_nestloop_params_mutator(Node *node, PlannerInfo *root);
96 static void process_subquery_nestloop_params(PlannerInfo *root,
97 List *subplan_params);
98 static List *fix_indexqual_references(PlannerInfo *root, IndexPath *index_path);
99 static List *fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path);
100 static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol);
101 static List *get_switched_clauses(List *clauses, Relids outerrelids);
102 static List *order_qual_clauses(PlannerInfo *root, List *clauses);
103 static void copy_path_costsize(Plan *dest, Path *src);
104 static void copy_plan_costsize(Plan *dest, Plan *src);
105 static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
106 static SampleScan *make_samplescan(List *qptlist, List *qpqual, Index scanrelid);
107 static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
108 Oid indexid, List *indexqual, List *indexqualorig,
109 List *indexorderby, List *indexorderbyorig, Oid *indexorderbyops,
110 ScanDirection indexscandir);
111 static IndexOnlyScan *make_indexonlyscan(List *qptlist, List *qpqual,
112 Index scanrelid, Oid indexid,
113 List *indexqual, List *indexorderby,
115 ScanDirection indexscandir);
116 static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid,
118 List *indexqualorig);
119 static BitmapHeapScan *make_bitmap_heapscan(List *qptlist,
122 List *bitmapqualorig,
124 static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
126 static FunctionScan *make_functionscan(List *qptlist, List *qpqual,
127 Index scanrelid, List *functions, bool funcordinality);
128 static ValuesScan *make_valuesscan(List *qptlist, List *qpqual,
129 Index scanrelid, List *values_lists);
130 static CteScan *make_ctescan(List *qptlist, List *qpqual,
131 Index scanrelid, int ctePlanId, int cteParam);
132 static WorkTableScan *make_worktablescan(List *qptlist, List *qpqual,
133 Index scanrelid, int wtParam);
134 static BitmapAnd *make_bitmap_and(List *bitmapplans);
135 static BitmapOr *make_bitmap_or(List *bitmapplans);
136 static NestLoop *make_nestloop(List *tlist,
137 List *joinclauses, List *otherclauses, List *nestParams,
138 Plan *lefttree, Plan *righttree,
140 static HashJoin *make_hashjoin(List *tlist,
141 List *joinclauses, List *otherclauses,
143 Plan *lefttree, Plan *righttree,
145 static Hash *make_hash(Plan *lefttree,
147 AttrNumber skewColumn,
150 int32 skewColTypmod);
151 static MergeJoin *make_mergejoin(List *tlist,
152 List *joinclauses, List *otherclauses,
155 Oid *mergecollations,
156 int *mergestrategies,
157 bool *mergenullsfirst,
158 Plan *lefttree, Plan *righttree,
160 static Sort *make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
161 AttrNumber *sortColIdx, Oid *sortOperators,
162 Oid *collations, bool *nullsFirst,
163 double limit_tuples);
164 static Plan *prepare_sort_from_pathkeys(PlannerInfo *root,
165 Plan *lefttree, List *pathkeys,
167 const AttrNumber *reqColIdx,
168 bool adjust_tlist_in_place,
170 AttrNumber **p_sortColIdx,
171 Oid **p_sortOperators,
173 bool **p_nullsFirst);
174 static EquivalenceMember *find_ec_member_for_expr(EquivalenceClass *ec,
177 static Material *make_material(Plan *lefttree);
182 * Creates the access plan for a query by recursively processing the
183 * desired tree of pathnodes, starting at the node 'best_path'. For
184 * every pathnode found, we create a corresponding plan node containing
185 * appropriate id, target list, and qualification information.
187 * The tlists and quals in the plan tree are still in planner format,
188 * ie, Vars still correspond to the parser's numbering. This will be
189 * fixed later by setrefs.c.
191 * best_path is the best access path
193 * Returns a Plan tree.
196 create_plan(PlannerInfo *root, Path *best_path)
200 /* plan_params should not be in use in current query level */
201 Assert(root->plan_params == NIL);
203 /* Initialize this module's private workspace in PlannerInfo */
204 root->curOuterRels = NULL;
205 root->curOuterParams = NIL;
207 /* Recursively process the path tree */
208 plan = create_plan_recurse(root, best_path);
210 /* Check we successfully assigned all NestLoopParams to plan nodes */
211 if (root->curOuterParams != NIL)
212 elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
215 * Reset plan_params to ensure param IDs used for nestloop params are not
218 root->plan_params = NIL;
224 * create_plan_recurse
225 * Recursive guts of create_plan().
228 create_plan_recurse(PlannerInfo *root, Path *best_path)
232 switch (best_path->pathtype)
237 case T_IndexOnlyScan:
238 case T_BitmapHeapScan:
244 case T_WorkTableScan:
247 plan = create_scan_plan(root, best_path);
252 plan = create_join_plan(root,
253 (JoinPath *) best_path);
256 plan = create_append_plan(root,
257 (AppendPath *) best_path);
260 plan = create_merge_append_plan(root,
261 (MergeAppendPath *) best_path);
264 plan = (Plan *) create_result_plan(root,
265 (ResultPath *) best_path);
268 plan = (Plan *) create_material_plan(root,
269 (MaterialPath *) best_path);
272 plan = create_unique_plan(root,
273 (UniquePath *) best_path);
276 elog(ERROR, "unrecognized node type: %d",
277 (int) best_path->pathtype);
278 plan = NULL; /* keep compiler quiet */
287 * Create a scan plan for the parent relation of 'best_path'.
290 create_scan_plan(PlannerInfo *root, Path *best_path)
292 RelOptInfo *rel = best_path->parent;
298 * For table scans, rather than using the relation targetlist (which is
299 * only those Vars actually needed by the query), we prefer to generate a
300 * tlist containing all Vars in order. This will allow the executor to
301 * optimize away projection of the table tuples, if possible. (Note that
302 * planner.c may replace the tlist we generate here, forcing projection to
305 if (use_physical_tlist(root, rel))
307 if (best_path->pathtype == T_IndexOnlyScan)
309 /* For index-only scan, the preferred tlist is the index's */
310 tlist = copyObject(((IndexPath *) best_path)->indexinfo->indextlist);
314 tlist = build_physical_tlist(root, rel);
315 /* if fail because of dropped cols, use regular method */
317 tlist = build_path_tlist(root, best_path);
322 tlist = build_path_tlist(root, best_path);
326 * Extract the relevant restriction clauses from the parent relation. The
327 * executor must apply all these restrictions during the scan, except for
328 * pseudoconstants which we'll take care of below.
330 scan_clauses = rel->baserestrictinfo;
333 * If this is a parameterized scan, we also need to enforce all the join
334 * clauses available from the outer relation(s).
336 * For paranoia's sake, don't modify the stored baserestrictinfo list.
338 if (best_path->param_info)
339 scan_clauses = list_concat(list_copy(scan_clauses),
340 best_path->param_info->ppi_clauses);
342 switch (best_path->pathtype)
345 plan = (Plan *) create_seqscan_plan(root,
352 plan = (Plan *) create_samplescan_plan(root,
359 plan = (Plan *) create_indexscan_plan(root,
360 (IndexPath *) best_path,
366 case T_IndexOnlyScan:
367 plan = (Plan *) create_indexscan_plan(root,
368 (IndexPath *) best_path,
374 case T_BitmapHeapScan:
375 plan = (Plan *) create_bitmap_scan_plan(root,
376 (BitmapHeapPath *) best_path,
382 plan = (Plan *) create_tidscan_plan(root,
383 (TidPath *) best_path,
389 plan = (Plan *) create_subqueryscan_plan(root,
396 plan = (Plan *) create_functionscan_plan(root,
403 plan = (Plan *) create_valuesscan_plan(root,
410 plan = (Plan *) create_ctescan_plan(root,
416 case T_WorkTableScan:
417 plan = (Plan *) create_worktablescan_plan(root,
424 plan = (Plan *) create_foreignscan_plan(root,
425 (ForeignPath *) best_path,
431 plan = (Plan *) create_customscan_plan(root,
432 (CustomPath *) best_path,
438 elog(ERROR, "unrecognized node type: %d",
439 (int) best_path->pathtype);
440 plan = NULL; /* keep compiler quiet */
445 * If there are any pseudoconstant clauses attached to this node, insert a
446 * gating Result node that evaluates the pseudoconstants as one-time
449 if (root->hasPseudoConstantQuals)
450 plan = create_gating_plan(root, plan, scan_clauses);
456 * Build a target list (ie, a list of TargetEntry) for the Path's output.
459 build_path_tlist(PlannerInfo *root, Path *path)
461 RelOptInfo *rel = path->parent;
466 foreach(v, rel->reltargetlist)
468 /* Do we really need to copy here? Not sure */
469 Node *node = (Node *) copyObject(lfirst(v));
472 * If it's a parameterized path, there might be lateral references in
473 * the tlist, which need to be replaced with Params. There's no need
474 * to remake the TargetEntry nodes, so apply this to each list item
477 if (path->param_info)
478 node = replace_nestloop_params(root, node);
480 tlist = lappend(tlist, makeTargetEntry((Expr *) node,
491 * Decide whether to use a tlist matching relation structure,
492 * rather than only those Vars actually referenced.
495 use_physical_tlist(PlannerInfo *root, RelOptInfo *rel)
501 * We can do this for real relation scans, subquery scans, function scans,
502 * values scans, and CTE scans (but not for, eg, joins).
504 if (rel->rtekind != RTE_RELATION &&
505 rel->rtekind != RTE_SUBQUERY &&
506 rel->rtekind != RTE_FUNCTION &&
507 rel->rtekind != RTE_VALUES &&
508 rel->rtekind != RTE_CTE)
512 * Can't do it with inheritance cases either (mainly because Append
515 if (rel->reloptkind != RELOPT_BASEREL)
519 * Can't do it if any system columns or whole-row Vars are requested.
520 * (This could possibly be fixed but would take some fragile assumptions
521 * in setrefs.c, I think.)
523 for (i = rel->min_attr; i <= 0; i++)
525 if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
530 * Can't do it if the rel is required to emit any placeholder expressions,
533 foreach(lc, root->placeholder_list)
535 PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
537 if (bms_nonempty_difference(phinfo->ph_needed, rel->relids) &&
538 bms_is_subset(phinfo->ph_eval_at, rel->relids))
546 * disuse_physical_tlist
547 * Switch a plan node back to emitting only Vars actually referenced.
549 * If the plan node immediately above a scan would prefer to get only
550 * needed Vars and not a physical tlist, it must call this routine to
551 * undo the decision made by use_physical_tlist(). Currently, Hash, Sort,
552 * and Material nodes want this, so they don't have to store useless columns.
555 disuse_physical_tlist(PlannerInfo *root, Plan *plan, Path *path)
557 /* Only need to undo it for path types handled by create_scan_plan() */
558 switch (path->pathtype)
563 case T_IndexOnlyScan:
564 case T_BitmapHeapScan:
570 case T_WorkTableScan:
573 plan->targetlist = build_path_tlist(root, path);
582 * Deal with pseudoconstant qual clauses
584 * If the node's quals list includes any pseudoconstant quals, put them
585 * into a gating Result node atop the already-built plan. Otherwise,
586 * return the plan as-is.
588 * Note that we don't change cost or size estimates when doing gating.
589 * The costs of qual eval were already folded into the plan's startup cost.
590 * Leaving the size alone amounts to assuming that the gating qual will
591 * succeed, which is the conservative estimate for planning upper queries.
592 * We certainly don't want to assume the output size is zero (unless the
593 * gating qual is actually constant FALSE, and that case is dealt with in
594 * clausesel.c). Interpolating between the two cases is silly, because
595 * it doesn't reflect what will really happen at runtime, and besides which
596 * in most cases we have only a very bad idea of the probability of the gating
600 create_gating_plan(PlannerInfo *root, Plan *plan, List *quals)
602 List *pseudoconstants;
604 /* Sort into desirable execution order while still in RestrictInfo form */
605 quals = order_qual_clauses(root, quals);
607 /* Pull out any pseudoconstant quals from the RestrictInfo list */
608 pseudoconstants = extract_actual_clauses(quals, true);
610 if (!pseudoconstants)
613 return (Plan *) make_result(root,
615 (Node *) pseudoconstants,
621 * Create a join plan for 'best_path' and (recursively) plans for its
622 * inner and outer paths.
625 create_join_plan(PlannerInfo *root, JoinPath *best_path)
630 Relids saveOuterRels = root->curOuterRels;
632 outer_plan = create_plan_recurse(root, best_path->outerjoinpath);
634 /* For a nestloop, include outer relids in curOuterRels for inner side */
635 if (best_path->path.pathtype == T_NestLoop)
636 root->curOuterRels = bms_union(root->curOuterRels,
637 best_path->outerjoinpath->parent->relids);
639 inner_plan = create_plan_recurse(root, best_path->innerjoinpath);
641 switch (best_path->path.pathtype)
644 plan = (Plan *) create_mergejoin_plan(root,
645 (MergePath *) best_path,
650 plan = (Plan *) create_hashjoin_plan(root,
651 (HashPath *) best_path,
656 /* Restore curOuterRels */
657 bms_free(root->curOuterRels);
658 root->curOuterRels = saveOuterRels;
660 plan = (Plan *) create_nestloop_plan(root,
661 (NestPath *) best_path,
666 elog(ERROR, "unrecognized node type: %d",
667 (int) best_path->path.pathtype);
668 plan = NULL; /* keep compiler quiet */
673 * If there are any pseudoconstant clauses attached to this node, insert a
674 * gating Result node that evaluates the pseudoconstants as one-time
677 if (root->hasPseudoConstantQuals)
678 plan = create_gating_plan(root, plan, best_path->joinrestrictinfo);
683 * * Expensive function pullups may have pulled local predicates * into
684 * this path node. Put them in the qpqual of the plan node. * JMH,
687 if (get_loc_restrictinfo(best_path) != NIL)
688 set_qpqual((Plan) plan,
689 list_concat(get_qpqual((Plan) plan),
690 get_actual_clauses(get_loc_restrictinfo(best_path))));
698 * Create an Append plan for 'best_path' and (recursively) plans
701 * Returns a Plan node.
704 create_append_plan(PlannerInfo *root, AppendPath *best_path)
707 List *tlist = build_path_tlist(root, &best_path->path);
708 List *subplans = NIL;
712 * The subpaths list could be empty, if every child was proven empty by
713 * constraint exclusion. In that case generate a dummy plan that returns
716 * Note that an AppendPath with no members is also generated in certain
717 * cases where there was no appending construct at all, but we know the
718 * relation is empty (see set_dummy_rel_pathlist).
720 if (best_path->subpaths == NIL)
722 /* Generate a Result plan with constant-FALSE gating qual */
723 return (Plan *) make_result(root,
725 (Node *) list_make1(makeBoolConst(false,
730 /* Build the plan for each child */
731 foreach(subpaths, best_path->subpaths)
733 Path *subpath = (Path *) lfirst(subpaths);
735 subplans = lappend(subplans, create_plan_recurse(root, subpath));
739 * XXX ideally, if there's just one child, we'd not bother to generate an
740 * Append node but just return the single child. At the moment this does
741 * not work because the varno of the child scan plan won't match the
742 * parent-rel Vars it'll be asked to emit.
745 plan = make_append(subplans, tlist);
747 return (Plan *) plan;
751 * create_merge_append_plan
752 * Create a MergeAppend plan for 'best_path' and (recursively) plans
755 * Returns a Plan node.
758 create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path)
760 MergeAppend *node = makeNode(MergeAppend);
761 Plan *plan = &node->plan;
762 List *tlist = build_path_tlist(root, &best_path->path);
763 List *pathkeys = best_path->path.pathkeys;
764 List *subplans = NIL;
768 * We don't have the actual creation of the MergeAppend node split out
769 * into a separate make_xxx function. This is because we want to run
770 * prepare_sort_from_pathkeys on it before we do so on the individual
771 * child plans, to make cross-checking the sort info easier.
773 copy_path_costsize(plan, (Path *) best_path);
774 plan->targetlist = tlist;
776 plan->lefttree = NULL;
777 plan->righttree = NULL;
779 /* Compute sort column info, and adjust MergeAppend's tlist as needed */
780 (void) prepare_sort_from_pathkeys(root, plan, pathkeys,
781 best_path->path.parent->relids,
786 &node->sortOperators,
791 * Now prepare the child plans. We must apply prepare_sort_from_pathkeys
792 * even to subplans that don't need an explicit sort, to make sure they
793 * are returning the same sort key columns the MergeAppend expects.
795 foreach(subpaths, best_path->subpaths)
797 Path *subpath = (Path *) lfirst(subpaths);
800 AttrNumber *sortColIdx;
805 /* Build the child plan */
806 subplan = create_plan_recurse(root, subpath);
808 /* Compute sort column info, and adjust subplan's tlist as needed */
809 subplan = prepare_sort_from_pathkeys(root, subplan, pathkeys,
810 subpath->parent->relids,
820 * Check that we got the same sort key information. We just Assert
821 * that the sortops match, since those depend only on the pathkeys;
822 * but it seems like a good idea to check the sort column numbers
823 * explicitly, to ensure the tlists really do match up.
825 Assert(numsortkeys == node->numCols);
826 if (memcmp(sortColIdx, node->sortColIdx,
827 numsortkeys * sizeof(AttrNumber)) != 0)
828 elog(ERROR, "MergeAppend child's targetlist doesn't match MergeAppend");
829 Assert(memcmp(sortOperators, node->sortOperators,
830 numsortkeys * sizeof(Oid)) == 0);
831 Assert(memcmp(collations, node->collations,
832 numsortkeys * sizeof(Oid)) == 0);
833 Assert(memcmp(nullsFirst, node->nullsFirst,
834 numsortkeys * sizeof(bool)) == 0);
836 /* Now, insert a Sort node if subplan isn't sufficiently ordered */
837 if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
838 subplan = (Plan *) make_sort(root, subplan, numsortkeys,
839 sortColIdx, sortOperators,
840 collations, nullsFirst,
841 best_path->limit_tuples);
843 subplans = lappend(subplans, subplan);
846 node->mergeplans = subplans;
848 return (Plan *) node;
853 * Create a Result plan for 'best_path'.
854 * This is only used for the case of a query with an empty jointree.
856 * Returns a Plan node.
859 create_result_plan(PlannerInfo *root, ResultPath *best_path)
864 /* The tlist will be installed later, since we have no RelOptInfo */
865 Assert(best_path->path.parent == NULL);
868 /* best_path->quals is just bare clauses */
870 quals = order_qual_clauses(root, best_path->quals);
872 return make_result(root, tlist, (Node *) quals, NULL);
876 * create_material_plan
877 * Create a Material plan for 'best_path' and (recursively) plans
880 * Returns a Plan node.
883 create_material_plan(PlannerInfo *root, MaterialPath *best_path)
888 subplan = create_plan_recurse(root, best_path->subpath);
890 /* We don't want any excess columns in the materialized tuples */
891 disuse_physical_tlist(root, subplan, best_path->subpath);
893 plan = make_material(subplan);
895 copy_path_costsize(&plan->plan, (Path *) best_path);
902 * Create a Unique plan for 'best_path' and (recursively) plans
905 * Returns a Plan node.
908 create_unique_plan(PlannerInfo *root, UniquePath *best_path)
918 AttrNumber *groupColIdx;
922 subplan = create_plan_recurse(root, best_path->subpath);
924 /* Done if we don't need to do any actual unique-ifying */
925 if (best_path->umethod == UNIQUE_PATH_NOOP)
929 * As constructed, the subplan has a "flat" tlist containing just the Vars
930 * needed here and at upper levels. The values we are supposed to
931 * unique-ify may be expressions in these variables. We have to add any
932 * such expressions to the subplan's tlist.
934 * The subplan may have a "physical" tlist if it is a simple scan plan. If
935 * we're going to sort, this should be reduced to the regular tlist, so
936 * that we don't sort more data than we need to. For hashing, the tlist
937 * should be left as-is if we don't need to add any expressions; but if we
938 * do have to add expressions, then a projection step will be needed at
939 * runtime anyway, so we may as well remove unneeded items. Therefore
940 * newtlist starts from build_path_tlist() not just a copy of the
941 * subplan's tlist; and we don't install it into the subplan unless we are
942 * sorting or stuff has to be added.
944 in_operators = best_path->in_operators;
945 uniq_exprs = best_path->uniq_exprs;
947 /* initialize modified subplan tlist as just the "required" vars */
948 newtlist = build_path_tlist(root, &best_path->path);
949 nextresno = list_length(newtlist) + 1;
952 foreach(l, uniq_exprs)
954 Node *uniqexpr = lfirst(l);
957 tle = tlist_member(uniqexpr, newtlist);
960 tle = makeTargetEntry((Expr *) uniqexpr,
964 newtlist = lappend(newtlist, tle);
970 if (newitems || best_path->umethod == UNIQUE_PATH_SORT)
973 * If the top plan node can't do projections and its existing target
974 * list isn't already what we need, we need to add a Result node to
977 if (!is_projection_capable_plan(subplan) &&
978 !tlist_same_exprs(newtlist, subplan->targetlist))
979 subplan = (Plan *) make_result(root, newtlist, NULL, subplan);
981 subplan->targetlist = newtlist;
985 * Build control information showing which subplan output columns are to
986 * be examined by the grouping step. Unfortunately we can't merge this
987 * with the previous loop, since we didn't then know which version of the
988 * subplan tlist we'd end up using.
990 newtlist = subplan->targetlist;
991 numGroupCols = list_length(uniq_exprs);
992 groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber));
995 foreach(l, uniq_exprs)
997 Node *uniqexpr = lfirst(l);
1000 tle = tlist_member(uniqexpr, newtlist);
1001 if (!tle) /* shouldn't happen */
1002 elog(ERROR, "failed to find unique expression in subplan tlist");
1003 groupColIdx[groupColPos++] = tle->resno;
1006 if (best_path->umethod == UNIQUE_PATH_HASH)
1009 Oid *groupOperators;
1011 numGroups = (long) Min(best_path->path.rows, (double) LONG_MAX);
1014 * Get the hashable equality operators for the Agg node to use.
1015 * Normally these are the same as the IN clause operators, but if
1016 * those are cross-type operators then the equality operators are the
1017 * ones for the IN clause operators' RHS datatype.
1019 groupOperators = (Oid *) palloc(numGroupCols * sizeof(Oid));
1021 foreach(l, in_operators)
1023 Oid in_oper = lfirst_oid(l);
1026 if (!get_compatible_hash_operators(in_oper, NULL, &eq_oper))
1027 elog(ERROR, "could not find compatible hash operator for operator %u",
1029 groupOperators[groupColPos++] = eq_oper;
1033 * Since the Agg node is going to project anyway, we can give it the
1034 * minimum output tlist, without any stuff we might have added to the
1037 plan = (Plan *) make_agg(root,
1038 build_path_tlist(root, &best_path->path),
1050 List *sortList = NIL;
1052 /* Create an ORDER BY list to sort the input compatibly */
1054 foreach(l, in_operators)
1056 Oid in_oper = lfirst_oid(l);
1060 SortGroupClause *sortcl;
1062 sortop = get_ordering_op_for_equality_op(in_oper, false);
1063 if (!OidIsValid(sortop)) /* shouldn't happen */
1064 elog(ERROR, "could not find ordering operator for equality operator %u",
1068 * The Unique node will need equality operators. Normally these
1069 * are the same as the IN clause operators, but if those are
1070 * cross-type operators then the equality operators are the ones
1071 * for the IN clause operators' RHS datatype.
1073 eqop = get_equality_op_for_ordering_op(sortop, NULL);
1074 if (!OidIsValid(eqop)) /* shouldn't happen */
1075 elog(ERROR, "could not find equality operator for ordering operator %u",
1078 tle = get_tle_by_resno(subplan->targetlist,
1079 groupColIdx[groupColPos]);
1080 Assert(tle != NULL);
1082 sortcl = makeNode(SortGroupClause);
1083 sortcl->tleSortGroupRef = assignSortGroupRef(tle,
1084 subplan->targetlist);
1085 sortcl->eqop = eqop;
1086 sortcl->sortop = sortop;
1087 sortcl->nulls_first = false;
1088 sortcl->hashable = false; /* no need to make this accurate */
1089 sortList = lappend(sortList, sortcl);
1092 plan = (Plan *) make_sort_from_sortclauses(root, sortList, subplan);
1093 plan = (Plan *) make_unique(plan, sortList);
1096 /* Adjust output size estimate (other fields should be OK already) */
1097 plan->plan_rows = best_path->path.rows;
1103 /*****************************************************************************
1105 * BASE-RELATION SCAN METHODS
1107 *****************************************************************************/
1111 * create_seqscan_plan
1112 * Returns a seqscan plan for the base relation scanned by 'best_path'
1113 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1116 create_seqscan_plan(PlannerInfo *root, Path *best_path,
1117 List *tlist, List *scan_clauses)
1120 Index scan_relid = best_path->parent->relid;
1122 /* it should be a base rel... */
1123 Assert(scan_relid > 0);
1124 Assert(best_path->parent->rtekind == RTE_RELATION);
1126 /* Sort clauses into best execution order */
1127 scan_clauses = order_qual_clauses(root, scan_clauses);
1129 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1130 scan_clauses = extract_actual_clauses(scan_clauses, false);
1132 /* Replace any outer-relation variables with nestloop params */
1133 if (best_path->param_info)
1135 scan_clauses = (List *)
1136 replace_nestloop_params(root, (Node *) scan_clauses);
1139 scan_plan = make_seqscan(tlist,
1143 copy_path_costsize(&scan_plan->plan, best_path);
1149 * create_samplescan_plan
1150 * Returns a samplecan plan for the base relation scanned by 'best_path'
1151 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1154 create_samplescan_plan(PlannerInfo *root, Path *best_path,
1155 List *tlist, List *scan_clauses)
1157 SampleScan *scan_plan;
1158 Index scan_relid = best_path->parent->relid;
1160 /* it should be a base rel with tablesample clause... */
1161 Assert(scan_relid > 0);
1162 Assert(best_path->parent->rtekind == RTE_RELATION);
1163 Assert(best_path->pathtype == T_SampleScan);
1165 /* Sort clauses into best execution order */
1166 scan_clauses = order_qual_clauses(root, scan_clauses);
1168 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1169 scan_clauses = extract_actual_clauses(scan_clauses, false);
1171 /* Replace any outer-relation variables with nestloop params */
1172 if (best_path->param_info)
1174 scan_clauses = (List *)
1175 replace_nestloop_params(root, (Node *) scan_clauses);
1178 scan_plan = make_samplescan(tlist,
1182 copy_path_costsize(&scan_plan->plan, best_path);
1188 * create_indexscan_plan
1189 * Returns an indexscan plan for the base relation scanned by 'best_path'
1190 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1192 * We use this for both plain IndexScans and IndexOnlyScans, because the
1193 * qual preprocessing work is the same for both. Note that the caller tells
1194 * us which to build --- we don't look at best_path->path.pathtype, because
1195 * create_bitmap_subplan needs to be able to override the prior decision.
1198 create_indexscan_plan(PlannerInfo *root,
1199 IndexPath *best_path,
1205 List *indexquals = best_path->indexquals;
1206 List *indexorderbys = best_path->indexorderbys;
1207 Index baserelid = best_path->path.parent->relid;
1208 Oid indexoid = best_path->indexinfo->indexoid;
1210 List *stripped_indexquals;
1211 List *fixed_indexquals;
1212 List *fixed_indexorderbys;
1213 Oid *indexorderbyops = NULL;
1216 /* it should be a base rel... */
1217 Assert(baserelid > 0);
1218 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1221 * Build "stripped" indexquals structure (no RestrictInfos) to pass to
1222 * executor as indexqualorig
1224 stripped_indexquals = get_actual_clauses(indexquals);
1227 * The executor needs a copy with the indexkey on the left of each clause
1228 * and with index Vars substituted for table ones.
1230 fixed_indexquals = fix_indexqual_references(root, best_path);
1233 * Likewise fix up index attr references in the ORDER BY expressions.
1235 fixed_indexorderbys = fix_indexorderby_references(root, best_path);
1238 * The qpqual list must contain all restrictions not automatically handled
1239 * by the index, other than pseudoconstant clauses which will be handled
1240 * by a separate gating plan node. All the predicates in the indexquals
1241 * will be checked (either by the index itself, or by nodeIndexscan.c),
1242 * but if there are any "special" operators involved then they must be
1243 * included in qpqual. The upshot is that qpqual must contain
1244 * scan_clauses minus whatever appears in indexquals.
1246 * In normal cases simple pointer equality checks will be enough to spot
1247 * duplicate RestrictInfos, so we try that first.
1249 * Another common case is that a scan_clauses entry is generated from the
1250 * same EquivalenceClass as some indexqual, and is therefore redundant
1251 * with it, though not equal. (This happens when indxpath.c prefers a
1252 * different derived equality than what generate_join_implied_equalities
1253 * picked for a parameterized scan's ppi_clauses.)
1255 * In some situations (particularly with OR'd index conditions) we may
1256 * have scan_clauses that are not equal to, but are logically implied by,
1257 * the index quals; so we also try a predicate_implied_by() check to see
1258 * if we can discard quals that way. (predicate_implied_by assumes its
1259 * first input contains only immutable functions, so we have to check
1262 * We can also discard quals that are implied by a partial index's
1263 * predicate, but only in a plain SELECT; when scanning a target relation
1264 * of UPDATE/DELETE/SELECT FOR UPDATE, we must leave such quals in the
1265 * plan so that they'll be properly rechecked by EvalPlanQual testing.
1267 * Note: if you change this bit of code you should also look at
1268 * extract_nonindex_conditions() in costsize.c.
1271 foreach(l, scan_clauses)
1273 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1275 Assert(IsA(rinfo, RestrictInfo));
1276 if (rinfo->pseudoconstant)
1277 continue; /* we may drop pseudoconstants here */
1278 if (list_member_ptr(indexquals, rinfo))
1279 continue; /* simple duplicate */
1280 if (is_redundant_derived_clause(rinfo, indexquals))
1281 continue; /* derived from same EquivalenceClass */
1282 if (!contain_mutable_functions((Node *) rinfo->clause))
1284 List *clausel = list_make1(rinfo->clause);
1286 if (predicate_implied_by(clausel, indexquals))
1287 continue; /* provably implied by indexquals */
1288 if (best_path->indexinfo->indpred)
1290 if (baserelid != root->parse->resultRelation &&
1291 get_plan_rowmark(root->rowMarks, baserelid) == NULL)
1292 if (predicate_implied_by(clausel,
1293 best_path->indexinfo->indpred))
1294 continue; /* implied by index predicate */
1297 qpqual = lappend(qpqual, rinfo);
1300 /* Sort clauses into best execution order */
1301 qpqual = order_qual_clauses(root, qpqual);
1303 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1304 qpqual = extract_actual_clauses(qpqual, false);
1307 * We have to replace any outer-relation variables with nestloop params in
1308 * the indexqualorig, qpqual, and indexorderbyorig expressions. A bit
1309 * annoying to have to do this separately from the processing in
1310 * fix_indexqual_references --- rethink this when generalizing the inner
1311 * indexscan support. But note we can't really do this earlier because
1312 * it'd break the comparisons to predicates above ... (or would it? Those
1313 * wouldn't have outer refs)
1315 if (best_path->path.param_info)
1317 stripped_indexquals = (List *)
1318 replace_nestloop_params(root, (Node *) stripped_indexquals);
1320 replace_nestloop_params(root, (Node *) qpqual);
1321 indexorderbys = (List *)
1322 replace_nestloop_params(root, (Node *) indexorderbys);
1326 * If there are ORDER BY expressions, look up the sort operators for
1329 if (best_path->path.pathkeys && indexorderbys)
1331 int numOrderBys = list_length(indexorderbys);
1333 ListCell *pathkeyCell,
1337 EquivalenceMember *em;
1339 indexorderbyops = (Oid *) palloc(numOrderBys * sizeof(Oid));
1342 * PathKey contains pointer to the equivalence class, but that's not
1343 * enough because we need the expression's datatype to look up the
1344 * sort operator in the operator family. We have to dig the
1345 * equivalence member for the datatype.
1348 forboth (pathkeyCell, best_path->path.pathkeys, exprCell, indexorderbys)
1350 pathkey = (PathKey *) lfirst(pathkeyCell);
1351 expr = (Expr *) lfirst(exprCell);
1353 /* Find equivalence member for the order by expression */
1354 em = find_ec_member_for_expr(pathkey->pk_eclass, expr, NULL);
1356 /* Get sort operator from opfamily */
1357 indexorderbyops[i] = get_opfamily_member(pathkey->pk_opfamily,
1360 pathkey->pk_strategy);
1365 /* Finally ready to build the plan node */
1367 scan_plan = (Scan *) make_indexonlyscan(tlist,
1372 fixed_indexorderbys,
1373 best_path->indexinfo->indextlist,
1374 best_path->indexscandir);
1376 scan_plan = (Scan *) make_indexscan(tlist,
1381 stripped_indexquals,
1382 fixed_indexorderbys,
1385 best_path->indexscandir);
1387 copy_path_costsize(&scan_plan->plan, &best_path->path);
1393 * create_bitmap_scan_plan
1394 * Returns a bitmap scan plan for the base relation scanned by 'best_path'
1395 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1397 static BitmapHeapScan *
1398 create_bitmap_scan_plan(PlannerInfo *root,
1399 BitmapHeapPath *best_path,
1403 Index baserelid = best_path->path.parent->relid;
1404 Plan *bitmapqualplan;
1405 List *bitmapqualorig;
1410 BitmapHeapScan *scan_plan;
1412 /* it should be a base rel... */
1413 Assert(baserelid > 0);
1414 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1416 /* Process the bitmapqual tree into a Plan tree and qual lists */
1417 bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
1418 &bitmapqualorig, &indexquals,
1422 * The qpqual list must contain all restrictions not automatically handled
1423 * by the index, other than pseudoconstant clauses which will be handled
1424 * by a separate gating plan node. All the predicates in the indexquals
1425 * will be checked (either by the index itself, or by
1426 * nodeBitmapHeapscan.c), but if there are any "special" operators
1427 * involved then they must be added to qpqual. The upshot is that qpqual
1428 * must contain scan_clauses minus whatever appears in indexquals.
1430 * This loop is similar to the comparable code in create_indexscan_plan(),
1431 * but with some differences because it has to compare the scan clauses to
1432 * stripped (no RestrictInfos) indexquals. See comments there for more
1435 * In normal cases simple equal() checks will be enough to spot duplicate
1436 * clauses, so we try that first. We next see if the scan clause is
1437 * redundant with any top-level indexqual by virtue of being generated
1438 * from the same EC. After that, try predicate_implied_by().
1440 * Unlike create_indexscan_plan(), we need take no special thought here
1441 * for partial index predicates; this is because the predicate conditions
1442 * are already listed in bitmapqualorig and indexquals. Bitmap scans have
1443 * to do it that way because predicate conditions need to be rechecked if
1444 * the scan becomes lossy, so they have to be included in bitmapqualorig.
1447 foreach(l, scan_clauses)
1449 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1450 Node *clause = (Node *) rinfo->clause;
1452 Assert(IsA(rinfo, RestrictInfo));
1453 if (rinfo->pseudoconstant)
1454 continue; /* we may drop pseudoconstants here */
1455 if (list_member(indexquals, clause))
1456 continue; /* simple duplicate */
1457 if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
1458 continue; /* derived from same EquivalenceClass */
1459 if (!contain_mutable_functions(clause))
1461 List *clausel = list_make1(clause);
1463 if (predicate_implied_by(clausel, indexquals))
1464 continue; /* provably implied by indexquals */
1466 qpqual = lappend(qpqual, rinfo);
1469 /* Sort clauses into best execution order */
1470 qpqual = order_qual_clauses(root, qpqual);
1472 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1473 qpqual = extract_actual_clauses(qpqual, false);
1476 * When dealing with special operators, we will at this point have
1477 * duplicate clauses in qpqual and bitmapqualorig. We may as well drop
1478 * 'em from bitmapqualorig, since there's no point in making the tests
1481 bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
1484 * We have to replace any outer-relation variables with nestloop params in
1485 * the qpqual and bitmapqualorig expressions. (This was already done for
1486 * expressions attached to plan nodes in the bitmapqualplan tree.)
1488 if (best_path->path.param_info)
1491 replace_nestloop_params(root, (Node *) qpqual);
1492 bitmapqualorig = (List *)
1493 replace_nestloop_params(root, (Node *) bitmapqualorig);
1496 /* Finally ready to build the plan node */
1497 scan_plan = make_bitmap_heapscan(tlist,
1503 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
1509 * Given a bitmapqual tree, generate the Plan tree that implements it
1511 * As byproducts, we also return in *qual and *indexqual the qual lists
1512 * (in implicit-AND form, without RestrictInfos) describing the original index
1513 * conditions and the generated indexqual conditions. (These are the same in
1514 * simple cases, but when special index operators are involved, the former
1515 * list includes the special conditions while the latter includes the actual
1516 * indexable conditions derived from them.) Both lists include partial-index
1517 * predicates, because we have to recheck predicates as well as index
1518 * conditions if the bitmap scan becomes lossy.
1520 * In addition, we return a list of EquivalenceClass pointers for all the
1521 * top-level indexquals that were possibly-redundantly derived from ECs.
1522 * This allows removal of scan_clauses that are redundant with such quals.
1523 * (We do not attempt to detect such redundancies for quals that are within
1524 * OR subtrees. This could be done in a less hacky way if we returned the
1525 * indexquals in RestrictInfo form, but that would be slower and still pretty
1526 * messy, since we'd have to build new RestrictInfos in many cases.)
1529 create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
1530 List **qual, List **indexqual, List **indexECs)
1534 if (IsA(bitmapqual, BitmapAndPath))
1536 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
1537 List *subplans = NIL;
1538 List *subquals = NIL;
1539 List *subindexquals = NIL;
1540 List *subindexECs = NIL;
1544 * There may well be redundant quals among the subplans, since a
1545 * top-level WHERE qual might have gotten used to form several
1546 * different index quals. We don't try exceedingly hard to eliminate
1547 * redundancies, but we do eliminate obvious duplicates by using
1548 * list_concat_unique.
1550 foreach(l, apath->bitmapquals)
1557 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1558 &subqual, &subindexqual,
1560 subplans = lappend(subplans, subplan);
1561 subquals = list_concat_unique(subquals, subqual);
1562 subindexquals = list_concat_unique(subindexquals, subindexqual);
1563 /* Duplicates in indexECs aren't worth getting rid of */
1564 subindexECs = list_concat(subindexECs, subindexEC);
1566 plan = (Plan *) make_bitmap_and(subplans);
1567 plan->startup_cost = apath->path.startup_cost;
1568 plan->total_cost = apath->path.total_cost;
1570 clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
1571 plan->plan_width = 0; /* meaningless */
1573 *indexqual = subindexquals;
1574 *indexECs = subindexECs;
1576 else if (IsA(bitmapqual, BitmapOrPath))
1578 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
1579 List *subplans = NIL;
1580 List *subquals = NIL;
1581 List *subindexquals = NIL;
1582 bool const_true_subqual = false;
1583 bool const_true_subindexqual = false;
1587 * Here, we only detect qual-free subplans. A qual-free subplan would
1588 * cause us to generate "... OR true ..." which we may as well reduce
1589 * to just "true". We do not try to eliminate redundant subclauses
1590 * because (a) it's not as likely as in the AND case, and (b) we might
1591 * well be working with hundreds or even thousands of OR conditions,
1592 * perhaps from a long IN list. The performance of list_append_unique
1593 * would be unacceptable.
1595 foreach(l, opath->bitmapquals)
1602 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1603 &subqual, &subindexqual,
1605 subplans = lappend(subplans, subplan);
1607 const_true_subqual = true;
1608 else if (!const_true_subqual)
1609 subquals = lappend(subquals,
1610 make_ands_explicit(subqual));
1611 if (subindexqual == NIL)
1612 const_true_subindexqual = true;
1613 else if (!const_true_subindexqual)
1614 subindexquals = lappend(subindexquals,
1615 make_ands_explicit(subindexqual));
1619 * In the presence of ScalarArrayOpExpr quals, we might have built
1620 * BitmapOrPaths with just one subpath; don't add an OR step.
1622 if (list_length(subplans) == 1)
1624 plan = (Plan *) linitial(subplans);
1628 plan = (Plan *) make_bitmap_or(subplans);
1629 plan->startup_cost = opath->path.startup_cost;
1630 plan->total_cost = opath->path.total_cost;
1632 clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
1633 plan->plan_width = 0; /* meaningless */
1637 * If there were constant-TRUE subquals, the OR reduces to constant
1638 * TRUE. Also, avoid generating one-element ORs, which could happen
1639 * due to redundancy elimination or ScalarArrayOpExpr quals.
1641 if (const_true_subqual)
1643 else if (list_length(subquals) <= 1)
1646 *qual = list_make1(make_orclause(subquals));
1647 if (const_true_subindexqual)
1649 else if (list_length(subindexquals) <= 1)
1650 *indexqual = subindexquals;
1652 *indexqual = list_make1(make_orclause(subindexquals));
1655 else if (IsA(bitmapqual, IndexPath))
1657 IndexPath *ipath = (IndexPath *) bitmapqual;
1662 /* Use the regular indexscan plan build machinery... */
1663 iscan = (IndexScan *) create_indexscan_plan(root, ipath,
1665 Assert(IsA(iscan, IndexScan));
1666 /* then convert to a bitmap indexscan */
1667 plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
1670 iscan->indexqualorig);
1671 plan->startup_cost = 0.0;
1672 plan->total_cost = ipath->indextotalcost;
1674 clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
1675 plan->plan_width = 0; /* meaningless */
1676 *qual = get_actual_clauses(ipath->indexclauses);
1677 *indexqual = get_actual_clauses(ipath->indexquals);
1678 foreach(l, ipath->indexinfo->indpred)
1680 Expr *pred = (Expr *) lfirst(l);
1683 * We know that the index predicate must have been implied by the
1684 * query condition as a whole, but it may or may not be implied by
1685 * the conditions that got pushed into the bitmapqual. Avoid
1686 * generating redundant conditions.
1688 if (!predicate_implied_by(list_make1(pred), ipath->indexclauses))
1690 *qual = lappend(*qual, pred);
1691 *indexqual = lappend(*indexqual, pred);
1695 foreach(l, ipath->indexquals)
1697 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1699 if (rinfo->parent_ec)
1700 subindexECs = lappend(subindexECs, rinfo->parent_ec);
1702 *indexECs = subindexECs;
1706 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
1707 plan = NULL; /* keep compiler quiet */
1714 * create_tidscan_plan
1715 * Returns a tidscan plan for the base relation scanned by 'best_path'
1716 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1719 create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
1720 List *tlist, List *scan_clauses)
1723 Index scan_relid = best_path->path.parent->relid;
1724 List *tidquals = best_path->tidquals;
1727 /* it should be a base rel... */
1728 Assert(scan_relid > 0);
1729 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1731 /* Sort clauses into best execution order */
1732 scan_clauses = order_qual_clauses(root, scan_clauses);
1734 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1735 scan_clauses = extract_actual_clauses(scan_clauses, false);
1737 /* Replace any outer-relation variables with nestloop params */
1738 if (best_path->path.param_info)
1741 replace_nestloop_params(root, (Node *) tidquals);
1742 scan_clauses = (List *)
1743 replace_nestloop_params(root, (Node *) scan_clauses);
1747 * Remove any clauses that are TID quals. This is a bit tricky since the
1748 * tidquals list has implicit OR semantics.
1750 ortidquals = tidquals;
1751 if (list_length(ortidquals) > 1)
1752 ortidquals = list_make1(make_orclause(ortidquals));
1753 scan_clauses = list_difference(scan_clauses, ortidquals);
1755 scan_plan = make_tidscan(tlist,
1760 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
1766 * create_subqueryscan_plan
1767 * Returns a subqueryscan plan for the base relation scanned by 'best_path'
1768 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1770 static SubqueryScan *
1771 create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
1772 List *tlist, List *scan_clauses)
1774 SubqueryScan *scan_plan;
1775 Index scan_relid = best_path->parent->relid;
1777 /* it should be a subquery base rel... */
1778 Assert(scan_relid > 0);
1779 Assert(best_path->parent->rtekind == RTE_SUBQUERY);
1781 /* Sort clauses into best execution order */
1782 scan_clauses = order_qual_clauses(root, scan_clauses);
1784 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1785 scan_clauses = extract_actual_clauses(scan_clauses, false);
1787 /* Replace any outer-relation variables with nestloop params */
1788 if (best_path->param_info)
1790 scan_clauses = (List *)
1791 replace_nestloop_params(root, (Node *) scan_clauses);
1792 process_subquery_nestloop_params(root,
1793 best_path->parent->subplan_params);
1796 scan_plan = make_subqueryscan(tlist,
1799 best_path->parent->subplan);
1801 copy_path_costsize(&scan_plan->scan.plan, best_path);
1807 * create_functionscan_plan
1808 * Returns a functionscan plan for the base relation scanned by 'best_path'
1809 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1811 static FunctionScan *
1812 create_functionscan_plan(PlannerInfo *root, Path *best_path,
1813 List *tlist, List *scan_clauses)
1815 FunctionScan *scan_plan;
1816 Index scan_relid = best_path->parent->relid;
1820 /* it should be a function base rel... */
1821 Assert(scan_relid > 0);
1822 rte = planner_rt_fetch(scan_relid, root);
1823 Assert(rte->rtekind == RTE_FUNCTION);
1824 functions = rte->functions;
1826 /* Sort clauses into best execution order */
1827 scan_clauses = order_qual_clauses(root, scan_clauses);
1829 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1830 scan_clauses = extract_actual_clauses(scan_clauses, false);
1832 /* Replace any outer-relation variables with nestloop params */
1833 if (best_path->param_info)
1835 scan_clauses = (List *)
1836 replace_nestloop_params(root, (Node *) scan_clauses);
1837 /* The function expressions could contain nestloop params, too */
1838 functions = (List *) replace_nestloop_params(root, (Node *) functions);
1841 scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
1842 functions, rte->funcordinality);
1844 copy_path_costsize(&scan_plan->scan.plan, best_path);
1850 * create_valuesscan_plan
1851 * Returns a valuesscan plan for the base relation scanned by 'best_path'
1852 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1855 create_valuesscan_plan(PlannerInfo *root, Path *best_path,
1856 List *tlist, List *scan_clauses)
1858 ValuesScan *scan_plan;
1859 Index scan_relid = best_path->parent->relid;
1863 /* it should be a values base rel... */
1864 Assert(scan_relid > 0);
1865 rte = planner_rt_fetch(scan_relid, root);
1866 Assert(rte->rtekind == RTE_VALUES);
1867 values_lists = rte->values_lists;
1869 /* Sort clauses into best execution order */
1870 scan_clauses = order_qual_clauses(root, scan_clauses);
1872 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1873 scan_clauses = extract_actual_clauses(scan_clauses, false);
1875 /* Replace any outer-relation variables with nestloop params */
1876 if (best_path->param_info)
1878 scan_clauses = (List *)
1879 replace_nestloop_params(root, (Node *) scan_clauses);
1880 /* The values lists could contain nestloop params, too */
1881 values_lists = (List *)
1882 replace_nestloop_params(root, (Node *) values_lists);
1885 scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid,
1888 copy_path_costsize(&scan_plan->scan.plan, best_path);
1894 * create_ctescan_plan
1895 * Returns a ctescan plan for the base relation scanned by 'best_path'
1896 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1899 create_ctescan_plan(PlannerInfo *root, Path *best_path,
1900 List *tlist, List *scan_clauses)
1903 Index scan_relid = best_path->parent->relid;
1905 SubPlan *ctesplan = NULL;
1908 PlannerInfo *cteroot;
1913 Assert(scan_relid > 0);
1914 rte = planner_rt_fetch(scan_relid, root);
1915 Assert(rte->rtekind == RTE_CTE);
1916 Assert(!rte->self_reference);
1919 * Find the referenced CTE, and locate the SubPlan previously made for it.
1921 levelsup = rte->ctelevelsup;
1923 while (levelsup-- > 0)
1925 cteroot = cteroot->parent_root;
1926 if (!cteroot) /* shouldn't happen */
1927 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
1931 * Note: cte_plan_ids can be shorter than cteList, if we are still working
1932 * on planning the CTEs (ie, this is a side-reference from another CTE).
1933 * So we mustn't use forboth here.
1936 foreach(lc, cteroot->parse->cteList)
1938 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
1940 if (strcmp(cte->ctename, rte->ctename) == 0)
1944 if (lc == NULL) /* shouldn't happen */
1945 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
1946 if (ndx >= list_length(cteroot->cte_plan_ids))
1947 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
1948 plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
1949 Assert(plan_id > 0);
1950 foreach(lc, cteroot->init_plans)
1952 ctesplan = (SubPlan *) lfirst(lc);
1953 if (ctesplan->plan_id == plan_id)
1956 if (lc == NULL) /* shouldn't happen */
1957 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
1960 * We need the CTE param ID, which is the sole member of the SubPlan's
1963 cte_param_id = linitial_int(ctesplan->setParam);
1965 /* Sort clauses into best execution order */
1966 scan_clauses = order_qual_clauses(root, scan_clauses);
1968 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1969 scan_clauses = extract_actual_clauses(scan_clauses, false);
1971 /* Replace any outer-relation variables with nestloop params */
1972 if (best_path->param_info)
1974 scan_clauses = (List *)
1975 replace_nestloop_params(root, (Node *) scan_clauses);
1978 scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
1979 plan_id, cte_param_id);
1981 copy_path_costsize(&scan_plan->scan.plan, best_path);
1987 * create_worktablescan_plan
1988 * Returns a worktablescan plan for the base relation scanned by 'best_path'
1989 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1991 static WorkTableScan *
1992 create_worktablescan_plan(PlannerInfo *root, Path *best_path,
1993 List *tlist, List *scan_clauses)
1995 WorkTableScan *scan_plan;
1996 Index scan_relid = best_path->parent->relid;
1999 PlannerInfo *cteroot;
2001 Assert(scan_relid > 0);
2002 rte = planner_rt_fetch(scan_relid, root);
2003 Assert(rte->rtekind == RTE_CTE);
2004 Assert(rte->self_reference);
2007 * We need to find the worktable param ID, which is in the plan level
2008 * that's processing the recursive UNION, which is one level *below* where
2009 * the CTE comes from.
2011 levelsup = rte->ctelevelsup;
2012 if (levelsup == 0) /* shouldn't happen */
2013 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2016 while (levelsup-- > 0)
2018 cteroot = cteroot->parent_root;
2019 if (!cteroot) /* shouldn't happen */
2020 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2022 if (cteroot->wt_param_id < 0) /* shouldn't happen */
2023 elog(ERROR, "could not find param ID for CTE \"%s\"", rte->ctename);
2025 /* Sort clauses into best execution order */
2026 scan_clauses = order_qual_clauses(root, scan_clauses);
2028 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2029 scan_clauses = extract_actual_clauses(scan_clauses, false);
2031 /* Replace any outer-relation variables with nestloop params */
2032 if (best_path->param_info)
2034 scan_clauses = (List *)
2035 replace_nestloop_params(root, (Node *) scan_clauses);
2038 scan_plan = make_worktablescan(tlist, scan_clauses, scan_relid,
2039 cteroot->wt_param_id);
2041 copy_path_costsize(&scan_plan->scan.plan, best_path);
2047 * create_foreignscan_plan
2048 * Returns a foreignscan plan for the relation scanned by 'best_path'
2049 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
2051 static ForeignScan *
2052 create_foreignscan_plan(PlannerInfo *root, ForeignPath *best_path,
2053 List *tlist, List *scan_clauses)
2055 ForeignScan *scan_plan;
2056 RelOptInfo *rel = best_path->path.parent;
2057 Index scan_relid = rel->relid;
2058 Oid rel_oid = InvalidOid;
2059 Bitmapset *attrs_used = NULL;
2063 Assert(rel->fdwroutine != NULL);
2066 * If we're scanning a base relation, fetch its OID. (Irrelevant if
2067 * scanning a join relation.)
2073 Assert(rel->rtekind == RTE_RELATION);
2074 rte = planner_rt_fetch(scan_relid, root);
2075 Assert(rte->rtekind == RTE_RELATION);
2076 rel_oid = rte->relid;
2080 * Sort clauses into best execution order. We do this first since the FDW
2081 * might have more info than we do and wish to adjust the ordering.
2083 scan_clauses = order_qual_clauses(root, scan_clauses);
2086 * Let the FDW perform its processing on the restriction clauses and
2087 * generate the plan node. Note that the FDW might remove restriction
2088 * clauses that it intends to execute remotely, or even add more (if it
2089 * has selected some join clauses for remote use but also wants them
2090 * rechecked locally).
2092 scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid,
2094 tlist, scan_clauses);
2096 /* Copy cost data from Path to Plan; no need to make FDW do this */
2097 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
2099 /* Copy foreign server OID; likewise, no need to make FDW do this */
2100 scan_plan->fs_server = rel->serverid;
2102 /* Likewise, copy the relids that are represented by this foreign scan */
2103 scan_plan->fs_relids = best_path->path.parent->relids;
2106 * Replace any outer-relation variables with nestloop params in the qual
2107 * and fdw_exprs expressions. We do this last so that the FDW doesn't
2108 * have to be involved. (Note that parts of fdw_exprs could have come
2109 * from join clauses, so doing this beforehand on the scan_clauses
2110 * wouldn't work.) We assume fdw_scan_tlist contains no such variables.
2112 if (best_path->path.param_info)
2114 scan_plan->scan.plan.qual = (List *)
2115 replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
2116 scan_plan->fdw_exprs = (List *)
2117 replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
2121 * Detect whether any system columns are requested from rel. This is a
2122 * bit of a kluge and might go away someday, so we intentionally leave it
2123 * out of the API presented to FDWs.
2125 * First, examine all the attributes needed for joins or final output.
2126 * Note: we must look at reltargetlist, not the attr_needed data, because
2127 * attr_needed isn't computed for inheritance child rels.
2129 pull_varattnos((Node *) rel->reltargetlist, rel->relid, &attrs_used);
2131 /* Add all the attributes used by restriction clauses. */
2132 foreach(lc, rel->baserestrictinfo)
2134 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2136 pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
2139 /* Now, are any system columns requested from rel? */
2140 scan_plan->fsSystemCol = false;
2141 for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
2143 if (bms_is_member(i - FirstLowInvalidHeapAttributeNumber, attrs_used))
2145 scan_plan->fsSystemCol = true;
2150 bms_free(attrs_used);
2156 * create_custom_plan
2158 * Transform a CustomPath into a Plan.
2161 create_customscan_plan(PlannerInfo *root, CustomPath *best_path,
2162 List *tlist, List *scan_clauses)
2165 RelOptInfo *rel = best_path->path.parent;
2168 * Sort clauses into the best execution order, although custom-scan
2169 * provider can reorder them again.
2171 scan_clauses = order_qual_clauses(root, scan_clauses);
2174 * Invoke custom plan provider to create the Plan node represented by the
2177 cplan = (CustomScan *) best_path->methods->PlanCustomPath(root,
2182 Assert(IsA(cplan, CustomScan));
2185 * Copy cost data from Path to Plan; no need to make custom-plan providers
2188 copy_path_costsize(&cplan->scan.plan, &best_path->path);
2190 /* Likewise, copy the relids that are represented by this custom scan */
2191 cplan->custom_relids = best_path->path.parent->relids;
2194 * Replace any outer-relation variables with nestloop params in the qual
2195 * and custom_exprs expressions. We do this last so that the custom-plan
2196 * provider doesn't have to be involved. (Note that parts of custom_exprs
2197 * could have come from join clauses, so doing this beforehand on the
2198 * scan_clauses wouldn't work.) We assume custom_scan_tlist contains no
2201 if (best_path->path.param_info)
2203 cplan->scan.plan.qual = (List *)
2204 replace_nestloop_params(root, (Node *) cplan->scan.plan.qual);
2205 cplan->custom_exprs = (List *)
2206 replace_nestloop_params(root, (Node *) cplan->custom_exprs);
2213 /*****************************************************************************
2217 *****************************************************************************/
2220 create_nestloop_plan(PlannerInfo *root,
2221 NestPath *best_path,
2225 NestLoop *join_plan;
2226 List *tlist = build_path_tlist(root, &best_path->path);
2227 List *joinrestrictclauses = best_path->joinrestrictinfo;
2236 /* Sort join qual clauses into best execution order */
2237 joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
2239 /* Get the join qual clauses (in plain expression form) */
2240 /* Any pseudoconstant clauses are ignored here */
2241 if (IS_OUTER_JOIN(best_path->jointype))
2243 extract_actual_join_clauses(joinrestrictclauses,
2244 &joinclauses, &otherclauses);
2248 /* We can treat all clauses alike for an inner join */
2249 joinclauses = extract_actual_clauses(joinrestrictclauses, false);
2253 /* Replace any outer-relation variables with nestloop params */
2254 if (best_path->path.param_info)
2256 joinclauses = (List *)
2257 replace_nestloop_params(root, (Node *) joinclauses);
2258 otherclauses = (List *)
2259 replace_nestloop_params(root, (Node *) otherclauses);
2263 * Identify any nestloop parameters that should be supplied by this join
2264 * node, and move them from root->curOuterParams to the nestParams list.
2266 outerrelids = best_path->outerjoinpath->parent->relids;
2269 for (cell = list_head(root->curOuterParams); cell; cell = next)
2271 NestLoopParam *nlp = (NestLoopParam *) lfirst(cell);
2274 if (IsA(nlp->paramval, Var) &&
2275 bms_is_member(nlp->paramval->varno, outerrelids))
2277 root->curOuterParams = list_delete_cell(root->curOuterParams,
2279 nestParams = lappend(nestParams, nlp);
2281 else if (IsA(nlp->paramval, PlaceHolderVar) &&
2282 bms_overlap(((PlaceHolderVar *) nlp->paramval)->phrels,
2284 bms_is_subset(find_placeholder_info(root,
2285 (PlaceHolderVar *) nlp->paramval,
2289 root->curOuterParams = list_delete_cell(root->curOuterParams,
2291 nestParams = lappend(nestParams, nlp);
2297 join_plan = make_nestloop(tlist,
2303 best_path->jointype);
2305 copy_path_costsize(&join_plan->join.plan, &best_path->path);
2311 create_mergejoin_plan(PlannerInfo *root,
2312 MergePath *best_path,
2316 List *tlist = build_path_tlist(root, &best_path->jpath.path);
2320 List *outerpathkeys;
2321 List *innerpathkeys;
2324 Oid *mergecollations;
2325 int *mergestrategies;
2326 bool *mergenullsfirst;
2327 MergeJoin *join_plan;
2333 /* Sort join qual clauses into best execution order */
2334 /* NB: do NOT reorder the mergeclauses */
2335 joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
2337 /* Get the join qual clauses (in plain expression form) */
2338 /* Any pseudoconstant clauses are ignored here */
2339 if (IS_OUTER_JOIN(best_path->jpath.jointype))
2341 extract_actual_join_clauses(joinclauses,
2342 &joinclauses, &otherclauses);
2346 /* We can treat all clauses alike for an inner join */
2347 joinclauses = extract_actual_clauses(joinclauses, false);
2352 * Remove the mergeclauses from the list of join qual clauses, leaving the
2353 * list of quals that must be checked as qpquals.
2355 mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
2356 joinclauses = list_difference(joinclauses, mergeclauses);
2359 * Replace any outer-relation variables with nestloop params. There
2360 * should not be any in the mergeclauses.
2362 if (best_path->jpath.path.param_info)
2364 joinclauses = (List *)
2365 replace_nestloop_params(root, (Node *) joinclauses);
2366 otherclauses = (List *)
2367 replace_nestloop_params(root, (Node *) otherclauses);
2371 * Rearrange mergeclauses, if needed, so that the outer variable is always
2372 * on the left; mark the mergeclause restrictinfos with correct
2373 * outer_is_left status.
2375 mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
2376 best_path->jpath.outerjoinpath->parent->relids);
2379 * Create explicit sort nodes for the outer and inner paths if necessary.
2380 * Make sure there are no excess columns in the inputs if sorting.
2382 if (best_path->outersortkeys)
2384 disuse_physical_tlist(root, outer_plan, best_path->jpath.outerjoinpath);
2385 outer_plan = (Plan *)
2386 make_sort_from_pathkeys(root,
2388 best_path->outersortkeys,
2390 outerpathkeys = best_path->outersortkeys;
2393 outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
2395 if (best_path->innersortkeys)
2397 disuse_physical_tlist(root, inner_plan, best_path->jpath.innerjoinpath);
2398 inner_plan = (Plan *)
2399 make_sort_from_pathkeys(root,
2401 best_path->innersortkeys,
2403 innerpathkeys = best_path->innersortkeys;
2406 innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
2409 * If specified, add a materialize node to shield the inner plan from the
2410 * need to handle mark/restore.
2412 if (best_path->materialize_inner)
2414 Plan *matplan = (Plan *) make_material(inner_plan);
2417 * We assume the materialize will not spill to disk, and therefore
2418 * charge just cpu_operator_cost per tuple. (Keep this estimate in
2419 * sync with final_cost_mergejoin.)
2421 copy_plan_costsize(matplan, inner_plan);
2422 matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
2424 inner_plan = matplan;
2428 * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
2429 * executor. The information is in the pathkeys for the two inputs, but
2430 * we need to be careful about the possibility of mergeclauses sharing a
2431 * pathkey (compare find_mergeclauses_for_pathkeys()).
2433 nClauses = list_length(mergeclauses);
2434 Assert(nClauses == list_length(best_path->path_mergeclauses));
2435 mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
2436 mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
2437 mergestrategies = (int *) palloc(nClauses * sizeof(int));
2438 mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
2440 lop = list_head(outerpathkeys);
2441 lip = list_head(innerpathkeys);
2443 foreach(lc, best_path->path_mergeclauses)
2445 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2446 EquivalenceClass *oeclass;
2447 EquivalenceClass *ieclass;
2450 EquivalenceClass *opeclass;
2451 EquivalenceClass *ipeclass;
2454 /* fetch outer/inner eclass from mergeclause */
2455 Assert(IsA(rinfo, RestrictInfo));
2456 if (rinfo->outer_is_left)
2458 oeclass = rinfo->left_ec;
2459 ieclass = rinfo->right_ec;
2463 oeclass = rinfo->right_ec;
2464 ieclass = rinfo->left_ec;
2466 Assert(oeclass != NULL);
2467 Assert(ieclass != NULL);
2470 * For debugging purposes, we check that the eclasses match the paths'
2471 * pathkeys. In typical cases the merge clauses are one-to-one with
2472 * the pathkeys, but when dealing with partially redundant query
2473 * conditions, we might have clauses that re-reference earlier path
2474 * keys. The case that we need to reject is where a pathkey is
2475 * entirely skipped over.
2477 * lop and lip reference the first as-yet-unused pathkey elements;
2478 * it's okay to match them, or any element before them. If they're
2479 * NULL then we have found all pathkey elements to be used.
2483 opathkey = (PathKey *) lfirst(lop);
2484 opeclass = opathkey->pk_eclass;
2485 if (oeclass == opeclass)
2487 /* fast path for typical case */
2492 /* redundant clauses ... must match something before lop */
2493 foreach(l2, outerpathkeys)
2497 opathkey = (PathKey *) lfirst(l2);
2498 opeclass = opathkey->pk_eclass;
2499 if (oeclass == opeclass)
2502 if (oeclass != opeclass)
2503 elog(ERROR, "outer pathkeys do not match mergeclauses");
2508 /* redundant clauses ... must match some already-used pathkey */
2511 foreach(l2, outerpathkeys)
2513 opathkey = (PathKey *) lfirst(l2);
2514 opeclass = opathkey->pk_eclass;
2515 if (oeclass == opeclass)
2519 elog(ERROR, "outer pathkeys do not match mergeclauses");
2524 ipathkey = (PathKey *) lfirst(lip);
2525 ipeclass = ipathkey->pk_eclass;
2526 if (ieclass == ipeclass)
2528 /* fast path for typical case */
2533 /* redundant clauses ... must match something before lip */
2534 foreach(l2, innerpathkeys)
2538 ipathkey = (PathKey *) lfirst(l2);
2539 ipeclass = ipathkey->pk_eclass;
2540 if (ieclass == ipeclass)
2543 if (ieclass != ipeclass)
2544 elog(ERROR, "inner pathkeys do not match mergeclauses");
2549 /* redundant clauses ... must match some already-used pathkey */
2552 foreach(l2, innerpathkeys)
2554 ipathkey = (PathKey *) lfirst(l2);
2555 ipeclass = ipathkey->pk_eclass;
2556 if (ieclass == ipeclass)
2560 elog(ERROR, "inner pathkeys do not match mergeclauses");
2563 /* pathkeys should match each other too (more debugging) */
2564 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
2565 opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
2566 opathkey->pk_strategy != ipathkey->pk_strategy ||
2567 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
2568 elog(ERROR, "left and right pathkeys do not match in mergejoin");
2570 /* OK, save info for executor */
2571 mergefamilies[i] = opathkey->pk_opfamily;
2572 mergecollations[i] = opathkey->pk_eclass->ec_collation;
2573 mergestrategies[i] = opathkey->pk_strategy;
2574 mergenullsfirst[i] = opathkey->pk_nulls_first;
2579 * Note: it is not an error if we have additional pathkey elements (i.e.,
2580 * lop or lip isn't NULL here). The input paths might be better-sorted
2581 * than we need for the current mergejoin.
2585 * Now we can build the mergejoin node.
2587 join_plan = make_mergejoin(tlist,
2597 best_path->jpath.jointype);
2599 /* Costs of sort and material steps are included in path cost already */
2600 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
2606 create_hashjoin_plan(PlannerInfo *root,
2607 HashPath *best_path,
2611 List *tlist = build_path_tlist(root, &best_path->jpath.path);
2615 Oid skewTable = InvalidOid;
2616 AttrNumber skewColumn = InvalidAttrNumber;
2617 bool skewInherit = false;
2618 Oid skewColType = InvalidOid;
2619 int32 skewColTypmod = -1;
2620 HashJoin *join_plan;
2623 /* Sort join qual clauses into best execution order */
2624 joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
2625 /* There's no point in sorting the hash clauses ... */
2627 /* Get the join qual clauses (in plain expression form) */
2628 /* Any pseudoconstant clauses are ignored here */
2629 if (IS_OUTER_JOIN(best_path->jpath.jointype))
2631 extract_actual_join_clauses(joinclauses,
2632 &joinclauses, &otherclauses);
2636 /* We can treat all clauses alike for an inner join */
2637 joinclauses = extract_actual_clauses(joinclauses, false);
2642 * Remove the hashclauses from the list of join qual clauses, leaving the
2643 * list of quals that must be checked as qpquals.
2645 hashclauses = get_actual_clauses(best_path->path_hashclauses);
2646 joinclauses = list_difference(joinclauses, hashclauses);
2649 * Replace any outer-relation variables with nestloop params. There
2650 * should not be any in the hashclauses.
2652 if (best_path->jpath.path.param_info)
2654 joinclauses = (List *)
2655 replace_nestloop_params(root, (Node *) joinclauses);
2656 otherclauses = (List *)
2657 replace_nestloop_params(root, (Node *) otherclauses);
2661 * Rearrange hashclauses, if needed, so that the outer variable is always
2664 hashclauses = get_switched_clauses(best_path->path_hashclauses,
2665 best_path->jpath.outerjoinpath->parent->relids);
2667 /* We don't want any excess columns in the hashed tuples */
2668 disuse_physical_tlist(root, inner_plan, best_path->jpath.innerjoinpath);
2670 /* If we expect batching, suppress excess columns in outer tuples too */
2671 if (best_path->num_batches > 1)
2672 disuse_physical_tlist(root, outer_plan, best_path->jpath.outerjoinpath);
2675 * If there is a single join clause and we can identify the outer variable
2676 * as a simple column reference, supply its identity for possible use in
2677 * skew optimization. (Note: in principle we could do skew optimization
2678 * with multiple join clauses, but we'd have to be able to determine the
2679 * most common combinations of outer values, which we don't currently have
2680 * enough stats for.)
2682 if (list_length(hashclauses) == 1)
2684 OpExpr *clause = (OpExpr *) linitial(hashclauses);
2687 Assert(is_opclause(clause));
2688 node = (Node *) linitial(clause->args);
2689 if (IsA(node, RelabelType))
2690 node = (Node *) ((RelabelType *) node)->arg;
2693 Var *var = (Var *) node;
2696 rte = root->simple_rte_array[var->varno];
2697 if (rte->rtekind == RTE_RELATION)
2699 skewTable = rte->relid;
2700 skewColumn = var->varattno;
2701 skewInherit = rte->inh;
2702 skewColType = var->vartype;
2703 skewColTypmod = var->vartypmod;
2709 * Build the hash node and hash join node.
2711 hash_plan = make_hash(inner_plan,
2717 join_plan = make_hashjoin(tlist,
2723 best_path->jpath.jointype);
2725 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
2731 /*****************************************************************************
2733 * SUPPORTING ROUTINES
2735 *****************************************************************************/
2738 * replace_nestloop_params
2739 * Replace outer-relation Vars and PlaceHolderVars in the given expression
2740 * with nestloop Params
2742 * All Vars and PlaceHolderVars belonging to the relation(s) identified by
2743 * root->curOuterRels are replaced by Params, and entries are added to
2744 * root->curOuterParams if not already present.
2747 replace_nestloop_params(PlannerInfo *root, Node *expr)
2749 /* No setup needed for tree walk, so away we go */
2750 return replace_nestloop_params_mutator(expr, root);
2754 replace_nestloop_params_mutator(Node *node, PlannerInfo *root)
2760 Var *var = (Var *) node;
2765 /* Upper-level Vars should be long gone at this point */
2766 Assert(var->varlevelsup == 0);
2767 /* If not to be replaced, we can just return the Var unmodified */
2768 if (!bms_is_member(var->varno, root->curOuterRels))
2770 /* Create a Param representing the Var */
2771 param = assign_nestloop_param_var(root, var);
2772 /* Is this param already listed in root->curOuterParams? */
2773 foreach(lc, root->curOuterParams)
2775 nlp = (NestLoopParam *) lfirst(lc);
2776 if (nlp->paramno == param->paramid)
2778 Assert(equal(var, nlp->paramval));
2779 /* Present, so we can just return the Param */
2780 return (Node *) param;
2784 nlp = makeNode(NestLoopParam);
2785 nlp->paramno = param->paramid;
2786 nlp->paramval = var;
2787 root->curOuterParams = lappend(root->curOuterParams, nlp);
2788 /* And return the replacement Param */
2789 return (Node *) param;
2791 if (IsA(node, PlaceHolderVar))
2793 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2798 /* Upper-level PlaceHolderVars should be long gone at this point */
2799 Assert(phv->phlevelsup == 0);
2802 * Check whether we need to replace the PHV. We use bms_overlap as a
2803 * cheap/quick test to see if the PHV might be evaluated in the outer
2804 * rels, and then grab its PlaceHolderInfo to tell for sure.
2806 if (!bms_overlap(phv->phrels, root->curOuterRels) ||
2807 !bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
2808 root->curOuterRels))
2811 * We can't replace the whole PHV, but we might still need to
2812 * replace Vars or PHVs within its expression, in case it ends up
2813 * actually getting evaluated here. (It might get evaluated in
2814 * this plan node, or some child node; in the latter case we don't
2815 * really need to process the expression here, but we haven't got
2816 * enough info to tell if that's the case.) Flat-copy the PHV
2817 * node and then recurse on its expression.
2819 * Note that after doing this, we might have different
2820 * representations of the contents of the same PHV in different
2821 * parts of the plan tree. This is OK because equal() will just
2822 * match on phid/phlevelsup, so setrefs.c will still recognize an
2823 * upper-level reference to a lower-level copy of the same PHV.
2825 PlaceHolderVar *newphv = makeNode(PlaceHolderVar);
2827 memcpy(newphv, phv, sizeof(PlaceHolderVar));
2828 newphv->phexpr = (Expr *)
2829 replace_nestloop_params_mutator((Node *) phv->phexpr,
2831 return (Node *) newphv;
2833 /* Create a Param representing the PlaceHolderVar */
2834 param = assign_nestloop_param_placeholdervar(root, phv);
2835 /* Is this param already listed in root->curOuterParams? */
2836 foreach(lc, root->curOuterParams)
2838 nlp = (NestLoopParam *) lfirst(lc);
2839 if (nlp->paramno == param->paramid)
2841 Assert(equal(phv, nlp->paramval));
2842 /* Present, so we can just return the Param */
2843 return (Node *) param;
2847 nlp = makeNode(NestLoopParam);
2848 nlp->paramno = param->paramid;
2849 nlp->paramval = (Var *) phv;
2850 root->curOuterParams = lappend(root->curOuterParams, nlp);
2851 /* And return the replacement Param */
2852 return (Node *) param;
2854 return expression_tree_mutator(node,
2855 replace_nestloop_params_mutator,
2860 * process_subquery_nestloop_params
2861 * Handle params of a parameterized subquery that need to be fed
2862 * from an outer nestloop.
2864 * Currently, that would be *all* params that a subquery in FROM has demanded
2865 * from the current query level, since they must be LATERAL references.
2867 * The subplan's references to the outer variables are already represented
2868 * as PARAM_EXEC Params, so we need not modify the subplan here. What we
2869 * do need to do is add entries to root->curOuterParams to signal the parent
2870 * nestloop plan node that it must provide these values.
2873 process_subquery_nestloop_params(PlannerInfo *root, List *subplan_params)
2877 foreach(ppl, subplan_params)
2879 PlannerParamItem *pitem = (PlannerParamItem *) lfirst(ppl);
2881 if (IsA(pitem->item, Var))
2883 Var *var = (Var *) pitem->item;
2887 /* If not from a nestloop outer rel, complain */
2888 if (!bms_is_member(var->varno, root->curOuterRels))
2889 elog(ERROR, "non-LATERAL parameter required by subquery");
2890 /* Is this param already listed in root->curOuterParams? */
2891 foreach(lc, root->curOuterParams)
2893 nlp = (NestLoopParam *) lfirst(lc);
2894 if (nlp->paramno == pitem->paramId)
2896 Assert(equal(var, nlp->paramval));
2897 /* Present, so nothing to do */
2904 nlp = makeNode(NestLoopParam);
2905 nlp->paramno = pitem->paramId;
2906 nlp->paramval = copyObject(var);
2907 root->curOuterParams = lappend(root->curOuterParams, nlp);
2910 else if (IsA(pitem->item, PlaceHolderVar))
2912 PlaceHolderVar *phv = (PlaceHolderVar *) pitem->item;
2916 /* If not from a nestloop outer rel, complain */
2917 if (!bms_is_subset(find_placeholder_info(root, phv, false)->ph_eval_at,
2918 root->curOuterRels))
2919 elog(ERROR, "non-LATERAL parameter required by subquery");
2920 /* Is this param already listed in root->curOuterParams? */
2921 foreach(lc, root->curOuterParams)
2923 nlp = (NestLoopParam *) lfirst(lc);
2924 if (nlp->paramno == pitem->paramId)
2926 Assert(equal(phv, nlp->paramval));
2927 /* Present, so nothing to do */
2934 nlp = makeNode(NestLoopParam);
2935 nlp->paramno = pitem->paramId;
2936 nlp->paramval = copyObject(phv);
2937 root->curOuterParams = lappend(root->curOuterParams, nlp);
2941 elog(ERROR, "unexpected type of subquery parameter");
2946 * fix_indexqual_references
2947 * Adjust indexqual clauses to the form the executor's indexqual
2950 * We have four tasks here:
2951 * * Remove RestrictInfo nodes from the input clauses.
2952 * * Replace any outer-relation Var or PHV nodes with nestloop Params.
2953 * (XXX eventually, that responsibility should go elsewhere?)
2954 * * Index keys must be represented by Var nodes with varattno set to the
2955 * index's attribute number, not the attribute number in the original rel.
2956 * * If the index key is on the right, commute the clause to put it on the
2959 * The result is a modified copy of the path's indexquals list --- the
2960 * original is not changed. Note also that the copy shares no substructure
2961 * with the original; this is needed in case there is a subplan in it (we need
2962 * two separate copies of the subplan tree, or things will go awry).
2965 fix_indexqual_references(PlannerInfo *root, IndexPath *index_path)
2967 IndexOptInfo *index = index_path->indexinfo;
2968 List *fixed_indexquals;
2972 fixed_indexquals = NIL;
2974 forboth(lcc, index_path->indexquals, lci, index_path->indexqualcols)
2976 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcc);
2977 int indexcol = lfirst_int(lci);
2980 Assert(IsA(rinfo, RestrictInfo));
2983 * Replace any outer-relation variables with nestloop params.
2985 * This also makes a copy of the clause, so it's safe to modify it
2988 clause = replace_nestloop_params(root, (Node *) rinfo->clause);
2990 if (IsA(clause, OpExpr))
2992 OpExpr *op = (OpExpr *) clause;
2994 if (list_length(op->args) != 2)
2995 elog(ERROR, "indexqual clause is not binary opclause");
2998 * Check to see if the indexkey is on the right; if so, commute
2999 * the clause. The indexkey should be the side that refers to
3000 * (only) the base relation.
3002 if (!bms_equal(rinfo->left_relids, index->rel->relids))
3006 * Now replace the indexkey expression with an index Var.
3008 linitial(op->args) = fix_indexqual_operand(linitial(op->args),
3012 else if (IsA(clause, RowCompareExpr))
3014 RowCompareExpr *rc = (RowCompareExpr *) clause;
3022 * Re-discover which index columns are used in the rowcompare.
3024 newrc = adjust_rowcompare_for_index(rc,
3031 * Trouble if adjust_rowcompare_for_index thought the
3032 * RowCompareExpr didn't match the index as-is; the clause should
3033 * have gone through that routine already.
3035 if (newrc != (Expr *) rc)
3036 elog(ERROR, "inconsistent results from adjust_rowcompare_for_index");
3039 * Check to see if the indexkey is on the right; if so, commute
3043 CommuteRowCompareExpr(rc);
3046 * Now replace the indexkey expressions with index Vars.
3048 Assert(list_length(rc->largs) == list_length(indexcolnos));
3049 forboth(lca, rc->largs, lcai, indexcolnos)
3051 lfirst(lca) = fix_indexqual_operand(lfirst(lca),
3056 else if (IsA(clause, ScalarArrayOpExpr))
3058 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
3060 /* Never need to commute... */
3062 /* Replace the indexkey expression with an index Var. */
3063 linitial(saop->args) = fix_indexqual_operand(linitial(saop->args),
3067 else if (IsA(clause, NullTest))
3069 NullTest *nt = (NullTest *) clause;
3071 /* Replace the indexkey expression with an index Var. */
3072 nt->arg = (Expr *) fix_indexqual_operand((Node *) nt->arg,
3077 elog(ERROR, "unsupported indexqual type: %d",
3078 (int) nodeTag(clause));
3080 fixed_indexquals = lappend(fixed_indexquals, clause);
3083 return fixed_indexquals;
3087 * fix_indexorderby_references
3088 * Adjust indexorderby clauses to the form the executor's index
3091 * This is a simplified version of fix_indexqual_references. The input does
3092 * not have RestrictInfo nodes, and we assume that indxpath.c already
3093 * commuted the clauses to put the index keys on the left. Also, we don't
3094 * bother to support any cases except simple OpExprs, since nothing else
3095 * is allowed for ordering operators.
3098 fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path)
3100 IndexOptInfo *index = index_path->indexinfo;
3101 List *fixed_indexorderbys;
3105 fixed_indexorderbys = NIL;
3107 forboth(lcc, index_path->indexorderbys, lci, index_path->indexorderbycols)
3109 Node *clause = (Node *) lfirst(lcc);
3110 int indexcol = lfirst_int(lci);
3113 * Replace any outer-relation variables with nestloop params.
3115 * This also makes a copy of the clause, so it's safe to modify it
3118 clause = replace_nestloop_params(root, clause);
3120 if (IsA(clause, OpExpr))
3122 OpExpr *op = (OpExpr *) clause;
3124 if (list_length(op->args) != 2)
3125 elog(ERROR, "indexorderby clause is not binary opclause");
3128 * Now replace the indexkey expression with an index Var.
3130 linitial(op->args) = fix_indexqual_operand(linitial(op->args),
3135 elog(ERROR, "unsupported indexorderby type: %d",
3136 (int) nodeTag(clause));
3138 fixed_indexorderbys = lappend(fixed_indexorderbys, clause);
3141 return fixed_indexorderbys;
3145 * fix_indexqual_operand
3146 * Convert an indexqual expression to a Var referencing the index column.
3148 * We represent index keys by Var nodes having varno == INDEX_VAR and varattno
3149 * equal to the index's attribute number (index column position).
3151 * Most of the code here is just for sanity cross-checking that the given
3152 * expression actually matches the index column it's claimed to.
3155 fix_indexqual_operand(Node *node, IndexOptInfo *index, int indexcol)
3159 ListCell *indexpr_item;
3162 * Remove any binary-compatible relabeling of the indexkey
3164 if (IsA(node, RelabelType))
3165 node = (Node *) ((RelabelType *) node)->arg;
3167 Assert(indexcol >= 0 && indexcol < index->ncolumns);
3169 if (index->indexkeys[indexcol] != 0)
3171 /* It's a simple index column */
3172 if (IsA(node, Var) &&
3173 ((Var *) node)->varno == index->rel->relid &&
3174 ((Var *) node)->varattno == index->indexkeys[indexcol])
3176 result = (Var *) copyObject(node);
3177 result->varno = INDEX_VAR;
3178 result->varattno = indexcol + 1;
3179 return (Node *) result;
3182 elog(ERROR, "index key does not match expected index column");
3185 /* It's an index expression, so find and cross-check the expression */
3186 indexpr_item = list_head(index->indexprs);
3187 for (pos = 0; pos < index->ncolumns; pos++)
3189 if (index->indexkeys[pos] == 0)
3191 if (indexpr_item == NULL)
3192 elog(ERROR, "too few entries in indexprs list");
3193 if (pos == indexcol)
3197 indexkey = (Node *) lfirst(indexpr_item);
3198 if (indexkey && IsA(indexkey, RelabelType))
3199 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
3200 if (equal(node, indexkey))
3202 result = makeVar(INDEX_VAR, indexcol + 1,
3203 exprType(lfirst(indexpr_item)), -1,
3204 exprCollation(lfirst(indexpr_item)),
3206 return (Node *) result;
3209 elog(ERROR, "index key does not match expected index column");
3211 indexpr_item = lnext(indexpr_item);
3216 elog(ERROR, "index key does not match expected index column");
3217 return NULL; /* keep compiler quiet */
3221 * get_switched_clauses
3222 * Given a list of merge or hash joinclauses (as RestrictInfo nodes),
3223 * extract the bare clauses, and rearrange the elements within the
3224 * clauses, if needed, so the outer join variable is on the left and
3225 * the inner is on the right. The original clause data structure is not
3226 * touched; a modified list is returned. We do, however, set the transient
3227 * outer_is_left field in each RestrictInfo to show which side was which.
3230 get_switched_clauses(List *clauses, Relids outerrelids)
3237 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
3238 OpExpr *clause = (OpExpr *) restrictinfo->clause;
3240 Assert(is_opclause(clause));
3241 if (bms_is_subset(restrictinfo->right_relids, outerrelids))
3244 * Duplicate just enough of the structure to allow commuting the
3245 * clause without changing the original list. Could use
3246 * copyObject, but a complete deep copy is overkill.
3248 OpExpr *temp = makeNode(OpExpr);
3250 temp->opno = clause->opno;
3251 temp->opfuncid = InvalidOid;
3252 temp->opresulttype = clause->opresulttype;
3253 temp->opretset = clause->opretset;
3254 temp->opcollid = clause->opcollid;
3255 temp->inputcollid = clause->inputcollid;
3256 temp->args = list_copy(clause->args);
3257 temp->location = clause->location;
3258 /* Commute it --- note this modifies the temp node in-place. */
3259 CommuteOpExpr(temp);
3260 t_list = lappend(t_list, temp);
3261 restrictinfo->outer_is_left = false;
3265 Assert(bms_is_subset(restrictinfo->left_relids, outerrelids));
3266 t_list = lappend(t_list, clause);
3267 restrictinfo->outer_is_left = true;
3274 * order_qual_clauses
3275 * Given a list of qual clauses that will all be evaluated at the same
3276 * plan node, sort the list into the order we want to check the quals
3279 * Ideally the order should be driven by a combination of execution cost and
3280 * selectivity, but it's not immediately clear how to account for both,
3281 * and given the uncertainty of the estimates the reliability of the decisions
3282 * would be doubtful anyway. So we just order by estimated per-tuple cost,
3283 * being careful not to change the order when (as is often the case) the
3284 * estimates are identical.
3286 * Although this will work on either bare clauses or RestrictInfos, it's
3287 * much faster to apply it to RestrictInfos, since it can re-use cost
3288 * information that is cached in RestrictInfos.
3290 * Note: some callers pass lists that contain entries that will later be
3291 * removed; this is the easiest way to let this routine see RestrictInfos
3292 * instead of bare clauses. It's OK because we only sort by cost, but
3293 * a cost/selectivity combination would likely do the wrong thing.
3296 order_qual_clauses(PlannerInfo *root, List *clauses)
3303 int nitems = list_length(clauses);
3309 /* No need to work hard for 0 or 1 clause */
3314 * Collect the items and costs into an array. This is to avoid repeated
3315 * cost_qual_eval work if the inputs aren't RestrictInfos.
3317 items = (QualItem *) palloc(nitems * sizeof(QualItem));
3319 foreach(lc, clauses)
3321 Node *clause = (Node *) lfirst(lc);
3324 cost_qual_eval_node(&qcost, clause, root);
3325 items[i].clause = clause;
3326 items[i].cost = qcost.per_tuple;
3331 * Sort. We don't use qsort() because it's not guaranteed stable for
3332 * equal keys. The expected number of entries is small enough that a
3333 * simple insertion sort should be good enough.
3335 for (i = 1; i < nitems; i++)
3337 QualItem newitem = items[i];
3340 /* insert newitem into the already-sorted subarray */
3341 for (j = i; j > 0; j--)
3343 if (newitem.cost >= items[j - 1].cost)
3345 items[j] = items[j - 1];
3350 /* Convert back to a list */
3352 for (i = 0; i < nitems; i++)
3353 result = lappend(result, items[i].clause);
3359 * Copy cost and size info from a Path node to the Plan node created from it.
3360 * The executor usually won't use this info, but it's needed by EXPLAIN.
3363 copy_path_costsize(Plan *dest, Path *src)
3367 dest->startup_cost = src->startup_cost;
3368 dest->total_cost = src->total_cost;
3369 dest->plan_rows = src->rows;
3370 dest->plan_width = src->parent->width;
3374 dest->startup_cost = 0;
3375 dest->total_cost = 0;
3376 dest->plan_rows = 0;
3377 dest->plan_width = 0;
3382 * Copy cost and size info from a lower plan node to an inserted node.
3383 * (Most callers alter the info after copying it.)
3386 copy_plan_costsize(Plan *dest, Plan *src)
3390 dest->startup_cost = src->startup_cost;
3391 dest->total_cost = src->total_cost;
3392 dest->plan_rows = src->plan_rows;
3393 dest->plan_width = src->plan_width;
3397 dest->startup_cost = 0;
3398 dest->total_cost = 0;
3399 dest->plan_rows = 0;
3400 dest->plan_width = 0;
3405 /*****************************************************************************
3407 * PLAN NODE BUILDING ROUTINES
3409 * Some of these are exported because they are called to build plan nodes
3410 * in contexts where we're not deriving the plan node from a path node.
3412 *****************************************************************************/
3415 make_seqscan(List *qptlist,
3419 SeqScan *node = makeNode(SeqScan);
3420 Plan *plan = &node->plan;
3422 /* cost should be inserted by caller */
3423 plan->targetlist = qptlist;
3424 plan->qual = qpqual;
3425 plan->lefttree = NULL;
3426 plan->righttree = NULL;
3427 node->scanrelid = scanrelid;
3433 make_samplescan(List *qptlist,
3437 SampleScan *node = makeNode(SampleScan);
3438 Plan *plan = &node->plan;
3440 /* cost should be inserted by caller */
3441 plan->targetlist = qptlist;
3442 plan->qual = qpqual;
3443 plan->lefttree = NULL;
3444 plan->righttree = NULL;
3445 node->scanrelid = scanrelid;
3451 make_indexscan(List *qptlist,
3456 List *indexqualorig,
3458 List *indexorderbyorig,
3459 Oid *indexorderbyops,
3460 ScanDirection indexscandir)
3462 IndexScan *node = makeNode(IndexScan);
3463 Plan *plan = &node->scan.plan;
3465 /* cost should be inserted by caller */
3466 plan->targetlist = qptlist;
3467 plan->qual = qpqual;
3468 plan->lefttree = NULL;
3469 plan->righttree = NULL;
3470 node->scan.scanrelid = scanrelid;
3471 node->indexid = indexid;
3472 node->indexqual = indexqual;
3473 node->indexqualorig = indexqualorig;
3474 node->indexorderby = indexorderby;
3475 node->indexorderbyorig = indexorderbyorig;
3476 node->indexorderbyops = indexorderbyops;
3477 node->indexorderdir = indexscandir;
3482 static IndexOnlyScan *
3483 make_indexonlyscan(List *qptlist,
3490 ScanDirection indexscandir)
3492 IndexOnlyScan *node = makeNode(IndexOnlyScan);
3493 Plan *plan = &node->scan.plan;
3495 /* cost should be inserted by caller */
3496 plan->targetlist = qptlist;
3497 plan->qual = qpqual;
3498 plan->lefttree = NULL;
3499 plan->righttree = NULL;
3500 node->scan.scanrelid = scanrelid;
3501 node->indexid = indexid;
3502 node->indexqual = indexqual;
3503 node->indexorderby = indexorderby;
3504 node->indextlist = indextlist;
3505 node->indexorderdir = indexscandir;
3510 static BitmapIndexScan *
3511 make_bitmap_indexscan(Index scanrelid,
3514 List *indexqualorig)
3516 BitmapIndexScan *node = makeNode(BitmapIndexScan);
3517 Plan *plan = &node->scan.plan;
3519 /* cost should be inserted by caller */
3520 plan->targetlist = NIL; /* not used */
3521 plan->qual = NIL; /* not used */
3522 plan->lefttree = NULL;
3523 plan->righttree = NULL;
3524 node->scan.scanrelid = scanrelid;
3525 node->indexid = indexid;
3526 node->indexqual = indexqual;
3527 node->indexqualorig = indexqualorig;
3532 static BitmapHeapScan *
3533 make_bitmap_heapscan(List *qptlist,
3536 List *bitmapqualorig,
3539 BitmapHeapScan *node = makeNode(BitmapHeapScan);
3540 Plan *plan = &node->scan.plan;
3542 /* cost should be inserted by caller */
3543 plan->targetlist = qptlist;
3544 plan->qual = qpqual;
3545 plan->lefttree = lefttree;
3546 plan->righttree = NULL;
3547 node->scan.scanrelid = scanrelid;
3548 node->bitmapqualorig = bitmapqualorig;
3554 make_tidscan(List *qptlist,
3559 TidScan *node = makeNode(TidScan);
3560 Plan *plan = &node->scan.plan;
3562 /* cost should be inserted by caller */
3563 plan->targetlist = qptlist;
3564 plan->qual = qpqual;
3565 plan->lefttree = NULL;
3566 plan->righttree = NULL;
3567 node->scan.scanrelid = scanrelid;
3568 node->tidquals = tidquals;
3574 make_subqueryscan(List *qptlist,
3579 SubqueryScan *node = makeNode(SubqueryScan);
3580 Plan *plan = &node->scan.plan;
3583 * Cost is figured here for the convenience of prepunion.c. Note this is
3584 * only correct for the case where qpqual is empty; otherwise caller
3585 * should overwrite cost with a better estimate.
3587 copy_plan_costsize(plan, subplan);
3588 plan->total_cost += cpu_tuple_cost * subplan->plan_rows;
3590 plan->targetlist = qptlist;
3591 plan->qual = qpqual;
3592 plan->lefttree = NULL;
3593 plan->righttree = NULL;
3594 node->scan.scanrelid = scanrelid;
3595 node->subplan = subplan;
3600 static FunctionScan *
3601 make_functionscan(List *qptlist,
3605 bool funcordinality)
3607 FunctionScan *node = makeNode(FunctionScan);
3608 Plan *plan = &node->scan.plan;
3610 /* cost should be inserted by caller */
3611 plan->targetlist = qptlist;
3612 plan->qual = qpqual;
3613 plan->lefttree = NULL;
3614 plan->righttree = NULL;
3615 node->scan.scanrelid = scanrelid;
3616 node->functions = functions;
3617 node->funcordinality = funcordinality;
3623 make_valuesscan(List *qptlist,
3628 ValuesScan *node = makeNode(ValuesScan);
3629 Plan *plan = &node->scan.plan;
3631 /* cost should be inserted by caller */
3632 plan->targetlist = qptlist;
3633 plan->qual = qpqual;
3634 plan->lefttree = NULL;
3635 plan->righttree = NULL;
3636 node->scan.scanrelid = scanrelid;
3637 node->values_lists = values_lists;
3643 make_ctescan(List *qptlist,
3649 CteScan *node = makeNode(CteScan);
3650 Plan *plan = &node->scan.plan;
3652 /* cost should be inserted by caller */
3653 plan->targetlist = qptlist;
3654 plan->qual = qpqual;
3655 plan->lefttree = NULL;
3656 plan->righttree = NULL;
3657 node->scan.scanrelid = scanrelid;
3658 node->ctePlanId = ctePlanId;
3659 node->cteParam = cteParam;
3664 static WorkTableScan *
3665 make_worktablescan(List *qptlist,
3670 WorkTableScan *node = makeNode(WorkTableScan);
3671 Plan *plan = &node->scan.plan;
3673 /* cost should be inserted by caller */
3674 plan->targetlist = qptlist;
3675 plan->qual = qpqual;
3676 plan->lefttree = NULL;
3677 plan->righttree = NULL;
3678 node->scan.scanrelid = scanrelid;
3679 node->wtParam = wtParam;
3685 make_foreignscan(List *qptlist,
3690 List *fdw_scan_tlist)
3692 ForeignScan *node = makeNode(ForeignScan);
3693 Plan *plan = &node->scan.plan;
3695 /* cost will be filled in by create_foreignscan_plan */
3696 plan->targetlist = qptlist;
3697 plan->qual = qpqual;
3698 plan->lefttree = NULL;
3699 plan->righttree = NULL;
3700 node->scan.scanrelid = scanrelid;
3701 /* fs_server will be filled in by create_foreignscan_plan */
3702 node->fs_server = InvalidOid;
3703 node->fdw_exprs = fdw_exprs;
3704 node->fdw_private = fdw_private;
3705 node->fdw_scan_tlist = fdw_scan_tlist;
3706 /* fs_relids will be filled in by create_foreignscan_plan */
3707 node->fs_relids = NULL;
3708 /* fsSystemCol will be filled in by create_foreignscan_plan */
3709 node->fsSystemCol = false;
3715 make_append(List *appendplans, List *tlist)
3717 Append *node = makeNode(Append);
3718 Plan *plan = &node->plan;
3723 * Compute cost as sum of subplan costs. We charge nothing extra for the
3724 * Append itself, which perhaps is too optimistic, but since it doesn't do
3725 * any selection or projection, it is a pretty cheap node.
3727 * If you change this, see also create_append_path(). Also, the size
3728 * calculations should match set_append_rel_pathlist(). It'd be better
3729 * not to duplicate all this logic, but some callers of this function
3730 * aren't working from an appendrel or AppendPath, so there's noplace to
3731 * copy the data from.
3733 plan->startup_cost = 0;
3734 plan->total_cost = 0;
3735 plan->plan_rows = 0;
3737 foreach(subnode, appendplans)
3739 Plan *subplan = (Plan *) lfirst(subnode);
3741 if (subnode == list_head(appendplans)) /* first node? */
3742 plan->startup_cost = subplan->startup_cost;
3743 plan->total_cost += subplan->total_cost;
3744 plan->plan_rows += subplan->plan_rows;
3745 total_size += subplan->plan_width * subplan->plan_rows;
3747 if (plan->plan_rows > 0)
3748 plan->plan_width = rint(total_size / plan->plan_rows);
3750 plan->plan_width = 0;
3752 plan->targetlist = tlist;
3754 plan->lefttree = NULL;
3755 plan->righttree = NULL;
3756 node->appendplans = appendplans;
3762 make_recursive_union(List *tlist,
3769 RecursiveUnion *node = makeNode(RecursiveUnion);
3770 Plan *plan = &node->plan;
3771 int numCols = list_length(distinctList);
3773 cost_recursive_union(plan, lefttree, righttree);
3775 plan->targetlist = tlist;
3777 plan->lefttree = lefttree;
3778 plan->righttree = righttree;
3779 node->wtParam = wtParam;
3782 * convert SortGroupClause list into arrays of attr indexes and equality
3783 * operators, as wanted by executor
3785 node->numCols = numCols;
3789 AttrNumber *dupColIdx;
3793 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
3794 dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
3796 foreach(slitem, distinctList)
3798 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
3799 TargetEntry *tle = get_sortgroupclause_tle(sortcl,
3802 dupColIdx[keyno] = tle->resno;
3803 dupOperators[keyno] = sortcl->eqop;
3804 Assert(OidIsValid(dupOperators[keyno]));
3807 node->dupColIdx = dupColIdx;
3808 node->dupOperators = dupOperators;
3810 node->numGroups = numGroups;
3816 make_bitmap_and(List *bitmapplans)
3818 BitmapAnd *node = makeNode(BitmapAnd);
3819 Plan *plan = &node->plan;
3821 /* cost should be inserted by caller */
3822 plan->targetlist = NIL;
3824 plan->lefttree = NULL;
3825 plan->righttree = NULL;
3826 node->bitmapplans = bitmapplans;
3832 make_bitmap_or(List *bitmapplans)
3834 BitmapOr *node = makeNode(BitmapOr);
3835 Plan *plan = &node->plan;
3837 /* cost should be inserted by caller */
3838 plan->targetlist = NIL;
3840 plan->lefttree = NULL;
3841 plan->righttree = NULL;
3842 node->bitmapplans = bitmapplans;
3848 make_nestloop(List *tlist,
3856 NestLoop *node = makeNode(NestLoop);
3857 Plan *plan = &node->join.plan;
3859 /* cost should be inserted by caller */
3860 plan->targetlist = tlist;
3861 plan->qual = otherclauses;
3862 plan->lefttree = lefttree;
3863 plan->righttree = righttree;
3864 node->join.jointype = jointype;
3865 node->join.joinqual = joinclauses;
3866 node->nestParams = nestParams;
3872 make_hashjoin(List *tlist,
3880 HashJoin *node = makeNode(HashJoin);
3881 Plan *plan = &node->join.plan;
3883 /* cost should be inserted by caller */
3884 plan->targetlist = tlist;
3885 plan->qual = otherclauses;
3886 plan->lefttree = lefttree;
3887 plan->righttree = righttree;
3888 node->hashclauses = hashclauses;
3889 node->join.jointype = jointype;
3890 node->join.joinqual = joinclauses;
3896 make_hash(Plan *lefttree,
3898 AttrNumber skewColumn,
3901 int32 skewColTypmod)
3903 Hash *node = makeNode(Hash);
3904 Plan *plan = &node->plan;
3906 copy_plan_costsize(plan, lefttree);
3909 * For plausibility, make startup & total costs equal total cost of input
3910 * plan; this only affects EXPLAIN display not decisions.
3912 plan->startup_cost = plan->total_cost;
3913 plan->targetlist = lefttree->targetlist;
3915 plan->lefttree = lefttree;
3916 plan->righttree = NULL;
3918 node->skewTable = skewTable;
3919 node->skewColumn = skewColumn;
3920 node->skewInherit = skewInherit;
3921 node->skewColType = skewColType;
3922 node->skewColTypmod = skewColTypmod;
3928 make_mergejoin(List *tlist,
3933 Oid *mergecollations,
3934 int *mergestrategies,
3935 bool *mergenullsfirst,
3940 MergeJoin *node = makeNode(MergeJoin);
3941 Plan *plan = &node->join.plan;
3943 /* cost should be inserted by caller */
3944 plan->targetlist = tlist;
3945 plan->qual = otherclauses;
3946 plan->lefttree = lefttree;
3947 plan->righttree = righttree;
3948 node->mergeclauses = mergeclauses;
3949 node->mergeFamilies = mergefamilies;
3950 node->mergeCollations = mergecollations;
3951 node->mergeStrategies = mergestrategies;
3952 node->mergeNullsFirst = mergenullsfirst;
3953 node->join.jointype = jointype;
3954 node->join.joinqual = joinclauses;
3960 * make_sort --- basic routine to build a Sort plan node
3962 * Caller must have built the sortColIdx, sortOperators, collations, and
3963 * nullsFirst arrays already.
3964 * limit_tuples is as for cost_sort (in particular, pass -1 if no limit)
3967 make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
3968 AttrNumber *sortColIdx, Oid *sortOperators,
3969 Oid *collations, bool *nullsFirst,
3970 double limit_tuples)
3972 Sort *node = makeNode(Sort);
3973 Plan *plan = &node->plan;
3974 Path sort_path; /* dummy for result of cost_sort */
3976 copy_plan_costsize(plan, lefttree); /* only care about copying size */
3977 cost_sort(&sort_path, root, NIL,
3978 lefttree->total_cost,
3979 lefttree->plan_rows,
3980 lefttree->plan_width,
3984 plan->startup_cost = sort_path.startup_cost;
3985 plan->total_cost = sort_path.total_cost;
3986 plan->targetlist = lefttree->targetlist;
3988 plan->lefttree = lefttree;
3989 plan->righttree = NULL;
3990 node->numCols = numCols;
3991 node->sortColIdx = sortColIdx;
3992 node->sortOperators = sortOperators;
3993 node->collations = collations;
3994 node->nullsFirst = nullsFirst;
4000 * prepare_sort_from_pathkeys
4001 * Prepare to sort according to given pathkeys
4003 * This is used to set up for both Sort and MergeAppend nodes. It calculates
4004 * the executor's representation of the sort key information, and adjusts the
4005 * plan targetlist if needed to add resjunk sort columns.
4008 * 'lefttree' is the plan node which yields input tuples
4009 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
4010 * 'relids' identifies the child relation being sorted, if any
4011 * 'reqColIdx' is NULL or an array of required sort key column numbers
4012 * 'adjust_tlist_in_place' is TRUE if lefttree must be modified in-place
4014 * We must convert the pathkey information into arrays of sort key column
4015 * numbers, sort operator OIDs, collation OIDs, and nulls-first flags,
4016 * which is the representation the executor wants. These are returned into
4017 * the output parameters *p_numsortkeys etc.
4019 * When looking for matches to an EquivalenceClass's members, we will only
4020 * consider child EC members if they match 'relids'. This protects against
4021 * possible incorrect matches to child expressions that contain no Vars.
4023 * If reqColIdx isn't NULL then it contains sort key column numbers that
4024 * we should match. This is used when making child plans for a MergeAppend;
4025 * it's an error if we can't match the columns.
4027 * If the pathkeys include expressions that aren't simple Vars, we will
4028 * usually need to add resjunk items to the input plan's targetlist to
4029 * compute these expressions, since the Sort/MergeAppend node itself won't
4030 * do any such calculations. If the input plan type isn't one that can do
4031 * projections, this means adding a Result node just to do the projection.
4032 * However, the caller can pass adjust_tlist_in_place = TRUE to force the
4033 * lefttree tlist to be modified in-place regardless of whether the node type
4034 * can project --- we use this for fixing the tlist of MergeAppend itself.
4036 * Returns the node which is to be the input to the Sort (either lefttree,
4037 * or a Result stacked atop lefttree).
4040 prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
4042 const AttrNumber *reqColIdx,
4043 bool adjust_tlist_in_place,
4045 AttrNumber **p_sortColIdx,
4046 Oid **p_sortOperators,
4048 bool **p_nullsFirst)
4050 List *tlist = lefttree->targetlist;
4053 AttrNumber *sortColIdx;
4059 * We will need at most list_length(pathkeys) sort columns; possibly less
4061 numsortkeys = list_length(pathkeys);
4062 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
4063 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
4064 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
4065 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
4069 foreach(i, pathkeys)
4071 PathKey *pathkey = (PathKey *) lfirst(i);
4072 EquivalenceClass *ec = pathkey->pk_eclass;
4073 EquivalenceMember *em;
4074 TargetEntry *tle = NULL;
4075 Oid pk_datatype = InvalidOid;
4079 if (ec->ec_has_volatile)
4082 * If the pathkey's EquivalenceClass is volatile, then it must
4083 * have come from an ORDER BY clause, and we have to match it to
4084 * that same targetlist entry.
4086 if (ec->ec_sortref == 0) /* can't happen */
4087 elog(ERROR, "volatile EquivalenceClass has no sortref");
4088 tle = get_sortgroupref_tle(ec->ec_sortref, tlist);
4090 Assert(list_length(ec->ec_members) == 1);
4091 pk_datatype = ((EquivalenceMember *) linitial(ec->ec_members))->em_datatype;
4093 else if (reqColIdx != NULL)
4096 * If we are given a sort column number to match, only consider
4097 * the single TLE at that position. It's possible that there is
4098 * no such TLE, in which case fall through and generate a resjunk
4099 * targetentry (we assume this must have happened in the parent
4100 * plan as well). If there is a TLE but it doesn't match the
4101 * pathkey's EC, we do the same, which is probably the wrong thing
4102 * but we'll leave it to caller to complain about the mismatch.
4104 tle = get_tle_by_resno(tlist, reqColIdx[numsortkeys]);
4107 em = find_ec_member_for_expr(ec, tle->expr, relids);
4110 /* found expr at right place in tlist */
4111 pk_datatype = em->em_datatype;
4120 * Otherwise, we can sort by any non-constant expression listed in
4121 * the pathkey's EquivalenceClass. For now, we take the first
4122 * tlist item found in the EC. If there's no match, we'll generate
4123 * a resjunk entry using the first EC member that is an expression
4124 * in the input's vars. (The non-const restriction only matters
4125 * if the EC is below_outer_join; but if it isn't, it won't
4126 * contain consts anyway, else we'd have discarded the pathkey as
4129 * XXX if we have a choice, is there any way of figuring out which
4130 * might be cheapest to execute? (For example, int4lt is likely
4131 * much cheaper to execute than numericlt, but both might appear
4132 * in the same equivalence class...) Not clear that we ever will
4133 * have an interesting choice in practice, so it may not matter.
4137 tle = (TargetEntry *) lfirst(j);
4138 em = find_ec_member_for_expr(ec, tle->expr, relids);
4141 /* found expr already in tlist */
4142 pk_datatype = em->em_datatype;
4152 * No matching tlist item; look for a computable expression. Note
4153 * that we treat Aggrefs as if they were variables; this is
4154 * necessary when attempting to sort the output from an Agg node
4155 * for use in a WindowFunc (since grouping_planner will have
4156 * treated the Aggrefs as variables, too).
4158 Expr *sortexpr = NULL;
4160 foreach(j, ec->ec_members)
4162 EquivalenceMember *em = (EquivalenceMember *) lfirst(j);
4167 * We shouldn't be trying to sort by an equivalence class that
4168 * contains a constant, so no need to consider such cases any
4171 if (em->em_is_const)
4175 * Ignore child members unless they match the rel being
4178 if (em->em_is_child &&
4179 !bms_equal(em->em_relids, relids))
4182 sortexpr = em->em_expr;
4183 exprvars = pull_var_clause((Node *) sortexpr,
4184 PVC_INCLUDE_AGGREGATES,
4185 PVC_INCLUDE_PLACEHOLDERS);
4186 foreach(k, exprvars)
4188 if (!tlist_member_ignore_relabel(lfirst(k), tlist))
4191 list_free(exprvars);
4194 pk_datatype = em->em_datatype;
4195 break; /* found usable expression */
4199 elog(ERROR, "could not find pathkey item to sort");
4202 * Do we need to insert a Result node?
4204 if (!adjust_tlist_in_place &&
4205 !is_projection_capable_plan(lefttree))
4207 /* copy needed so we don't modify input's tlist below */
4208 tlist = copyObject(tlist);
4209 lefttree = (Plan *) make_result(root, tlist, NULL,
4213 /* Don't bother testing is_projection_capable_plan again */
4214 adjust_tlist_in_place = true;
4217 * Add resjunk entry to input's tlist
4219 tle = makeTargetEntry(sortexpr,
4220 list_length(tlist) + 1,
4223 tlist = lappend(tlist, tle);
4224 lefttree->targetlist = tlist; /* just in case NIL before */
4228 * Look up the correct sort operator from the PathKey's slightly
4229 * abstracted representation.
4231 sortop = get_opfamily_member(pathkey->pk_opfamily,
4234 pathkey->pk_strategy);
4235 if (!OidIsValid(sortop)) /* should not happen */
4236 elog(ERROR, "could not find member %d(%u,%u) of opfamily %u",
4237 pathkey->pk_strategy, pk_datatype, pk_datatype,
4238 pathkey->pk_opfamily);
4240 /* Add the column to the sort arrays */
4241 sortColIdx[numsortkeys] = tle->resno;
4242 sortOperators[numsortkeys] = sortop;
4243 collations[numsortkeys] = ec->ec_collation;
4244 nullsFirst[numsortkeys] = pathkey->pk_nulls_first;
4248 /* Return results */
4249 *p_numsortkeys = numsortkeys;
4250 *p_sortColIdx = sortColIdx;
4251 *p_sortOperators = sortOperators;
4252 *p_collations = collations;
4253 *p_nullsFirst = nullsFirst;
4259 * find_ec_member_for_expr
4260 * Locate an EquivalenceClass member matching the given expression, if any
4262 * Child EC members are ignored unless they match 'relids'.
4264 static EquivalenceMember *
4265 find_ec_member_for_expr(EquivalenceClass *ec,
4271 /* We ignore binary-compatible relabeling on both ends */
4272 while (expr && IsA(expr, RelabelType))
4273 expr = ((RelabelType *) expr)->arg;
4275 foreach(lc, ec->ec_members)
4277 EquivalenceMember *em = (EquivalenceMember *) lfirst(lc);
4281 * We shouldn't be trying to sort by an equivalence class that
4282 * contains a constant, so no need to consider such cases any further.
4284 if (em->em_is_const)
4288 * Ignore child members unless they match the rel being sorted.
4290 if (em->em_is_child &&
4291 !bms_equal(em->em_relids, relids))
4294 /* Match if same expression (after stripping relabel) */
4295 emexpr = em->em_expr;
4296 while (emexpr && IsA(emexpr, RelabelType))
4297 emexpr = ((RelabelType *) emexpr)->arg;
4299 if (equal(emexpr, expr))
4307 * make_sort_from_pathkeys
4308 * Create sort plan to sort according to given pathkeys
4310 * 'lefttree' is the node which yields input tuples
4311 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
4312 * 'limit_tuples' is the bound on the number of output tuples;
4316 make_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
4317 double limit_tuples)
4320 AttrNumber *sortColIdx;
4325 /* Compute sort column info, and adjust lefttree as needed */
4326 lefttree = prepare_sort_from_pathkeys(root, lefttree, pathkeys,
4336 /* Now build the Sort node */
4337 return make_sort(root, lefttree, numsortkeys,
4338 sortColIdx, sortOperators, collations,
4339 nullsFirst, limit_tuples);
4343 * make_sort_from_sortclauses
4344 * Create sort plan to sort according to given sortclauses
4346 * 'sortcls' is a list of SortGroupClauses
4347 * 'lefttree' is the node which yields input tuples
4350 make_sort_from_sortclauses(PlannerInfo *root, List *sortcls, Plan *lefttree)
4352 List *sub_tlist = lefttree->targetlist;
4355 AttrNumber *sortColIdx;
4360 /* Convert list-ish representation to arrays wanted by executor */
4361 numsortkeys = list_length(sortcls);
4362 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
4363 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
4364 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
4365 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
4370 SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
4371 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
4373 sortColIdx[numsortkeys] = tle->resno;
4374 sortOperators[numsortkeys] = sortcl->sortop;
4375 collations[numsortkeys] = exprCollation((Node *) tle->expr);
4376 nullsFirst[numsortkeys] = sortcl->nulls_first;
4380 return make_sort(root, lefttree, numsortkeys,
4381 sortColIdx, sortOperators, collations,
4386 * make_sort_from_groupcols
4387 * Create sort plan to sort based on grouping columns
4389 * 'groupcls' is the list of SortGroupClauses
4390 * 'grpColIdx' gives the column numbers to use
4392 * This might look like it could be merged with make_sort_from_sortclauses,
4393 * but presently we *must* use the grpColIdx[] array to locate sort columns,
4394 * because the child plan's tlist is not marked with ressortgroupref info
4395 * appropriate to the grouping node. So, only the sort ordering info
4396 * is used from the SortGroupClause entries.
4399 make_sort_from_groupcols(PlannerInfo *root,
4401 AttrNumber *grpColIdx,
4404 List *sub_tlist = lefttree->targetlist;
4407 AttrNumber *sortColIdx;
4412 /* Convert list-ish representation to arrays wanted by executor */
4413 numsortkeys = list_length(groupcls);
4414 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
4415 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
4416 collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
4417 nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
4420 foreach(l, groupcls)
4422 SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
4423 TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[numsortkeys]);
4426 elog(ERROR, "could not retrive tle for sort-from-groupcols");
4428 sortColIdx[numsortkeys] = tle->resno;
4429 sortOperators[numsortkeys] = grpcl->sortop;
4430 collations[numsortkeys] = exprCollation((Node *) tle->expr);
4431 nullsFirst[numsortkeys] = grpcl->nulls_first;
4435 return make_sort(root, lefttree, numsortkeys,
4436 sortColIdx, sortOperators, collations,
4441 make_material(Plan *lefttree)
4443 Material *node = makeNode(Material);
4444 Plan *plan = &node->plan;
4446 /* cost should be inserted by caller */
4447 plan->targetlist = lefttree->targetlist;
4449 plan->lefttree = lefttree;
4450 plan->righttree = NULL;
4456 * materialize_finished_plan: stick a Material node atop a completed plan
4458 * There are a couple of places where we want to attach a Material node
4459 * after completion of subquery_planner(). This currently requires hackery.
4460 * Since subquery_planner has already run SS_finalize_plan on the subplan
4461 * tree, we have to kluge up parameter lists for the Material node.
4462 * Possibly this could be fixed by postponing SS_finalize_plan processing
4463 * until setrefs.c is run?
4466 materialize_finished_plan(Plan *subplan)
4469 Path matpath; /* dummy for result of cost_material */
4471 matplan = (Plan *) make_material(subplan);
4474 cost_material(&matpath,
4475 subplan->startup_cost,
4476 subplan->total_cost,
4478 subplan->plan_width);
4479 matplan->startup_cost = matpath.startup_cost;
4480 matplan->total_cost = matpath.total_cost;
4481 matplan->plan_rows = subplan->plan_rows;
4482 matplan->plan_width = subplan->plan_width;
4484 /* parameter kluge --- see comments above */
4485 matplan->extParam = bms_copy(subplan->extParam);
4486 matplan->allParam = bms_copy(subplan->allParam);
4492 make_agg(PlannerInfo *root, List *tlist, List *qual,
4493 AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
4494 int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators,
4498 Agg *node = makeNode(Agg);
4499 Plan *plan = &node->plan;
4500 Path agg_path; /* dummy for result of cost_agg */
4503 node->aggstrategy = aggstrategy;
4504 node->numCols = numGroupCols;
4505 node->grpColIdx = grpColIdx;
4506 node->grpOperators = grpOperators;
4507 node->numGroups = numGroups;
4509 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4510 cost_agg(&agg_path, root,
4511 aggstrategy, aggcosts,
4512 numGroupCols, numGroups,
4513 lefttree->startup_cost,
4514 lefttree->total_cost,
4515 lefttree->plan_rows);
4516 plan->startup_cost = agg_path.startup_cost;
4517 plan->total_cost = agg_path.total_cost;
4520 * We will produce a single output tuple if not grouping, and a tuple per
4523 if (aggstrategy == AGG_PLAIN)
4524 plan->plan_rows = 1;
4526 plan->plan_rows = numGroups;
4529 * We also need to account for the cost of evaluation of the qual (ie, the
4530 * HAVING clause) and the tlist. Note that cost_qual_eval doesn't charge
4531 * anything for Aggref nodes; this is okay since they are really
4532 * comparable to Vars.
4534 * See notes in add_tlist_costs_to_plan about why only make_agg,
4535 * make_windowagg and make_group worry about tlist eval cost.
4539 cost_qual_eval(&qual_cost, qual, root);
4540 plan->startup_cost += qual_cost.startup;
4541 plan->total_cost += qual_cost.startup;
4542 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
4544 add_tlist_costs_to_plan(root, plan, tlist);
4547 plan->targetlist = tlist;
4548 plan->lefttree = lefttree;
4549 plan->righttree = NULL;
4555 make_windowagg(PlannerInfo *root, List *tlist,
4556 List *windowFuncs, Index winref,
4557 int partNumCols, AttrNumber *partColIdx, Oid *partOperators,
4558 int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators,
4559 int frameOptions, Node *startOffset, Node *endOffset,
4562 WindowAgg *node = makeNode(WindowAgg);
4563 Plan *plan = &node->plan;
4564 Path windowagg_path; /* dummy for result of cost_windowagg */
4566 node->winref = winref;
4567 node->partNumCols = partNumCols;
4568 node->partColIdx = partColIdx;
4569 node->partOperators = partOperators;
4570 node->ordNumCols = ordNumCols;
4571 node->ordColIdx = ordColIdx;
4572 node->ordOperators = ordOperators;
4573 node->frameOptions = frameOptions;
4574 node->startOffset = startOffset;
4575 node->endOffset = endOffset;
4577 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4578 cost_windowagg(&windowagg_path, root,
4579 windowFuncs, partNumCols, ordNumCols,
4580 lefttree->startup_cost,
4581 lefttree->total_cost,
4582 lefttree->plan_rows);
4583 plan->startup_cost = windowagg_path.startup_cost;
4584 plan->total_cost = windowagg_path.total_cost;
4587 * We also need to account for the cost of evaluation of the tlist.
4589 * See notes in add_tlist_costs_to_plan about why only make_agg,
4590 * make_windowagg and make_group worry about tlist eval cost.
4592 add_tlist_costs_to_plan(root, plan, tlist);
4594 plan->targetlist = tlist;
4595 plan->lefttree = lefttree;
4596 plan->righttree = NULL;
4597 /* WindowAgg nodes never have a qual clause */
4604 make_group(PlannerInfo *root,
4608 AttrNumber *grpColIdx,
4613 Group *node = makeNode(Group);
4614 Plan *plan = &node->plan;
4615 Path group_path; /* dummy for result of cost_group */
4618 node->numCols = numGroupCols;
4619 node->grpColIdx = grpColIdx;
4620 node->grpOperators = grpOperators;
4622 copy_plan_costsize(plan, lefttree); /* only care about copying size */
4623 cost_group(&group_path, root,
4624 numGroupCols, numGroups,
4625 lefttree->startup_cost,
4626 lefttree->total_cost,
4627 lefttree->plan_rows);
4628 plan->startup_cost = group_path.startup_cost;
4629 plan->total_cost = group_path.total_cost;
4631 /* One output tuple per estimated result group */
4632 plan->plan_rows = numGroups;
4635 * We also need to account for the cost of evaluation of the qual (ie, the
4636 * HAVING clause) and the tlist.
4638 * XXX this double-counts the cost of evaluation of any expressions used
4639 * for grouping, since in reality those will have been evaluated at a
4640 * lower plan level and will only be copied by the Group node. Worth
4643 * See notes in add_tlist_costs_to_plan about why only make_agg,
4644 * make_windowagg and make_group worry about tlist eval cost.
4648 cost_qual_eval(&qual_cost, qual, root);
4649 plan->startup_cost += qual_cost.startup;
4650 plan->total_cost += qual_cost.startup;
4651 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
4653 add_tlist_costs_to_plan(root, plan, tlist);
4656 plan->targetlist = tlist;
4657 plan->lefttree = lefttree;
4658 plan->righttree = NULL;
4664 * distinctList is a list of SortGroupClauses, identifying the targetlist items
4665 * that should be considered by the Unique filter. The input path must
4666 * already be sorted accordingly.
4669 make_unique(Plan *lefttree, List *distinctList)
4671 Unique *node = makeNode(Unique);
4672 Plan *plan = &node->plan;
4673 int numCols = list_length(distinctList);
4675 AttrNumber *uniqColIdx;
4679 copy_plan_costsize(plan, lefttree);
4682 * Charge one cpu_operator_cost per comparison per input tuple. We assume
4683 * all columns get compared at most of the tuples. (XXX probably this is
4686 plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols;
4689 * plan->plan_rows is left as a copy of the input subplan's plan_rows; ie,
4690 * we assume the filter removes nothing. The caller must alter this if he
4691 * has a better idea.
4694 plan->targetlist = lefttree->targetlist;
4696 plan->lefttree = lefttree;
4697 plan->righttree = NULL;
4700 * convert SortGroupClause list into arrays of attr indexes and equality
4701 * operators, as wanted by executor
4703 Assert(numCols > 0);
4704 uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
4705 uniqOperators = (Oid *) palloc(sizeof(Oid) * numCols);
4707 foreach(slitem, distinctList)
4709 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
4710 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
4712 uniqColIdx[keyno] = tle->resno;
4713 uniqOperators[keyno] = sortcl->eqop;
4714 Assert(OidIsValid(uniqOperators[keyno]));
4718 node->numCols = numCols;
4719 node->uniqColIdx = uniqColIdx;
4720 node->uniqOperators = uniqOperators;
4726 * distinctList is a list of SortGroupClauses, identifying the targetlist
4727 * items that should be considered by the SetOp filter. The input path must
4728 * already be sorted accordingly.
4731 make_setop(SetOpCmd cmd, SetOpStrategy strategy, Plan *lefttree,
4732 List *distinctList, AttrNumber flagColIdx, int firstFlag,
4733 long numGroups, double outputRows)
4735 SetOp *node = makeNode(SetOp);
4736 Plan *plan = &node->plan;
4737 int numCols = list_length(distinctList);
4739 AttrNumber *dupColIdx;
4743 copy_plan_costsize(plan, lefttree);
4744 plan->plan_rows = outputRows;
4747 * Charge one cpu_operator_cost per comparison per input tuple. We assume
4748 * all columns get compared at most of the tuples.
4750 plan->total_cost += cpu_operator_cost * lefttree->plan_rows * numCols;
4752 plan->targetlist = lefttree->targetlist;
4754 plan->lefttree = lefttree;
4755 plan->righttree = NULL;
4758 * convert SortGroupClause list into arrays of attr indexes and equality
4759 * operators, as wanted by executor
4761 Assert(numCols > 0);
4762 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
4763 dupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
4765 foreach(slitem, distinctList)
4767 SortGroupClause *sortcl = (SortGroupClause *) lfirst(slitem);
4768 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
4770 dupColIdx[keyno] = tle->resno;
4771 dupOperators[keyno] = sortcl->eqop;
4772 Assert(OidIsValid(dupOperators[keyno]));
4777 node->strategy = strategy;
4778 node->numCols = numCols;
4779 node->dupColIdx = dupColIdx;
4780 node->dupOperators = dupOperators;
4781 node->flagColIdx = flagColIdx;
4782 node->firstFlag = firstFlag;
4783 node->numGroups = numGroups;
4790 * Build a LockRows plan node
4793 make_lockrows(Plan *lefttree, List *rowMarks, int epqParam)
4795 LockRows *node = makeNode(LockRows);
4796 Plan *plan = &node->plan;
4798 copy_plan_costsize(plan, lefttree);
4800 /* charge cpu_tuple_cost to reflect locking costs (underestimate?) */
4801 plan->total_cost += cpu_tuple_cost * plan->plan_rows;
4803 plan->targetlist = lefttree->targetlist;
4805 plan->lefttree = lefttree;
4806 plan->righttree = NULL;
4808 node->rowMarks = rowMarks;
4809 node->epqParam = epqParam;
4815 * Note: offset_est and count_est are passed in to save having to repeat
4816 * work already done to estimate the values of the limitOffset and limitCount
4817 * expressions. Their values are as returned by preprocess_limit (0 means
4818 * "not relevant", -1 means "couldn't estimate"). Keep the code below in sync
4819 * with that function!
4822 make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount,
4823 int64 offset_est, int64 count_est)
4825 Limit *node = makeNode(Limit);
4826 Plan *plan = &node->plan;
4828 copy_plan_costsize(plan, lefttree);
4831 * Adjust the output rows count and costs according to the offset/limit.
4832 * This is only a cosmetic issue if we are at top level, but if we are
4833 * building a subquery then it's important to report correct info to the
4836 * When the offset or count couldn't be estimated, use 10% of the
4837 * estimated number of rows emitted from the subplan.
4839 if (offset_est != 0)
4844 offset_rows = (double) offset_est;
4846 offset_rows = clamp_row_est(lefttree->plan_rows * 0.10);
4847 if (offset_rows > plan->plan_rows)
4848 offset_rows = plan->plan_rows;
4849 if (plan->plan_rows > 0)
4850 plan->startup_cost +=
4851 (plan->total_cost - plan->startup_cost)
4852 * offset_rows / plan->plan_rows;
4853 plan->plan_rows -= offset_rows;
4854 if (plan->plan_rows < 1)
4855 plan->plan_rows = 1;
4863 count_rows = (double) count_est;
4865 count_rows = clamp_row_est(lefttree->plan_rows * 0.10);
4866 if (count_rows > plan->plan_rows)
4867 count_rows = plan->plan_rows;
4868 if (plan->plan_rows > 0)
4869 plan->total_cost = plan->startup_cost +
4870 (plan->total_cost - plan->startup_cost)
4871 * count_rows / plan->plan_rows;
4872 plan->plan_rows = count_rows;
4873 if (plan->plan_rows < 1)
4874 plan->plan_rows = 1;
4877 plan->targetlist = lefttree->targetlist;
4879 plan->lefttree = lefttree;
4880 plan->righttree = NULL;
4882 node->limitOffset = limitOffset;
4883 node->limitCount = limitCount;
4890 * Build a Result plan node
4892 * If we have a subplan, assume that any evaluation costs for the gating qual
4893 * were already factored into the subplan's startup cost, and just copy the
4894 * subplan cost. If there's no subplan, we should include the qual eval
4895 * cost. In either case, tlist eval cost is not to be included here.
4898 make_result(PlannerInfo *root,
4900 Node *resconstantqual,
4903 Result *node = makeNode(Result);
4904 Plan *plan = &node->plan;
4907 copy_plan_costsize(plan, subplan);
4910 plan->startup_cost = 0;
4911 plan->total_cost = cpu_tuple_cost;
4912 plan->plan_rows = 1; /* wrong if we have a set-valued function? */
4913 plan->plan_width = 0; /* XXX is it worth being smarter? */
4914 if (resconstantqual)
4918 cost_qual_eval(&qual_cost, (List *) resconstantqual, root);
4919 /* resconstantqual is evaluated once at startup */
4920 plan->startup_cost += qual_cost.startup + qual_cost.per_tuple;
4921 plan->total_cost += qual_cost.startup + qual_cost.per_tuple;
4925 plan->targetlist = tlist;
4927 plan->lefttree = subplan;
4928 plan->righttree = NULL;
4929 node->resconstantqual = resconstantqual;
4936 * Build a ModifyTable plan node
4938 * Currently, we don't charge anything extra for the actual table modification
4939 * work, nor for the WITH CHECK OPTIONS or RETURNING expressions if any. It
4940 * would only be window dressing, since these are always top-level nodes and
4941 * there is no way for the costs to change any higher-level planning choices.
4942 * But we might want to make it look better sometime.
4945 make_modifytable(PlannerInfo *root,
4946 CmdType operation, bool canSetTag,
4947 Index nominalRelation,
4948 List *resultRelations, List *subplans,
4949 List *withCheckOptionLists, List *returningLists,
4950 List *rowMarks, OnConflictExpr *onconflict, int epqParam)
4952 ModifyTable *node = makeNode(ModifyTable);
4953 Plan *plan = &node->plan;
4955 List *fdw_private_list;
4960 Assert(list_length(resultRelations) == list_length(subplans));
4961 Assert(withCheckOptionLists == NIL ||
4962 list_length(resultRelations) == list_length(withCheckOptionLists));
4963 Assert(returningLists == NIL ||
4964 list_length(resultRelations) == list_length(returningLists));
4967 * Compute cost as sum of subplan costs.
4969 plan->startup_cost = 0;
4970 plan->total_cost = 0;
4971 plan->plan_rows = 0;
4973 foreach(subnode, subplans)
4975 Plan *subplan = (Plan *) lfirst(subnode);
4977 if (subnode == list_head(subplans)) /* first node? */
4978 plan->startup_cost = subplan->startup_cost;
4979 plan->total_cost += subplan->total_cost;
4980 plan->plan_rows += subplan->plan_rows;
4981 total_size += subplan->plan_width * subplan->plan_rows;
4983 if (plan->plan_rows > 0)
4984 plan->plan_width = rint(total_size / plan->plan_rows);
4986 plan->plan_width = 0;
4988 node->plan.lefttree = NULL;
4989 node->plan.righttree = NULL;
4990 node->plan.qual = NIL;
4991 /* setrefs.c will fill in the targetlist, if needed */
4992 node->plan.targetlist = NIL;
4994 node->operation = operation;
4995 node->canSetTag = canSetTag;
4996 node->nominalRelation = nominalRelation;
4997 node->resultRelations = resultRelations;
4998 node->resultRelIndex = -1; /* will be set correctly in setrefs.c */
4999 node->plans = subplans;
5002 node->onConflictAction = ONCONFLICT_NONE;
5003 node->onConflictSet = NIL;
5004 node->onConflictWhere = NULL;
5005 node->arbiterIndexes = NIL;
5009 node->onConflictAction = onconflict->action;
5010 node->onConflictSet = onconflict->onConflictSet;
5011 node->onConflictWhere = onconflict->onConflictWhere;
5014 * If a set of unique index inference elements was provided (an
5015 * INSERT...ON CONFLICT "inference specification"), then infer
5016 * appropriate unique indexes (or throw an error if none are
5019 node->arbiterIndexes = infer_arbiter_indexes(root);
5021 node->exclRelRTI = onconflict->exclRelIndex;
5022 node->exclRelTlist = onconflict->exclRelTlist;
5024 node->withCheckOptionLists = withCheckOptionLists;
5025 node->returningLists = returningLists;
5026 node->rowMarks = rowMarks;
5027 node->epqParam = epqParam;
5030 * For each result relation that is a foreign table, allow the FDW to
5031 * construct private plan data, and accumulate it all into a list.
5033 fdw_private_list = NIL;
5035 foreach(lc, resultRelations)
5037 Index rti = lfirst_int(lc);
5038 FdwRoutine *fdwroutine;
5042 * If possible, we want to get the FdwRoutine from our RelOptInfo for
5043 * the table. But sometimes we don't have a RelOptInfo and must get
5044 * it the hard way. (In INSERT, the target relation is not scanned,
5045 * so it's not a baserel; and there are also corner cases for
5046 * updatable views where the target rel isn't a baserel.)
5048 if (rti < root->simple_rel_array_size &&
5049 root->simple_rel_array[rti] != NULL)
5051 RelOptInfo *resultRel = root->simple_rel_array[rti];
5053 fdwroutine = resultRel->fdwroutine;
5057 RangeTblEntry *rte = planner_rt_fetch(rti, root);
5059 Assert(rte->rtekind == RTE_RELATION);
5060 if (rte->relkind == RELKIND_FOREIGN_TABLE)
5061 fdwroutine = GetFdwRoutineByRelId(rte->relid);
5066 if (fdwroutine != NULL &&
5067 fdwroutine->PlanForeignModify != NULL)
5068 fdw_private = fdwroutine->PlanForeignModify(root, node, rti, i);
5071 fdw_private_list = lappend(fdw_private_list, fdw_private);
5074 node->fdwPrivLists = fdw_private_list;
5080 * is_projection_capable_plan
5081 * Check whether a given Plan node is able to do projection.
5084 is_projection_capable_plan(Plan *plan)
5086 /* Most plan types can project, so just list the ones that can't */
5087 switch (nodeTag(plan))
5099 case T_RecursiveUnion: