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-2006, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
13 * $PostgreSQL: pgsql/src/backend/optimizer/plan/createplan.c,v 1.218 2006/12/23 00:43:10 tgl Exp $
15 *-------------------------------------------------------------------------
21 #include "nodes/makefuncs.h"
22 #include "optimizer/clauses.h"
23 #include "optimizer/cost.h"
24 #include "optimizer/plancat.h"
25 #include "optimizer/planmain.h"
26 #include "optimizer/predtest.h"
27 #include "optimizer/restrictinfo.h"
28 #include "optimizer/tlist.h"
29 #include "optimizer/var.h"
30 #include "parser/parse_clause.h"
31 #include "parser/parse_expr.h"
32 #include "parser/parsetree.h"
33 #include "utils/lsyscache.h"
36 static Plan *create_scan_plan(PlannerInfo *root, Path *best_path);
37 static List *build_relation_tlist(RelOptInfo *rel);
38 static bool use_physical_tlist(RelOptInfo *rel);
39 static void disuse_physical_tlist(Plan *plan, Path *path);
40 static Plan *create_gating_plan(PlannerInfo *root, Plan *plan, List *quals);
41 static Plan *create_join_plan(PlannerInfo *root, JoinPath *best_path);
42 static Plan *create_append_plan(PlannerInfo *root, AppendPath *best_path);
43 static Result *create_result_plan(PlannerInfo *root, ResultPath *best_path);
44 static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path);
45 static Plan *create_unique_plan(PlannerInfo *root, UniquePath *best_path);
46 static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path,
47 List *tlist, List *scan_clauses);
48 static IndexScan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path,
49 List *tlist, List *scan_clauses,
50 List **nonlossy_clauses);
51 static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
52 BitmapHeapPath *best_path,
53 List *tlist, List *scan_clauses);
54 static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
55 List **qual, List **indexqual);
56 static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
57 List *tlist, List *scan_clauses);
58 static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
59 List *tlist, List *scan_clauses);
60 static FunctionScan *create_functionscan_plan(PlannerInfo *root, Path *best_path,
61 List *tlist, List *scan_clauses);
62 static ValuesScan *create_valuesscan_plan(PlannerInfo *root, Path *best_path,
63 List *tlist, List *scan_clauses);
64 static NestLoop *create_nestloop_plan(PlannerInfo *root, NestPath *best_path,
65 Plan *outer_plan, Plan *inner_plan);
66 static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path,
67 Plan *outer_plan, Plan *inner_plan);
68 static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path,
69 Plan *outer_plan, Plan *inner_plan);
70 static void fix_indexqual_references(List *indexquals, IndexPath *index_path,
71 List **fixed_indexquals,
72 List **nonlossy_indexquals,
75 static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index,
77 static List *get_switched_clauses(List *clauses, Relids outerrelids);
78 static List *order_qual_clauses(PlannerInfo *root, List *clauses);
79 static void copy_path_costsize(Plan *dest, Path *src);
80 static void copy_plan_costsize(Plan *dest, Plan *src);
81 static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
82 static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
83 Oid indexid, List *indexqual, List *indexqualorig,
84 List *indexstrategy, List *indexsubtype,
85 ScanDirection indexscandir);
86 static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid,
91 static BitmapHeapScan *make_bitmap_heapscan(List *qptlist,
96 static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
98 static FunctionScan *make_functionscan(List *qptlist, List *qpqual,
100 static ValuesScan *make_valuesscan(List *qptlist, List *qpqual,
102 static BitmapAnd *make_bitmap_and(List *bitmapplans);
103 static BitmapOr *make_bitmap_or(List *bitmapplans);
104 static NestLoop *make_nestloop(List *tlist,
105 List *joinclauses, List *otherclauses,
106 Plan *lefttree, Plan *righttree,
108 static HashJoin *make_hashjoin(List *tlist,
109 List *joinclauses, List *otherclauses,
111 Plan *lefttree, Plan *righttree,
113 static Hash *make_hash(Plan *lefttree);
114 static MergeJoin *make_mergejoin(List *tlist,
115 List *joinclauses, List *otherclauses,
116 List *mergeclauses, List *mergefamilies, List *mergestrategies,
117 Plan *lefttree, Plan *righttree,
119 static Sort *make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
120 AttrNumber *sortColIdx, Oid *sortOperators);
121 static Sort *make_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree,
127 * Creates the access plan for a query by tracing backwards through the
128 * desired chain of pathnodes, starting at the node 'best_path'. For
129 * every pathnode found:
130 * (1) Create a corresponding plan node containing appropriate id,
131 * target list, and qualification information.
132 * (2) Modify qual clauses of join nodes so that subplan attributes are
133 * referenced using relative values.
134 * (3) Target lists are not modified, but will be in setrefs.c.
136 * best_path is the best access path
138 * Returns a Plan tree.
141 create_plan(PlannerInfo *root, Path *best_path)
145 switch (best_path->pathtype)
149 case T_BitmapHeapScan:
154 plan = create_scan_plan(root, best_path);
159 plan = create_join_plan(root,
160 (JoinPath *) best_path);
163 plan = create_append_plan(root,
164 (AppendPath *) best_path);
167 plan = (Plan *) create_result_plan(root,
168 (ResultPath *) best_path);
171 plan = (Plan *) create_material_plan(root,
172 (MaterialPath *) best_path);
175 plan = create_unique_plan(root,
176 (UniquePath *) best_path);
179 elog(ERROR, "unrecognized node type: %d",
180 (int) best_path->pathtype);
181 plan = NULL; /* keep compiler quiet */
190 * Create a scan plan for the parent relation of 'best_path'.
193 create_scan_plan(PlannerInfo *root, Path *best_path)
195 RelOptInfo *rel = best_path->parent;
201 * For table scans, rather than using the relation targetlist (which is
202 * only those Vars actually needed by the query), we prefer to generate a
203 * tlist containing all Vars in order. This will allow the executor to
204 * optimize away projection of the table tuples, if possible. (Note that
205 * planner.c may replace the tlist we generate here, forcing projection to
208 if (use_physical_tlist(rel))
210 tlist = build_physical_tlist(root, rel);
211 /* if fail because of dropped cols, use regular method */
213 tlist = build_relation_tlist(rel);
216 tlist = build_relation_tlist(rel);
219 * Extract the relevant restriction clauses from the parent relation. The
220 * executor must apply all these restrictions during the scan, except for
221 * pseudoconstants which we'll take care of below.
223 scan_clauses = rel->baserestrictinfo;
225 switch (best_path->pathtype)
228 plan = (Plan *) create_seqscan_plan(root,
235 plan = (Plan *) create_indexscan_plan(root,
236 (IndexPath *) best_path,
242 case T_BitmapHeapScan:
243 plan = (Plan *) create_bitmap_scan_plan(root,
244 (BitmapHeapPath *) best_path,
250 plan = (Plan *) create_tidscan_plan(root,
251 (TidPath *) best_path,
257 plan = (Plan *) create_subqueryscan_plan(root,
264 plan = (Plan *) create_functionscan_plan(root,
271 plan = (Plan *) create_valuesscan_plan(root,
278 elog(ERROR, "unrecognized node type: %d",
279 (int) best_path->pathtype);
280 plan = NULL; /* keep compiler quiet */
285 * If there are any pseudoconstant clauses attached to this node, insert a
286 * gating Result node that evaluates the pseudoconstants as one-time
289 if (root->hasPseudoConstantQuals)
290 plan = create_gating_plan(root, plan, scan_clauses);
296 * Build a target list (ie, a list of TargetEntry) for a relation.
299 build_relation_tlist(RelOptInfo *rel)
305 foreach(v, rel->reltargetlist)
307 /* Do we really need to copy here? Not sure */
308 Var *var = (Var *) copyObject(lfirst(v));
310 tlist = lappend(tlist, makeTargetEntry((Expr *) var,
321 * Decide whether to use a tlist matching relation structure,
322 * rather than only those Vars actually referenced.
325 use_physical_tlist(RelOptInfo *rel)
330 * We can do this for real relation scans, subquery scans, function scans,
331 * and values scans (but not for, eg, joins).
333 if (rel->rtekind != RTE_RELATION &&
334 rel->rtekind != RTE_SUBQUERY &&
335 rel->rtekind != RTE_FUNCTION &&
336 rel->rtekind != RTE_VALUES)
340 * Can't do it with inheritance cases either (mainly because Append
343 if (rel->reloptkind != RELOPT_BASEREL)
347 * Can't do it if any system columns or whole-row Vars are requested,
348 * either. (This could possibly be fixed but would take some fragile
349 * assumptions in setrefs.c, I think.)
351 for (i = rel->min_attr; i <= 0; i++)
353 if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
361 * disuse_physical_tlist
362 * Switch a plan node back to emitting only Vars actually referenced.
364 * If the plan node immediately above a scan would prefer to get only
365 * needed Vars and not a physical tlist, it must call this routine to
366 * undo the decision made by use_physical_tlist(). Currently, Hash, Sort,
367 * and Material nodes want this, so they don't have to store useless columns.
370 disuse_physical_tlist(Plan *plan, Path *path)
372 /* Only need to undo it for path types handled by create_scan_plan() */
373 switch (path->pathtype)
377 case T_BitmapHeapScan:
382 plan->targetlist = build_relation_tlist(path->parent);
391 * Deal with pseudoconstant qual clauses
393 * If the node's quals list includes any pseudoconstant quals, put them
394 * into a gating Result node atop the already-built plan. Otherwise,
395 * return the plan as-is.
397 * Note that we don't change cost or size estimates when doing gating.
398 * The costs of qual eval were already folded into the plan's startup cost.
399 * Leaving the size alone amounts to assuming that the gating qual will
400 * succeed, which is the conservative estimate for planning upper queries.
401 * We certainly don't want to assume the output size is zero (unless the
402 * gating qual is actually constant FALSE, and that case is dealt with in
403 * clausesel.c). Interpolating between the two cases is silly, because
404 * it doesn't reflect what will really happen at runtime, and besides which
405 * in most cases we have only a very bad idea of the probability of the gating
409 create_gating_plan(PlannerInfo *root, Plan *plan, List *quals)
411 List *pseudoconstants;
413 /* Pull out any pseudoconstant quals from the RestrictInfo list */
414 pseudoconstants = extract_actual_clauses(quals, true);
416 if (!pseudoconstants)
419 pseudoconstants = order_qual_clauses(root, pseudoconstants);
421 return (Plan *) make_result((List *) copyObject(plan->targetlist),
422 (Node *) pseudoconstants,
428 * Create a join plan for 'best_path' and (recursively) plans for its
429 * inner and outer paths.
432 create_join_plan(PlannerInfo *root, JoinPath *best_path)
438 outer_plan = create_plan(root, best_path->outerjoinpath);
439 inner_plan = create_plan(root, best_path->innerjoinpath);
441 switch (best_path->path.pathtype)
444 plan = (Plan *) create_mergejoin_plan(root,
445 (MergePath *) best_path,
450 plan = (Plan *) create_hashjoin_plan(root,
451 (HashPath *) best_path,
456 plan = (Plan *) create_nestloop_plan(root,
457 (NestPath *) best_path,
462 elog(ERROR, "unrecognized node type: %d",
463 (int) best_path->path.pathtype);
464 plan = NULL; /* keep compiler quiet */
469 * If there are any pseudoconstant clauses attached to this node, insert a
470 * gating Result node that evaluates the pseudoconstants as one-time
473 if (root->hasPseudoConstantQuals)
474 plan = create_gating_plan(root, plan, best_path->joinrestrictinfo);
479 * * Expensive function pullups may have pulled local predicates * into
480 * this path node. Put them in the qpqual of the plan node. * JMH,
483 if (get_loc_restrictinfo(best_path) != NIL)
484 set_qpqual((Plan) plan,
485 list_concat(get_qpqual((Plan) plan),
486 get_actual_clauses(get_loc_restrictinfo(best_path))));
494 * Create an Append plan for 'best_path' and (recursively) plans
497 * Returns a Plan node.
500 create_append_plan(PlannerInfo *root, AppendPath *best_path)
503 List *tlist = build_relation_tlist(best_path->path.parent);
504 List *subplans = NIL;
508 * It is possible for the subplans list to contain only one entry, or even
509 * no entries. Handle these cases specially.
511 * XXX ideally, if there's just one entry, we'd not bother to generate an
512 * Append node but just return the single child. At the moment this does
513 * not work because the varno of the child scan plan won't match the
514 * parent-rel Vars it'll be asked to emit.
516 if (best_path->subpaths == NIL)
518 /* Generate a Result plan with constant-FALSE gating qual */
519 return (Plan *) make_result(tlist,
520 (Node *) list_make1(makeBoolConst(false,
525 /* Normal case with multiple subpaths */
526 foreach(subpaths, best_path->subpaths)
528 Path *subpath = (Path *) lfirst(subpaths);
530 subplans = lappend(subplans, create_plan(root, subpath));
533 plan = make_append(subplans, false, tlist);
535 return (Plan *) plan;
540 * Create a Result plan for 'best_path'.
541 * This is only used for the case of a query with an empty jointree.
543 * Returns a Plan node.
546 create_result_plan(PlannerInfo *root, ResultPath *best_path)
551 /* The tlist will be installed later, since we have no RelOptInfo */
552 Assert(best_path->path.parent == NULL);
555 quals = order_qual_clauses(root, best_path->quals);
557 return make_result(tlist, (Node *) quals, NULL);
561 * create_material_plan
562 * Create a Material plan for 'best_path' and (recursively) plans
565 * Returns a Plan node.
568 create_material_plan(PlannerInfo *root, MaterialPath *best_path)
573 subplan = create_plan(root, best_path->subpath);
575 /* We don't want any excess columns in the materialized tuples */
576 disuse_physical_tlist(subplan, best_path->subpath);
578 plan = make_material(subplan);
580 copy_path_costsize(&plan->plan, (Path *) best_path);
587 * Create a Unique plan for 'best_path' and (recursively) plans
590 * Returns a Plan node.
593 create_unique_plan(PlannerInfo *root, UniquePath *best_path)
602 AttrNumber *groupColIdx;
606 subplan = create_plan(root, best_path->subpath);
608 /* Done if we don't need to do any actual unique-ifying */
609 if (best_path->umethod == UNIQUE_PATH_NOOP)
613 * As constructed, the subplan has a "flat" tlist containing just the
614 * Vars needed here and at upper levels. The values we are supposed
615 * to unique-ify may be expressions in these variables. We have to
616 * add any such expressions to the subplan's tlist.
618 * The subplan may have a "physical" tlist if it is a simple scan plan.
619 * This should be left as-is if we don't need to add any expressions;
620 * but if we do have to add expressions, then a projection step will be
621 * needed at runtime anyway, and so we may as well remove unneeded items.
622 * Therefore newtlist starts from build_relation_tlist() not just a
623 * copy of the subplan's tlist; and we don't install it into the subplan
624 * unless stuff has to be added.
626 * To find the correct list of values to unique-ify, we look in the
627 * information saved for IN expressions. If this code is ever used in
628 * other scenarios, some other way of finding what to unique-ify will
632 uniq_exprs = NIL; /* just to keep compiler quiet */
633 foreach(l, root->in_info_list)
635 InClauseInfo *ininfo = (InClauseInfo *) lfirst(l);
637 if (bms_equal(ininfo->righthand, best_path->path.parent->relids))
639 uniq_exprs = ininfo->sub_targetlist;
643 if (l == NULL) /* fell out of loop? */
644 elog(ERROR, "could not find UniquePath in in_info_list");
646 /* initialize modified subplan tlist as just the "required" vars */
647 newtlist = build_relation_tlist(best_path->path.parent);
648 nextresno = list_length(newtlist) + 1;
651 foreach(l, uniq_exprs)
653 Node *uniqexpr = lfirst(l);
656 tle = tlist_member(uniqexpr, newtlist);
659 tle = makeTargetEntry((Expr *) uniqexpr,
663 newtlist = lappend(newtlist, tle);
672 * If the top plan node can't do projections, we need to add a Result
673 * node to help it along.
675 if (!is_projection_capable_plan(subplan))
676 subplan = (Plan *) make_result(newtlist, NULL, subplan);
678 subplan->targetlist = newtlist;
682 * Build control information showing which subplan output columns are to
683 * be examined by the grouping step. Unfortunately we can't merge this
684 * with the previous loop, since we didn't then know which version of the
685 * subplan tlist we'd end up using.
687 newtlist = subplan->targetlist;
688 numGroupCols = list_length(uniq_exprs);
689 groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber));
692 foreach(l, uniq_exprs)
694 Node *uniqexpr = lfirst(l);
697 tle = tlist_member(uniqexpr, newtlist);
698 if (!tle) /* shouldn't happen */
699 elog(ERROR, "failed to find unique expression in subplan tlist");
700 groupColIdx[groupColPos++] = tle->resno;
703 if (best_path->umethod == UNIQUE_PATH_HASH)
707 numGroups = (long) Min(best_path->rows, (double) LONG_MAX);
710 * Since the Agg node is going to project anyway, we can give it the
711 * minimum output tlist, without any stuff we might have added to the
714 plan = (Plan *) make_agg(root,
715 build_relation_tlist(best_path->path.parent),
726 List *sortList = NIL;
728 for (groupColPos = 0; groupColPos < numGroupCols; groupColPos++)
732 tle = get_tle_by_resno(subplan->targetlist,
733 groupColIdx[groupColPos]);
735 sortList = addTargetToSortList(NULL, tle,
736 sortList, subplan->targetlist,
737 SORTBY_ASC, NIL, false);
739 plan = (Plan *) make_sort_from_sortclauses(root, sortList, subplan);
740 plan = (Plan *) make_unique(plan, sortList);
743 /* Adjust output size estimate (other fields should be OK already) */
744 plan->plan_rows = best_path->rows;
750 /*****************************************************************************
752 * BASE-RELATION SCAN METHODS
754 *****************************************************************************/
758 * create_seqscan_plan
759 * Returns a seqscan plan for the base relation scanned by 'best_path'
760 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
763 create_seqscan_plan(PlannerInfo *root, Path *best_path,
764 List *tlist, List *scan_clauses)
767 Index scan_relid = best_path->parent->relid;
769 /* it should be a base rel... */
770 Assert(scan_relid > 0);
771 Assert(best_path->parent->rtekind == RTE_RELATION);
773 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
774 scan_clauses = extract_actual_clauses(scan_clauses, false);
776 /* Sort clauses into best execution order */
777 scan_clauses = order_qual_clauses(root, scan_clauses);
779 scan_plan = make_seqscan(tlist,
783 copy_path_costsize(&scan_plan->plan, best_path);
789 * create_indexscan_plan
790 * Returns an indexscan plan for the base relation scanned by 'best_path'
791 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
793 * The indexquals list of the path contains implicitly-ANDed qual conditions.
794 * The list can be empty --- then no index restrictions will be applied during
797 * If nonlossy_clauses isn't NULL, *nonlossy_clauses receives a list of the
798 * nonlossy indexquals.
801 create_indexscan_plan(PlannerInfo *root,
802 IndexPath *best_path,
805 List **nonlossy_clauses)
807 List *indexquals = best_path->indexquals;
808 Index baserelid = best_path->path.parent->relid;
809 Oid indexoid = best_path->indexinfo->indexoid;
811 List *stripped_indexquals;
812 List *fixed_indexquals;
813 List *nonlossy_indexquals;
817 IndexScan *scan_plan;
819 /* it should be a base rel... */
820 Assert(baserelid > 0);
821 Assert(best_path->path.parent->rtekind == RTE_RELATION);
824 * Build "stripped" indexquals structure (no RestrictInfos) to pass to
825 * executor as indexqualorig
827 stripped_indexquals = get_actual_clauses(indexquals);
830 * The executor needs a copy with the indexkey on the left of each clause
831 * and with index attr numbers substituted for table ones. This pass also
832 * gets strategy info and looks for "lossy" operators.
834 fix_indexqual_references(indexquals, best_path,
836 &nonlossy_indexquals,
840 /* pass back nonlossy quals if caller wants 'em */
841 if (nonlossy_clauses)
842 *nonlossy_clauses = nonlossy_indexquals;
845 * If this is an innerjoin scan, the indexclauses will contain join
846 * clauses that are not present in scan_clauses (since the passed-in value
847 * is just the rel's baserestrictinfo list). We must add these clauses to
848 * scan_clauses to ensure they get checked. In most cases we will remove
849 * the join clauses again below, but if a join clause contains a special
850 * operator, we need to make sure it gets into the scan_clauses.
852 * Note: pointer comparison should be enough to determine RestrictInfo
855 if (best_path->isjoininner)
856 scan_clauses = list_union_ptr(scan_clauses, best_path->indexclauses);
859 * The qpqual list must contain all restrictions not automatically handled
860 * by the index. All the predicates in the indexquals will be checked
861 * (either by the index itself, or by nodeIndexscan.c), but if there are
862 * any "special" operators involved then they must be included in qpqual.
863 * Also, any lossy index operators must be rechecked in the qpqual. The
864 * upshot is that qpqual must contain scan_clauses minus whatever appears
865 * in nonlossy_indexquals.
867 * In normal cases simple pointer equality checks will be enough to spot
868 * duplicate RestrictInfos, so we try that first. In some situations
869 * (particularly with OR'd index conditions) we may have scan_clauses that
870 * are not equal to, but are logically implied by, the index quals; so we
871 * also try a predicate_implied_by() check to see if we can discard quals
872 * that way. (predicate_implied_by assumes its first input contains only
873 * immutable functions, so we have to check that.)
875 * We can also discard quals that are implied by a partial index's
876 * predicate, but only in a plain SELECT; when scanning a target relation
877 * of UPDATE/DELETE/SELECT FOR UPDATE, we must leave such quals in the
878 * plan so that they'll be properly rechecked by EvalPlanQual testing.
880 * While at it, we strip off the RestrictInfos to produce a list of plain
881 * expressions (this loop replaces extract_actual_clauses used in the
882 * other routines in this file). We have to ignore pseudoconstants.
885 foreach(l, scan_clauses)
887 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
889 Assert(IsA(rinfo, RestrictInfo));
890 if (rinfo->pseudoconstant)
892 if (list_member_ptr(nonlossy_indexquals, rinfo))
894 if (!contain_mutable_functions((Node *) rinfo->clause))
896 List *clausel = list_make1(rinfo->clause);
898 if (predicate_implied_by(clausel, nonlossy_indexquals))
900 if (best_path->indexinfo->indpred)
902 if (baserelid != root->parse->resultRelation &&
903 get_rowmark(root->parse, baserelid) == NULL)
904 if (predicate_implied_by(clausel,
905 best_path->indexinfo->indpred))
909 qpqual = lappend(qpqual, rinfo->clause);
912 /* Sort clauses into best execution order */
913 qpqual = order_qual_clauses(root, qpqual);
915 /* Finally ready to build the plan node */
916 scan_plan = make_indexscan(tlist,
924 best_path->indexscandir);
926 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
927 /* use the indexscan-specific rows estimate, not the parent rel's */
928 scan_plan->scan.plan.plan_rows = best_path->rows;
934 * create_bitmap_scan_plan
935 * Returns a bitmap scan plan for the base relation scanned by 'best_path'
936 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
938 static BitmapHeapScan *
939 create_bitmap_scan_plan(PlannerInfo *root,
940 BitmapHeapPath *best_path,
944 Index baserelid = best_path->path.parent->relid;
945 Plan *bitmapqualplan;
946 List *bitmapqualorig;
950 BitmapHeapScan *scan_plan;
952 /* it should be a base rel... */
953 Assert(baserelid > 0);
954 Assert(best_path->path.parent->rtekind == RTE_RELATION);
956 /* Process the bitmapqual tree into a Plan tree and qual lists */
957 bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
958 &bitmapqualorig, &indexquals);
960 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
961 scan_clauses = extract_actual_clauses(scan_clauses, false);
964 * If this is a innerjoin scan, the indexclauses will contain join clauses
965 * that are not present in scan_clauses (since the passed-in value is just
966 * the rel's baserestrictinfo list). We must add these clauses to
967 * scan_clauses to ensure they get checked. In most cases we will remove
968 * the join clauses again below, but if a join clause contains a special
969 * operator, we need to make sure it gets into the scan_clauses.
971 if (best_path->isjoininner)
973 scan_clauses = list_concat_unique(scan_clauses, bitmapqualorig);
977 * The qpqual list must contain all restrictions not automatically handled
978 * by the index. All the predicates in the indexquals will be checked
979 * (either by the index itself, or by nodeBitmapHeapscan.c), but if there
980 * are any "special" or lossy operators involved then they must be added
981 * to qpqual. The upshot is that qpqual must contain scan_clauses minus
982 * whatever appears in indexquals.
984 * In normal cases simple equal() checks will be enough to spot duplicate
985 * clauses, so we try that first. In some situations (particularly with
986 * OR'd index conditions) we may have scan_clauses that are not equal to,
987 * but are logically implied by, the index quals; so we also try a
988 * predicate_implied_by() check to see if we can discard quals that way.
989 * (predicate_implied_by assumes its first input contains only immutable
990 * functions, so we have to check that.)
992 * Unlike create_indexscan_plan(), we need take no special thought here
993 * for partial index predicates; this is because the predicate conditions
994 * are already listed in bitmapqualorig and indexquals. Bitmap scans have
995 * to do it that way because predicate conditions need to be rechecked if
996 * the scan becomes lossy.
999 foreach(l, scan_clauses)
1001 Node *clause = (Node *) lfirst(l);
1003 if (list_member(indexquals, clause))
1005 if (!contain_mutable_functions(clause))
1007 List *clausel = list_make1(clause);
1009 if (predicate_implied_by(clausel, indexquals))
1012 qpqual = lappend(qpqual, clause);
1015 /* Sort clauses into best execution order */
1016 qpqual = order_qual_clauses(root, qpqual);
1019 * When dealing with special or lossy operators, we will at this point
1020 * have duplicate clauses in qpqual and bitmapqualorig. We may as well
1021 * drop 'em from bitmapqualorig, since there's no point in making the
1024 bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
1027 * Copy the finished bitmapqualorig to make sure we have an independent
1028 * copy --- needed in case there are subplans in the index quals
1030 bitmapqualorig = copyObject(bitmapqualorig);
1032 /* Finally ready to build the plan node */
1033 scan_plan = make_bitmap_heapscan(tlist,
1039 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
1040 /* use the indexscan-specific rows estimate, not the parent rel's */
1041 scan_plan->scan.plan.plan_rows = best_path->rows;
1047 * Given a bitmapqual tree, generate the Plan tree that implements it
1049 * As byproducts, we also return in *qual and *indexqual the qual lists
1050 * (in implicit-AND form, without RestrictInfos) describing the original index
1051 * conditions and the generated indexqual conditions. The latter is made to
1052 * exclude lossy index operators. Both lists include partial-index predicates,
1053 * because we have to recheck predicates as well as index conditions if the
1054 * bitmap scan becomes lossy.
1056 * Note: if you find yourself changing this, you probably need to change
1057 * make_restrictinfo_from_bitmapqual too.
1060 create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
1061 List **qual, List **indexqual)
1065 if (IsA(bitmapqual, BitmapAndPath))
1067 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
1068 List *subplans = NIL;
1069 List *subquals = NIL;
1070 List *subindexquals = NIL;
1074 * There may well be redundant quals among the subplans, since a
1075 * top-level WHERE qual might have gotten used to form several
1076 * different index quals. We don't try exceedingly hard to eliminate
1077 * redundancies, but we do eliminate obvious duplicates by using
1078 * list_concat_unique.
1080 foreach(l, apath->bitmapquals)
1086 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1087 &subqual, &subindexqual);
1088 subplans = lappend(subplans, subplan);
1089 subquals = list_concat_unique(subquals, subqual);
1090 subindexquals = list_concat_unique(subindexquals, subindexqual);
1092 plan = (Plan *) make_bitmap_and(subplans);
1093 plan->startup_cost = apath->path.startup_cost;
1094 plan->total_cost = apath->path.total_cost;
1096 clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
1097 plan->plan_width = 0; /* meaningless */
1099 *indexqual = subindexquals;
1101 else if (IsA(bitmapqual, BitmapOrPath))
1103 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
1104 List *subplans = NIL;
1105 List *subquals = NIL;
1106 List *subindexquals = NIL;
1107 bool const_true_subqual = false;
1108 bool const_true_subindexqual = false;
1112 * Here, we only detect qual-free subplans. A qual-free subplan would
1113 * cause us to generate "... OR true ..." which we may as well reduce
1114 * to just "true". We do not try to eliminate redundant subclauses
1115 * because (a) it's not as likely as in the AND case, and (b) we might
1116 * well be working with hundreds or even thousands of OR conditions,
1117 * perhaps from a long IN list. The performance of list_append_unique
1118 * would be unacceptable.
1120 foreach(l, opath->bitmapquals)
1126 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1127 &subqual, &subindexqual);
1128 subplans = lappend(subplans, subplan);
1130 const_true_subqual = true;
1131 else if (!const_true_subqual)
1132 subquals = lappend(subquals,
1133 make_ands_explicit(subqual));
1134 if (subindexqual == NIL)
1135 const_true_subindexqual = true;
1136 else if (!const_true_subindexqual)
1137 subindexquals = lappend(subindexquals,
1138 make_ands_explicit(subindexqual));
1142 * In the presence of ScalarArrayOpExpr quals, we might have built
1143 * BitmapOrPaths with just one subpath; don't add an OR step.
1145 if (list_length(subplans) == 1)
1147 plan = (Plan *) linitial(subplans);
1151 plan = (Plan *) make_bitmap_or(subplans);
1152 plan->startup_cost = opath->path.startup_cost;
1153 plan->total_cost = opath->path.total_cost;
1155 clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
1156 plan->plan_width = 0; /* meaningless */
1160 * If there were constant-TRUE subquals, the OR reduces to constant
1161 * TRUE. Also, avoid generating one-element ORs, which could happen
1162 * due to redundancy elimination or ScalarArrayOpExpr quals.
1164 if (const_true_subqual)
1166 else if (list_length(subquals) <= 1)
1169 *qual = list_make1(make_orclause(subquals));
1170 if (const_true_subindexqual)
1172 else if (list_length(subindexquals) <= 1)
1173 *indexqual = subindexquals;
1175 *indexqual = list_make1(make_orclause(subindexquals));
1177 else if (IsA(bitmapqual, IndexPath))
1179 IndexPath *ipath = (IndexPath *) bitmapqual;
1181 List *nonlossy_clauses;
1184 /* Use the regular indexscan plan build machinery... */
1185 iscan = create_indexscan_plan(root, ipath, NIL, NIL,
1187 /* then convert to a bitmap indexscan */
1188 plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
1191 iscan->indexqualorig,
1192 iscan->indexstrategy,
1193 iscan->indexsubtype);
1194 plan->startup_cost = 0.0;
1195 plan->total_cost = ipath->indextotalcost;
1197 clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
1198 plan->plan_width = 0; /* meaningless */
1199 *qual = get_actual_clauses(ipath->indexclauses);
1200 *indexqual = get_actual_clauses(nonlossy_clauses);
1201 foreach(l, ipath->indexinfo->indpred)
1203 Expr *pred = (Expr *) lfirst(l);
1206 * We know that the index predicate must have been implied by the
1207 * query condition as a whole, but it may or may not be implied by
1208 * the conditions that got pushed into the bitmapqual. Avoid
1209 * generating redundant conditions.
1211 if (!predicate_implied_by(list_make1(pred), ipath->indexclauses))
1213 *qual = lappend(*qual, pred);
1214 *indexqual = lappend(*indexqual, pred);
1220 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
1221 plan = NULL; /* keep compiler quiet */
1228 * create_tidscan_plan
1229 * Returns a tidscan plan for the base relation scanned by 'best_path'
1230 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1233 create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
1234 List *tlist, List *scan_clauses)
1237 Index scan_relid = best_path->path.parent->relid;
1240 /* it should be a base rel... */
1241 Assert(scan_relid > 0);
1242 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1244 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1245 scan_clauses = extract_actual_clauses(scan_clauses, false);
1248 * Remove any clauses that are TID quals. This is a bit tricky since the
1249 * tidquals list has implicit OR semantics.
1251 ortidquals = best_path->tidquals;
1252 if (list_length(ortidquals) > 1)
1253 ortidquals = list_make1(make_orclause(ortidquals));
1254 scan_clauses = list_difference(scan_clauses, ortidquals);
1256 /* Sort clauses into best execution order */
1257 scan_clauses = order_qual_clauses(root, scan_clauses);
1259 scan_plan = make_tidscan(tlist,
1262 best_path->tidquals);
1264 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
1270 * create_subqueryscan_plan
1271 * Returns a subqueryscan plan for the base relation scanned by 'best_path'
1272 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1274 static SubqueryScan *
1275 create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
1276 List *tlist, List *scan_clauses)
1278 SubqueryScan *scan_plan;
1279 Index scan_relid = best_path->parent->relid;
1281 /* it should be a subquery base rel... */
1282 Assert(scan_relid > 0);
1283 Assert(best_path->parent->rtekind == RTE_SUBQUERY);
1285 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1286 scan_clauses = extract_actual_clauses(scan_clauses, false);
1288 /* Sort clauses into best execution order */
1289 scan_clauses = order_qual_clauses(root, scan_clauses);
1291 scan_plan = make_subqueryscan(tlist,
1294 best_path->parent->subplan);
1296 copy_path_costsize(&scan_plan->scan.plan, best_path);
1302 * create_functionscan_plan
1303 * Returns a functionscan plan for the base relation scanned by 'best_path'
1304 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1306 static FunctionScan *
1307 create_functionscan_plan(PlannerInfo *root, Path *best_path,
1308 List *tlist, List *scan_clauses)
1310 FunctionScan *scan_plan;
1311 Index scan_relid = best_path->parent->relid;
1313 /* it should be a function base rel... */
1314 Assert(scan_relid > 0);
1315 Assert(best_path->parent->rtekind == RTE_FUNCTION);
1317 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1318 scan_clauses = extract_actual_clauses(scan_clauses, false);
1320 /* Sort clauses into best execution order */
1321 scan_clauses = order_qual_clauses(root, scan_clauses);
1323 scan_plan = make_functionscan(tlist, scan_clauses, scan_relid);
1325 copy_path_costsize(&scan_plan->scan.plan, best_path);
1331 * create_valuesscan_plan
1332 * Returns a valuesscan plan for the base relation scanned by 'best_path'
1333 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1336 create_valuesscan_plan(PlannerInfo *root, Path *best_path,
1337 List *tlist, List *scan_clauses)
1339 ValuesScan *scan_plan;
1340 Index scan_relid = best_path->parent->relid;
1342 /* it should be a values base rel... */
1343 Assert(scan_relid > 0);
1344 Assert(best_path->parent->rtekind == RTE_VALUES);
1346 /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
1347 scan_clauses = extract_actual_clauses(scan_clauses, false);
1349 /* Sort clauses into best execution order */
1350 scan_clauses = order_qual_clauses(root, scan_clauses);
1352 scan_plan = make_valuesscan(tlist, scan_clauses, scan_relid);
1354 copy_path_costsize(&scan_plan->scan.plan, best_path);
1359 /*****************************************************************************
1363 *****************************************************************************/
1366 create_nestloop_plan(PlannerInfo *root,
1367 NestPath *best_path,
1371 List *tlist = build_relation_tlist(best_path->path.parent);
1372 List *joinrestrictclauses = best_path->joinrestrictinfo;
1375 NestLoop *join_plan;
1377 if (IsA(best_path->innerjoinpath, IndexPath))
1380 * An index is being used to reduce the number of tuples scanned in
1381 * the inner relation. If there are join clauses being used with the
1382 * index, we may remove those join clauses from the list of clauses
1383 * that have to be checked as qpquals at the join node.
1385 * We can also remove any join clauses that are redundant with those
1386 * being used in the index scan; prior redundancy checks will not have
1387 * caught this case because the join clauses would never have been put
1388 * in the same joininfo list.
1390 * We can skip this if the index path is an ordinary indexpath and not
1391 * a special innerjoin path.
1393 IndexPath *innerpath = (IndexPath *) best_path->innerjoinpath;
1395 if (innerpath->isjoininner)
1397 joinrestrictclauses =
1398 select_nonredundant_join_clauses(root,
1399 joinrestrictclauses,
1400 innerpath->indexclauses,
1401 IS_OUTER_JOIN(best_path->jointype));
1404 else if (IsA(best_path->innerjoinpath, BitmapHeapPath))
1407 * Same deal for bitmapped index scans.
1409 * Note: both here and above, we ignore any implicit index
1410 * restrictions associated with the use of partial indexes. This is
1411 * OK because we're only trying to prove we can dispense with some
1412 * join quals; failing to prove that doesn't result in an incorrect
1413 * plan. It is the right way to proceed because adding more quals to
1414 * the stuff we got from the original query would just make it harder
1415 * to detect duplication. (Also, to change this we'd have to be wary
1416 * of UPDATE/DELETE/SELECT FOR UPDATE target relations; see notes
1417 * above about EvalPlanQual.)
1419 BitmapHeapPath *innerpath = (BitmapHeapPath *) best_path->innerjoinpath;
1421 if (innerpath->isjoininner)
1423 List *bitmapclauses;
1426 make_restrictinfo_from_bitmapqual(innerpath->bitmapqual,
1429 joinrestrictclauses =
1430 select_nonredundant_join_clauses(root,
1431 joinrestrictclauses,
1433 IS_OUTER_JOIN(best_path->jointype));
1437 /* Get the join qual clauses (in plain expression form) */
1438 /* Any pseudoconstant clauses are ignored here */
1439 if (IS_OUTER_JOIN(best_path->jointype))
1441 extract_actual_join_clauses(joinrestrictclauses,
1442 &joinclauses, &otherclauses);
1446 /* We can treat all clauses alike for an inner join */
1447 joinclauses = extract_actual_clauses(joinrestrictclauses, false);
1451 /* Sort clauses into best execution order */
1452 joinclauses = order_qual_clauses(root, joinclauses);
1453 otherclauses = order_qual_clauses(root, otherclauses);
1455 join_plan = make_nestloop(tlist,
1460 best_path->jointype);
1462 copy_path_costsize(&join_plan->join.plan, &best_path->path);
1468 create_mergejoin_plan(PlannerInfo *root,
1469 MergePath *best_path,
1473 List *tlist = build_relation_tlist(best_path->jpath.path.parent);
1477 MergeJoin *join_plan;
1479 /* Get the join qual clauses (in plain expression form) */
1480 /* Any pseudoconstant clauses are ignored here */
1481 if (IS_OUTER_JOIN(best_path->jpath.jointype))
1483 extract_actual_join_clauses(best_path->jpath.joinrestrictinfo,
1484 &joinclauses, &otherclauses);
1488 /* We can treat all clauses alike for an inner join */
1489 joinclauses = extract_actual_clauses(best_path->jpath.joinrestrictinfo,
1495 * Remove the mergeclauses from the list of join qual clauses, leaving the
1496 * list of quals that must be checked as qpquals.
1498 mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
1499 joinclauses = list_difference(joinclauses, mergeclauses);
1502 * Rearrange mergeclauses, if needed, so that the outer variable is always
1505 mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
1506 best_path->jpath.outerjoinpath->parent->relids);
1508 /* Sort clauses into best execution order */
1509 /* NB: do NOT reorder the mergeclauses */
1510 joinclauses = order_qual_clauses(root, joinclauses);
1511 otherclauses = order_qual_clauses(root, otherclauses);
1514 * Create explicit sort nodes for the outer and inner join paths if
1515 * necessary. The sort cost was already accounted for in the path. Make
1516 * sure there are no excess columns in the inputs if sorting.
1518 if (best_path->outersortkeys)
1520 disuse_physical_tlist(outer_plan, best_path->jpath.outerjoinpath);
1521 outer_plan = (Plan *)
1522 make_sort_from_pathkeys(root,
1524 best_path->outersortkeys);
1527 if (best_path->innersortkeys)
1529 disuse_physical_tlist(inner_plan, best_path->jpath.innerjoinpath);
1530 inner_plan = (Plan *)
1531 make_sort_from_pathkeys(root,
1533 best_path->innersortkeys);
1537 * Now we can build the mergejoin node.
1539 join_plan = make_mergejoin(tlist,
1543 best_path->path_mergefamilies,
1544 best_path->path_mergestrategies,
1547 best_path->jpath.jointype);
1549 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
1555 create_hashjoin_plan(PlannerInfo *root,
1556 HashPath *best_path,
1560 List *tlist = build_relation_tlist(best_path->jpath.path.parent);
1564 HashJoin *join_plan;
1567 /* Get the join qual clauses (in plain expression form) */
1568 /* Any pseudoconstant clauses are ignored here */
1569 if (IS_OUTER_JOIN(best_path->jpath.jointype))
1571 extract_actual_join_clauses(best_path->jpath.joinrestrictinfo,
1572 &joinclauses, &otherclauses);
1576 /* We can treat all clauses alike for an inner join */
1577 joinclauses = extract_actual_clauses(best_path->jpath.joinrestrictinfo,
1583 * Remove the hashclauses from the list of join qual clauses, leaving the
1584 * list of quals that must be checked as qpquals.
1586 hashclauses = get_actual_clauses(best_path->path_hashclauses);
1587 joinclauses = list_difference(joinclauses, hashclauses);
1590 * Rearrange hashclauses, if needed, so that the outer variable is always
1593 hashclauses = get_switched_clauses(best_path->path_hashclauses,
1594 best_path->jpath.outerjoinpath->parent->relids);
1596 /* Sort clauses into best execution order */
1597 joinclauses = order_qual_clauses(root, joinclauses);
1598 otherclauses = order_qual_clauses(root, otherclauses);
1599 hashclauses = order_qual_clauses(root, hashclauses);
1601 /* We don't want any excess columns in the hashed tuples */
1602 disuse_physical_tlist(inner_plan, best_path->jpath.innerjoinpath);
1605 * Build the hash node and hash join node.
1607 hash_plan = make_hash(inner_plan);
1608 join_plan = make_hashjoin(tlist,
1614 best_path->jpath.jointype);
1616 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
1622 /*****************************************************************************
1624 * SUPPORTING ROUTINES
1626 *****************************************************************************/
1629 * fix_indexqual_references
1630 * Adjust indexqual clauses to the form the executor's indexqual
1631 * machinery needs, and check for recheckable (lossy) index conditions.
1633 * We have five tasks here:
1634 * * Remove RestrictInfo nodes from the input clauses.
1635 * * Index keys must be represented by Var nodes with varattno set to the
1636 * index's attribute number, not the attribute number in the original rel.
1637 * * If the index key is on the right, commute the clause to put it on the
1639 * * We must construct lists of operator strategy numbers and subtypes
1640 * for the top-level operators of each index clause.
1641 * * We must detect any lossy index operators. The API is that we return
1642 * a list of the input clauses whose operators are NOT lossy.
1644 * fixed_indexquals receives a modified copy of the indexquals list --- the
1645 * original is not changed. Note also that the copy shares no substructure
1646 * with the original; this is needed in case there is a subplan in it (we need
1647 * two separate copies of the subplan tree, or things will go awry).
1649 * nonlossy_indexquals receives a list of the original input clauses (with
1650 * RestrictInfos) that contain non-lossy operators.
1652 * indexstrategy receives an integer list of strategy numbers.
1653 * indexsubtype receives an OID list of strategy subtypes.
1656 fix_indexqual_references(List *indexquals, IndexPath *index_path,
1657 List **fixed_indexquals,
1658 List **nonlossy_indexquals,
1659 List **indexstrategy,
1660 List **indexsubtype)
1662 IndexOptInfo *index = index_path->indexinfo;
1665 *fixed_indexquals = NIL;
1666 *nonlossy_indexquals = NIL;
1667 *indexstrategy = NIL;
1668 *indexsubtype = NIL;
1671 * For each qual clause, commute if needed to put the indexkey operand on
1672 * the left, and then fix its varattno. (We do not need to change the
1673 * other side of the clause.) Then determine the operator's strategy
1674 * number and subtype number, and check for lossy index behavior.
1676 foreach(l, indexquals)
1678 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1687 Assert(IsA(rinfo, RestrictInfo));
1690 * Make a copy that will become the fixed clause.
1692 * We used to try to do a shallow copy here, but that fails if there
1693 * is a subplan in the arguments of the opclause. So just do a full
1696 clause = (Expr *) copyObject((Node *) rinfo->clause);
1698 if (IsA(clause, OpExpr))
1700 OpExpr *op = (OpExpr *) clause;
1702 if (list_length(op->args) != 2)
1703 elog(ERROR, "indexqual clause is not binary opclause");
1706 * Check to see if the indexkey is on the right; if so, commute
1707 * the clause. The indexkey should be the side that refers to
1708 * (only) the base relation.
1710 if (!bms_equal(rinfo->left_relids, index->rel->relids))
1714 * Now, determine which index attribute this is, change the
1715 * indexkey operand as needed, and get the index opfamily.
1717 linitial(op->args) = fix_indexqual_operand(linitial(op->args),
1720 clause_op = op->opno;
1722 else if (IsA(clause, RowCompareExpr))
1724 RowCompareExpr *rc = (RowCompareExpr *) clause;
1728 * Check to see if the indexkey is on the right; if so, commute
1729 * the clause. The indexkey should be the side that refers to
1730 * (only) the base relation.
1732 if (!bms_overlap(pull_varnos(linitial(rc->largs)),
1733 index->rel->relids))
1734 CommuteRowCompareExpr(rc);
1737 * For each column in the row comparison, determine which index
1738 * attribute this is and change the indexkey operand as needed.
1740 * Save the index opfamily for only the first column. We will
1741 * return the operator and opfamily info for just the first column
1742 * of the row comparison; the executor will have to look up the
1743 * rest if it needs them.
1745 foreach(lc, rc->largs)
1749 lfirst(lc) = fix_indexqual_operand(lfirst(lc),
1752 if (lc == list_head(rc->largs))
1753 opfamily = tmp_opfamily;
1755 clause_op = linitial_oid(rc->opnos);
1757 else if (IsA(clause, ScalarArrayOpExpr))
1759 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
1761 /* Never need to commute... */
1764 * Now, determine which index attribute this is, change the
1765 * indexkey operand as needed, and get the index opfamily.
1767 linitial(saop->args) = fix_indexqual_operand(linitial(saop->args),
1770 clause_op = saop->opno;
1774 elog(ERROR, "unsupported indexqual type: %d",
1775 (int) nodeTag(clause));
1776 continue; /* keep compiler quiet */
1779 *fixed_indexquals = lappend(*fixed_indexquals, clause);
1782 * Look up the (possibly commuted) operator in the operator family to
1783 * get its strategy number and the recheck indicator. This also
1784 * double-checks that we found an operator matching the index.
1786 get_op_opfamily_properties(clause_op, opfamily,
1792 *indexstrategy = lappend_int(*indexstrategy, stratno);
1793 *indexsubtype = lappend_oid(*indexsubtype, stratrighttype);
1795 /* If it's not lossy, add to nonlossy_indexquals */
1797 *nonlossy_indexquals = lappend(*nonlossy_indexquals, rinfo);
1802 fix_indexqual_operand(Node *node, IndexOptInfo *index, Oid *opfamily)
1805 * We represent index keys by Var nodes having the varno of the base table
1806 * but varattno equal to the index's attribute number (index column
1807 * position). This is a bit hokey ... would be cleaner to use a
1808 * special-purpose node type that could not be mistaken for a regular Var.
1809 * But it will do for now.
1813 ListCell *indexpr_item;
1816 * Remove any binary-compatible relabeling of the indexkey
1818 if (IsA(node, RelabelType))
1819 node = (Node *) ((RelabelType *) node)->arg;
1821 if (IsA(node, Var) &&
1822 ((Var *) node)->varno == index->rel->relid)
1824 /* Try to match against simple index columns */
1825 int varatt = ((Var *) node)->varattno;
1829 for (pos = 0; pos < index->ncolumns; pos++)
1831 if (index->indexkeys[pos] == varatt)
1833 result = (Var *) copyObject(node);
1834 result->varattno = pos + 1;
1835 /* return the correct opfamily, too */
1836 *opfamily = index->opfamily[pos];
1837 return (Node *) result;
1843 /* Try to match against index expressions */
1844 indexpr_item = list_head(index->indexprs);
1845 for (pos = 0; pos < index->ncolumns; pos++)
1847 if (index->indexkeys[pos] == 0)
1851 if (indexpr_item == NULL)
1852 elog(ERROR, "too few entries in indexprs list");
1853 indexkey = (Node *) lfirst(indexpr_item);
1854 if (indexkey && IsA(indexkey, RelabelType))
1855 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
1856 if (equal(node, indexkey))
1859 result = makeVar(index->rel->relid, pos + 1,
1860 exprType(lfirst(indexpr_item)), -1,
1862 /* return the correct opfamily, too */
1863 *opfamily = index->opfamily[pos];
1864 return (Node *) result;
1866 indexpr_item = lnext(indexpr_item);
1871 elog(ERROR, "node is not an index attribute");
1872 *opfamily = InvalidOid; /* keep compiler quiet */
1877 * get_switched_clauses
1878 * Given a list of merge or hash joinclauses (as RestrictInfo nodes),
1879 * extract the bare clauses, and rearrange the elements within the
1880 * clauses, if needed, so the outer join variable is on the left and
1881 * the inner is on the right. The original data structure is not touched;
1882 * a modified list is returned.
1885 get_switched_clauses(List *clauses, Relids outerrelids)
1892 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
1893 OpExpr *clause = (OpExpr *) restrictinfo->clause;
1895 Assert(is_opclause(clause));
1896 if (bms_is_subset(restrictinfo->right_relids, outerrelids))
1899 * Duplicate just enough of the structure to allow commuting the
1900 * clause without changing the original list. Could use
1901 * copyObject, but a complete deep copy is overkill.
1903 OpExpr *temp = makeNode(OpExpr);
1905 temp->opno = clause->opno;
1906 temp->opfuncid = InvalidOid;
1907 temp->opresulttype = clause->opresulttype;
1908 temp->opretset = clause->opretset;
1909 temp->args = list_copy(clause->args);
1910 /* Commute it --- note this modifies the temp node in-place. */
1911 CommuteOpExpr(temp);
1912 t_list = lappend(t_list, temp);
1915 t_list = lappend(t_list, clause);
1921 * order_qual_clauses
1922 * Given a list of qual clauses that will all be evaluated at the same
1923 * plan node, sort the list into the order we want to check the quals
1926 * Ideally the order should be driven by a combination of execution cost and
1927 * selectivity, but unfortunately we have so little information about
1928 * execution cost of operators that it's really hard to do anything smart.
1929 * For now, we just move any quals that contain SubPlan references (but not
1930 * InitPlan references) to the end of the list.
1933 order_qual_clauses(PlannerInfo *root, List *clauses)
1939 /* No need to work hard if the query is subselect-free */
1940 if (!root->parse->hasSubLinks)
1947 Node *clause = (Node *) lfirst(l);
1949 if (contain_subplans(clause))
1950 withsubplans = lappend(withsubplans, clause);
1952 nosubplans = lappend(nosubplans, clause);
1955 return list_concat(nosubplans, withsubplans);
1959 * Copy cost and size info from a Path node to the Plan node created from it.
1960 * The executor won't use this info, but it's needed by EXPLAIN.
1963 copy_path_costsize(Plan *dest, Path *src)
1967 dest->startup_cost = src->startup_cost;
1968 dest->total_cost = src->total_cost;
1969 dest->plan_rows = src->parent->rows;
1970 dest->plan_width = src->parent->width;
1974 dest->startup_cost = 0;
1975 dest->total_cost = 0;
1976 dest->plan_rows = 0;
1977 dest->plan_width = 0;
1982 * Copy cost and size info from a lower plan node to an inserted node.
1983 * This is not critical, since the decisions have already been made,
1984 * but it helps produce more reasonable-looking EXPLAIN output.
1985 * (Some callers alter the info after copying it.)
1988 copy_plan_costsize(Plan *dest, Plan *src)
1992 dest->startup_cost = src->startup_cost;
1993 dest->total_cost = src->total_cost;
1994 dest->plan_rows = src->plan_rows;
1995 dest->plan_width = src->plan_width;
1999 dest->startup_cost = 0;
2000 dest->total_cost = 0;
2001 dest->plan_rows = 0;
2002 dest->plan_width = 0;
2007 /*****************************************************************************
2009 * PLAN NODE BUILDING ROUTINES
2011 * Some of these are exported because they are called to build plan nodes
2012 * in contexts where we're not deriving the plan node from a path node.
2014 *****************************************************************************/
2017 make_seqscan(List *qptlist,
2021 SeqScan *node = makeNode(SeqScan);
2022 Plan *plan = &node->plan;
2024 /* cost should be inserted by caller */
2025 plan->targetlist = qptlist;
2026 plan->qual = qpqual;
2027 plan->lefttree = NULL;
2028 plan->righttree = NULL;
2029 node->scanrelid = scanrelid;
2035 make_indexscan(List *qptlist,
2040 List *indexqualorig,
2041 List *indexstrategy,
2043 ScanDirection indexscandir)
2045 IndexScan *node = makeNode(IndexScan);
2046 Plan *plan = &node->scan.plan;
2048 /* cost should be inserted by caller */
2049 plan->targetlist = qptlist;
2050 plan->qual = qpqual;
2051 plan->lefttree = NULL;
2052 plan->righttree = NULL;
2053 node->scan.scanrelid = scanrelid;
2054 node->indexid = indexid;
2055 node->indexqual = indexqual;
2056 node->indexqualorig = indexqualorig;
2057 node->indexstrategy = indexstrategy;
2058 node->indexsubtype = indexsubtype;
2059 node->indexorderdir = indexscandir;
2064 static BitmapIndexScan *
2065 make_bitmap_indexscan(Index scanrelid,
2068 List *indexqualorig,
2069 List *indexstrategy,
2072 BitmapIndexScan *node = makeNode(BitmapIndexScan);
2073 Plan *plan = &node->scan.plan;
2075 /* cost should be inserted by caller */
2076 plan->targetlist = NIL; /* not used */
2077 plan->qual = NIL; /* not used */
2078 plan->lefttree = NULL;
2079 plan->righttree = NULL;
2080 node->scan.scanrelid = scanrelid;
2081 node->indexid = indexid;
2082 node->indexqual = indexqual;
2083 node->indexqualorig = indexqualorig;
2084 node->indexstrategy = indexstrategy;
2085 node->indexsubtype = indexsubtype;
2090 static BitmapHeapScan *
2091 make_bitmap_heapscan(List *qptlist,
2094 List *bitmapqualorig,
2097 BitmapHeapScan *node = makeNode(BitmapHeapScan);
2098 Plan *plan = &node->scan.plan;
2100 /* cost should be inserted by caller */
2101 plan->targetlist = qptlist;
2102 plan->qual = qpqual;
2103 plan->lefttree = lefttree;
2104 plan->righttree = NULL;
2105 node->scan.scanrelid = scanrelid;
2106 node->bitmapqualorig = bitmapqualorig;
2112 make_tidscan(List *qptlist,
2117 TidScan *node = makeNode(TidScan);
2118 Plan *plan = &node->scan.plan;
2120 /* cost should be inserted by caller */
2121 plan->targetlist = qptlist;
2122 plan->qual = qpqual;
2123 plan->lefttree = NULL;
2124 plan->righttree = NULL;
2125 node->scan.scanrelid = scanrelid;
2126 node->tidquals = tidquals;
2132 make_subqueryscan(List *qptlist,
2137 SubqueryScan *node = makeNode(SubqueryScan);
2138 Plan *plan = &node->scan.plan;
2141 * Cost is figured here for the convenience of prepunion.c. Note this is
2142 * only correct for the case where qpqual is empty; otherwise caller
2143 * should overwrite cost with a better estimate.
2145 copy_plan_costsize(plan, subplan);
2146 plan->total_cost += cpu_tuple_cost * subplan->plan_rows;
2148 plan->targetlist = qptlist;
2149 plan->qual = qpqual;
2150 plan->lefttree = NULL;
2151 plan->righttree = NULL;
2152 node->scan.scanrelid = scanrelid;
2153 node->subplan = subplan;
2158 static FunctionScan *
2159 make_functionscan(List *qptlist,
2163 FunctionScan *node = makeNode(FunctionScan);
2164 Plan *plan = &node->scan.plan;
2166 /* cost should be inserted by caller */
2167 plan->targetlist = qptlist;
2168 plan->qual = qpqual;
2169 plan->lefttree = NULL;
2170 plan->righttree = NULL;
2171 node->scan.scanrelid = scanrelid;
2177 make_valuesscan(List *qptlist,
2181 ValuesScan *node = makeNode(ValuesScan);
2182 Plan *plan = &node->scan.plan;
2184 /* cost should be inserted by caller */
2185 plan->targetlist = qptlist;
2186 plan->qual = qpqual;
2187 plan->lefttree = NULL;
2188 plan->righttree = NULL;
2189 node->scan.scanrelid = scanrelid;
2195 make_append(List *appendplans, bool isTarget, List *tlist)
2197 Append *node = makeNode(Append);
2198 Plan *plan = &node->plan;
2202 * Compute cost as sum of subplan costs. We charge nothing extra for the
2203 * Append itself, which perhaps is too optimistic, but since it doesn't do
2204 * any selection or projection, it is a pretty cheap node.
2206 plan->startup_cost = 0;
2207 plan->total_cost = 0;
2208 plan->plan_rows = 0;
2209 plan->plan_width = 0;
2210 foreach(subnode, appendplans)
2212 Plan *subplan = (Plan *) lfirst(subnode);
2214 if (subnode == list_head(appendplans)) /* first node? */
2215 plan->startup_cost = subplan->startup_cost;
2216 plan->total_cost += subplan->total_cost;
2217 plan->plan_rows += subplan->plan_rows;
2218 if (plan->plan_width < subplan->plan_width)
2219 plan->plan_width = subplan->plan_width;
2222 plan->targetlist = tlist;
2224 plan->lefttree = NULL;
2225 plan->righttree = NULL;
2226 node->appendplans = appendplans;
2227 node->isTarget = isTarget;
2233 make_bitmap_and(List *bitmapplans)
2235 BitmapAnd *node = makeNode(BitmapAnd);
2236 Plan *plan = &node->plan;
2238 /* cost should be inserted by caller */
2239 plan->targetlist = NIL;
2241 plan->lefttree = NULL;
2242 plan->righttree = NULL;
2243 node->bitmapplans = bitmapplans;
2249 make_bitmap_or(List *bitmapplans)
2251 BitmapOr *node = makeNode(BitmapOr);
2252 Plan *plan = &node->plan;
2254 /* cost should be inserted by caller */
2255 plan->targetlist = NIL;
2257 plan->lefttree = NULL;
2258 plan->righttree = NULL;
2259 node->bitmapplans = bitmapplans;
2265 make_nestloop(List *tlist,
2272 NestLoop *node = makeNode(NestLoop);
2273 Plan *plan = &node->join.plan;
2275 /* cost should be inserted by caller */
2276 plan->targetlist = tlist;
2277 plan->qual = otherclauses;
2278 plan->lefttree = lefttree;
2279 plan->righttree = righttree;
2280 node->join.jointype = jointype;
2281 node->join.joinqual = joinclauses;
2287 make_hashjoin(List *tlist,
2295 HashJoin *node = makeNode(HashJoin);
2296 Plan *plan = &node->join.plan;
2298 /* cost should be inserted by caller */
2299 plan->targetlist = tlist;
2300 plan->qual = otherclauses;
2301 plan->lefttree = lefttree;
2302 plan->righttree = righttree;
2303 node->hashclauses = hashclauses;
2304 node->join.jointype = jointype;
2305 node->join.joinqual = joinclauses;
2311 make_hash(Plan *lefttree)
2313 Hash *node = makeNode(Hash);
2314 Plan *plan = &node->plan;
2316 copy_plan_costsize(plan, lefttree);
2319 * For plausibility, make startup & total costs equal total cost of input
2320 * plan; this only affects EXPLAIN display not decisions.
2322 plan->startup_cost = plan->total_cost;
2323 plan->targetlist = copyObject(lefttree->targetlist);
2325 plan->lefttree = lefttree;
2326 plan->righttree = NULL;
2332 make_mergejoin(List *tlist,
2336 List *mergefamilies,
2337 List *mergestrategies,
2342 MergeJoin *node = makeNode(MergeJoin);
2343 Plan *plan = &node->join.plan;
2345 /* cost should be inserted by caller */
2346 plan->targetlist = tlist;
2347 plan->qual = otherclauses;
2348 plan->lefttree = lefttree;
2349 plan->righttree = righttree;
2350 node->mergeclauses = mergeclauses;
2351 node->mergefamilies = mergefamilies;
2352 node->mergestrategies = mergestrategies;
2353 node->join.jointype = jointype;
2354 node->join.joinqual = joinclauses;
2360 * make_sort --- basic routine to build a Sort plan node
2362 * Caller must have built the sortColIdx and sortOperators arrays already.
2365 make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
2366 AttrNumber *sortColIdx, Oid *sortOperators)
2368 Sort *node = makeNode(Sort);
2369 Plan *plan = &node->plan;
2370 Path sort_path; /* dummy for result of cost_sort */
2372 copy_plan_costsize(plan, lefttree); /* only care about copying size */
2373 cost_sort(&sort_path, root, NIL,
2374 lefttree->total_cost,
2375 lefttree->plan_rows,
2376 lefttree->plan_width);
2377 plan->startup_cost = sort_path.startup_cost;
2378 plan->total_cost = sort_path.total_cost;
2379 plan->targetlist = copyObject(lefttree->targetlist);
2381 plan->lefttree = lefttree;
2382 plan->righttree = NULL;
2383 node->numCols = numCols;
2384 node->sortColIdx = sortColIdx;
2385 node->sortOperators = sortOperators;
2391 * add_sort_column --- utility subroutine for building sort info arrays
2393 * We need this routine because the same column might be selected more than
2394 * once as a sort key column; if so, the extra mentions are redundant.
2396 * Caller is assumed to have allocated the arrays large enough for the
2397 * max possible number of columns. Return value is the new column count.
2400 add_sort_column(AttrNumber colIdx, Oid sortOp,
2401 int numCols, AttrNumber *sortColIdx, Oid *sortOperators)
2405 for (i = 0; i < numCols; i++)
2407 if (sortColIdx[i] == colIdx)
2409 /* Already sorting by this col, so extra sort key is useless */
2414 /* Add the column */
2415 sortColIdx[numCols] = colIdx;
2416 sortOperators[numCols] = sortOp;
2421 * make_sort_from_pathkeys
2422 * Create sort plan to sort according to given pathkeys
2424 * 'lefttree' is the node which yields input tuples
2425 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
2427 * We must convert the pathkey information into arrays of sort key column
2428 * numbers and sort operator OIDs.
2430 * If the pathkeys include expressions that aren't simple Vars, we will
2431 * usually need to add resjunk items to the input plan's targetlist to
2432 * compute these expressions (since the Sort node itself won't do it).
2433 * If the input plan type isn't one that can do projections, this means
2434 * adding a Result node just to do the projection.
2437 make_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys)
2439 List *tlist = lefttree->targetlist;
2442 AttrNumber *sortColIdx;
2446 * We will need at most list_length(pathkeys) sort columns; possibly less
2448 numsortkeys = list_length(pathkeys);
2449 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
2450 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
2454 foreach(i, pathkeys)
2456 List *keysublist = (List *) lfirst(i);
2457 PathKeyItem *pathkey = NULL;
2458 TargetEntry *tle = NULL;
2462 * We can sort by any one of the sort key items listed in this
2463 * sublist. For now, we take the first one that corresponds to an
2464 * available Var in the tlist. If there isn't any, use the first one
2465 * that is an expression in the input's vars.
2467 * XXX if we have a choice, is there any way of figuring out which
2468 * might be cheapest to execute? (For example, int4lt is likely much
2469 * cheaper to execute than numericlt, but both might appear in the
2470 * same pathkey sublist...) Not clear that we ever will have a choice
2471 * in practice, so it may not matter.
2473 foreach(j, keysublist)
2475 pathkey = (PathKeyItem *) lfirst(j);
2476 Assert(IsA(pathkey, PathKeyItem));
2477 tle = tlist_member(pathkey->key, tlist);
2483 /* No matching Var; look for a computable expression */
2484 foreach(j, keysublist)
2489 pathkey = (PathKeyItem *) lfirst(j);
2490 exprvars = pull_var_clause(pathkey->key, false);
2491 foreach(k, exprvars)
2493 if (!tlist_member(lfirst(k), tlist))
2496 list_free(exprvars);
2498 break; /* found usable expression */
2501 elog(ERROR, "could not find pathkey item to sort");
2504 * Do we need to insert a Result node?
2506 if (!is_projection_capable_plan(lefttree))
2508 tlist = copyObject(tlist);
2509 lefttree = (Plan *) make_result(tlist, NULL, lefttree);
2513 * Add resjunk entry to input's tlist
2515 tle = makeTargetEntry((Expr *) pathkey->key,
2516 list_length(tlist) + 1,
2519 tlist = lappend(tlist, tle);
2520 lefttree->targetlist = tlist; /* just in case NIL before */
2524 * The column might already be selected as a sort key, if the pathkeys
2525 * contain duplicate entries. (This can happen in scenarios where
2526 * multiple mergejoinable clauses mention the same var, for example.)
2527 * So enter it only once in the sort arrays.
2529 numsortkeys = add_sort_column(tle->resno, pathkey->sortop,
2530 numsortkeys, sortColIdx, sortOperators);
2533 Assert(numsortkeys > 0);
2535 return make_sort(root, lefttree, numsortkeys,
2536 sortColIdx, sortOperators);
2540 * make_sort_from_sortclauses
2541 * Create sort plan to sort according to given sortclauses
2543 * 'sortcls' is a list of SortClauses
2544 * 'lefttree' is the node which yields input tuples
2547 make_sort_from_sortclauses(PlannerInfo *root, List *sortcls, Plan *lefttree)
2549 List *sub_tlist = lefttree->targetlist;
2552 AttrNumber *sortColIdx;
2556 * We will need at most list_length(sortcls) sort columns; possibly less
2558 numsortkeys = list_length(sortcls);
2559 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
2560 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
2566 SortClause *sortcl = (SortClause *) lfirst(l);
2567 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
2570 * Check for the possibility of duplicate order-by clauses --- the
2571 * parser should have removed 'em, but no point in sorting
2574 numsortkeys = add_sort_column(tle->resno, sortcl->sortop,
2575 numsortkeys, sortColIdx, sortOperators);
2578 Assert(numsortkeys > 0);
2580 return make_sort(root, lefttree, numsortkeys,
2581 sortColIdx, sortOperators);
2585 * make_sort_from_groupcols
2586 * Create sort plan to sort based on grouping columns
2588 * 'groupcls' is the list of GroupClauses
2589 * 'grpColIdx' gives the column numbers to use
2591 * This might look like it could be merged with make_sort_from_sortclauses,
2592 * but presently we *must* use the grpColIdx[] array to locate sort columns,
2593 * because the child plan's tlist is not marked with ressortgroupref info
2594 * appropriate to the grouping node. So, only the sortop is used from the
2595 * GroupClause entries.
2598 make_sort_from_groupcols(PlannerInfo *root,
2600 AttrNumber *grpColIdx,
2603 List *sub_tlist = lefttree->targetlist;
2607 AttrNumber *sortColIdx;
2611 * We will need at most list_length(groupcls) sort columns; possibly less
2613 numsortkeys = list_length(groupcls);
2614 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
2615 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
2619 foreach(l, groupcls)
2621 GroupClause *grpcl = (GroupClause *) lfirst(l);
2622 TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[grpno]);
2625 * Check for the possibility of duplicate group-by clauses --- the
2626 * parser should have removed 'em, but no point in sorting
2629 numsortkeys = add_sort_column(tle->resno, grpcl->sortop,
2630 numsortkeys, sortColIdx, sortOperators);
2634 Assert(numsortkeys > 0);
2636 return make_sort(root, lefttree, numsortkeys,
2637 sortColIdx, sortOperators);
2641 make_material(Plan *lefttree)
2643 Material *node = makeNode(Material);
2644 Plan *plan = &node->plan;
2646 /* cost should be inserted by caller */
2647 plan->targetlist = copyObject(lefttree->targetlist);
2649 plan->lefttree = lefttree;
2650 plan->righttree = NULL;
2656 * materialize_finished_plan: stick a Material node atop a completed plan
2658 * There are a couple of places where we want to attach a Material node
2659 * after completion of subquery_planner(). This currently requires hackery.
2660 * Since subquery_planner has already run SS_finalize_plan on the subplan
2661 * tree, we have to kluge up parameter lists for the Material node.
2662 * Possibly this could be fixed by postponing SS_finalize_plan processing
2663 * until setrefs.c is run?
2666 materialize_finished_plan(Plan *subplan)
2669 Path matpath; /* dummy for result of cost_material */
2671 matplan = (Plan *) make_material(subplan);
2674 cost_material(&matpath,
2675 subplan->total_cost,
2677 subplan->plan_width);
2678 matplan->startup_cost = matpath.startup_cost;
2679 matplan->total_cost = matpath.total_cost;
2680 matplan->plan_rows = subplan->plan_rows;
2681 matplan->plan_width = subplan->plan_width;
2683 /* parameter kluge --- see comments above */
2684 matplan->extParam = bms_copy(subplan->extParam);
2685 matplan->allParam = bms_copy(subplan->allParam);
2691 make_agg(PlannerInfo *root, List *tlist, List *qual,
2692 AggStrategy aggstrategy,
2693 int numGroupCols, AttrNumber *grpColIdx,
2694 long numGroups, int numAggs,
2697 Agg *node = makeNode(Agg);
2698 Plan *plan = &node->plan;
2699 Path agg_path; /* dummy for result of cost_agg */
2702 node->aggstrategy = aggstrategy;
2703 node->numCols = numGroupCols;
2704 node->grpColIdx = grpColIdx;
2705 node->numGroups = numGroups;
2707 copy_plan_costsize(plan, lefttree); /* only care about copying size */
2708 cost_agg(&agg_path, root,
2709 aggstrategy, numAggs,
2710 numGroupCols, numGroups,
2711 lefttree->startup_cost,
2712 lefttree->total_cost,
2713 lefttree->plan_rows);
2714 plan->startup_cost = agg_path.startup_cost;
2715 plan->total_cost = agg_path.total_cost;
2718 * We will produce a single output tuple if not grouping, and a tuple per
2721 if (aggstrategy == AGG_PLAIN)
2722 plan->plan_rows = 1;
2724 plan->plan_rows = numGroups;
2727 * We also need to account for the cost of evaluation of the qual (ie, the
2728 * HAVING clause) and the tlist. Note that cost_qual_eval doesn't charge
2729 * anything for Aggref nodes; this is okay since they are really
2730 * comparable to Vars.
2732 * See notes in grouping_planner about why this routine and make_group are
2733 * the only ones in this file that worry about tlist eval cost.
2737 cost_qual_eval(&qual_cost, qual);
2738 plan->startup_cost += qual_cost.startup;
2739 plan->total_cost += qual_cost.startup;
2740 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2742 cost_qual_eval(&qual_cost, tlist);
2743 plan->startup_cost += qual_cost.startup;
2744 plan->total_cost += qual_cost.startup;
2745 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2748 plan->targetlist = tlist;
2749 plan->lefttree = lefttree;
2750 plan->righttree = NULL;
2756 make_group(PlannerInfo *root,
2760 AttrNumber *grpColIdx,
2764 Group *node = makeNode(Group);
2765 Plan *plan = &node->plan;
2766 Path group_path; /* dummy for result of cost_group */
2769 node->numCols = numGroupCols;
2770 node->grpColIdx = grpColIdx;
2772 copy_plan_costsize(plan, lefttree); /* only care about copying size */
2773 cost_group(&group_path, root,
2774 numGroupCols, numGroups,
2775 lefttree->startup_cost,
2776 lefttree->total_cost,
2777 lefttree->plan_rows);
2778 plan->startup_cost = group_path.startup_cost;
2779 plan->total_cost = group_path.total_cost;
2781 /* One output tuple per estimated result group */
2782 plan->plan_rows = numGroups;
2785 * We also need to account for the cost of evaluation of the qual (ie, the
2786 * HAVING clause) and the tlist.
2788 * XXX this double-counts the cost of evaluation of any expressions used
2789 * for grouping, since in reality those will have been evaluated at a
2790 * lower plan level and will only be copied by the Group node. Worth
2793 * See notes in grouping_planner about why this routine and make_agg are
2794 * the only ones in this file that worry about tlist eval cost.
2798 cost_qual_eval(&qual_cost, qual);
2799 plan->startup_cost += qual_cost.startup;
2800 plan->total_cost += qual_cost.startup;
2801 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2803 cost_qual_eval(&qual_cost, tlist);
2804 plan->startup_cost += qual_cost.startup;
2805 plan->total_cost += qual_cost.startup;
2806 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2809 plan->targetlist = tlist;
2810 plan->lefttree = lefttree;
2811 plan->righttree = NULL;
2817 * distinctList is a list of SortClauses, identifying the targetlist items
2818 * that should be considered by the Unique filter.
2821 make_unique(Plan *lefttree, List *distinctList)
2823 Unique *node = makeNode(Unique);
2824 Plan *plan = &node->plan;
2825 int numCols = list_length(distinctList);
2827 AttrNumber *uniqColIdx;
2830 copy_plan_costsize(plan, lefttree);
2833 * Charge one cpu_operator_cost per comparison per input tuple. We assume
2834 * all columns get compared at most of the tuples. (XXX probably this is
2837 plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols;
2840 * plan->plan_rows is left as a copy of the input subplan's plan_rows; ie,
2841 * we assume the filter removes nothing. The caller must alter this if he
2842 * has a better idea.
2845 plan->targetlist = copyObject(lefttree->targetlist);
2847 plan->lefttree = lefttree;
2848 plan->righttree = NULL;
2851 * convert SortClause list into array of attr indexes, as wanted by exec
2853 Assert(numCols > 0);
2854 uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
2856 foreach(slitem, distinctList)
2858 SortClause *sortcl = (SortClause *) lfirst(slitem);
2859 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
2861 uniqColIdx[keyno++] = tle->resno;
2864 node->numCols = numCols;
2865 node->uniqColIdx = uniqColIdx;
2871 * distinctList is a list of SortClauses, identifying the targetlist items
2872 * that should be considered by the SetOp filter.
2876 make_setop(SetOpCmd cmd, Plan *lefttree,
2877 List *distinctList, AttrNumber flagColIdx)
2879 SetOp *node = makeNode(SetOp);
2880 Plan *plan = &node->plan;
2881 int numCols = list_length(distinctList);
2883 AttrNumber *dupColIdx;
2886 copy_plan_costsize(plan, lefttree);
2889 * Charge one cpu_operator_cost per comparison per input tuple. We assume
2890 * all columns get compared at most of the tuples.
2892 plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols;
2895 * We make the unsupported assumption that there will be 10% as many
2896 * tuples out as in. Any way to do better?
2898 plan->plan_rows *= 0.1;
2899 if (plan->plan_rows < 1)
2900 plan->plan_rows = 1;
2902 plan->targetlist = copyObject(lefttree->targetlist);
2904 plan->lefttree = lefttree;
2905 plan->righttree = NULL;
2908 * convert SortClause list into array of attr indexes, as wanted by exec
2910 Assert(numCols > 0);
2911 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
2913 foreach(slitem, distinctList)
2915 SortClause *sortcl = (SortClause *) lfirst(slitem);
2916 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
2918 dupColIdx[keyno++] = tle->resno;
2922 node->numCols = numCols;
2923 node->dupColIdx = dupColIdx;
2924 node->flagColIdx = flagColIdx;
2930 * Note: offset_est and count_est are passed in to save having to repeat
2931 * work already done to estimate the values of the limitOffset and limitCount
2932 * expressions. Their values are as returned by preprocess_limit (0 means
2933 * "not relevant", -1 means "couldn't estimate"). Keep the code below in sync
2934 * with that function!
2937 make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount,
2938 int64 offset_est, int64 count_est)
2940 Limit *node = makeNode(Limit);
2941 Plan *plan = &node->plan;
2943 copy_plan_costsize(plan, lefttree);
2946 * Adjust the output rows count and costs according to the offset/limit.
2947 * This is only a cosmetic issue if we are at top level, but if we are
2948 * building a subquery then it's important to report correct info to the
2951 * When the offset or count couldn't be estimated, use 10% of the
2952 * estimated number of rows emitted from the subplan.
2954 if (offset_est != 0)
2959 offset_rows = (double) offset_est;
2961 offset_rows = clamp_row_est(lefttree->plan_rows * 0.10);
2962 if (offset_rows > plan->plan_rows)
2963 offset_rows = plan->plan_rows;
2964 if (plan->plan_rows > 0)
2965 plan->startup_cost +=
2966 (plan->total_cost - plan->startup_cost)
2967 * offset_rows / plan->plan_rows;
2968 plan->plan_rows -= offset_rows;
2969 if (plan->plan_rows < 1)
2970 plan->plan_rows = 1;
2978 count_rows = (double) count_est;
2980 count_rows = clamp_row_est(lefttree->plan_rows * 0.10);
2981 if (count_rows > plan->plan_rows)
2982 count_rows = plan->plan_rows;
2983 if (plan->plan_rows > 0)
2984 plan->total_cost = plan->startup_cost +
2985 (plan->total_cost - plan->startup_cost)
2986 * count_rows / plan->plan_rows;
2987 plan->plan_rows = count_rows;
2988 if (plan->plan_rows < 1)
2989 plan->plan_rows = 1;
2992 plan->targetlist = copyObject(lefttree->targetlist);
2994 plan->lefttree = lefttree;
2995 plan->righttree = NULL;
2997 node->limitOffset = limitOffset;
2998 node->limitCount = limitCount;
3005 * Build a Result plan node
3007 * If we have a subplan, assume that any evaluation costs for the gating qual
3008 * were already factored into the subplan's startup cost, and just copy the
3009 * subplan cost. If there's no subplan, we should include the qual eval
3010 * cost. In either case, tlist eval cost is not to be included here.
3013 make_result(List *tlist,
3014 Node *resconstantqual,
3017 Result *node = makeNode(Result);
3018 Plan *plan = &node->plan;
3021 copy_plan_costsize(plan, subplan);
3024 plan->startup_cost = 0;
3025 plan->total_cost = cpu_tuple_cost;
3026 plan->plan_rows = 1; /* wrong if we have a set-valued function? */
3027 plan->plan_width = 0; /* XXX is it worth being smarter? */
3028 if (resconstantqual)
3032 cost_qual_eval(&qual_cost, (List *) resconstantqual);
3033 /* resconstantqual is evaluated once at startup */
3034 plan->startup_cost += qual_cost.startup + qual_cost.per_tuple;
3035 plan->total_cost += qual_cost.startup + qual_cost.per_tuple;
3039 plan->targetlist = tlist;
3041 plan->lefttree = subplan;
3042 plan->righttree = NULL;
3043 node->resconstantqual = resconstantqual;
3049 * is_projection_capable_plan
3050 * Check whether a given Plan node is able to do projection.
3053 is_projection_capable_plan(Plan *plan)
3055 /* Most plan types can project, so just list the ones that can't */
3056 switch (nodeTag(plan))