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-2005, 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.202 2005/10/19 17:31:20 tgl Exp $
15 *-------------------------------------------------------------------------
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.h"
23 #include "optimizer/clauses.h"
24 #include "optimizer/cost.h"
25 #include "optimizer/plancat.h"
26 #include "optimizer/planmain.h"
27 #include "optimizer/predtest.h"
28 #include "optimizer/restrictinfo.h"
29 #include "optimizer/tlist.h"
30 #include "optimizer/var.h"
31 #include "parser/parsetree.h"
32 #include "parser/parse_clause.h"
33 #include "parser/parse_expr.h"
34 #include "utils/lsyscache.h"
35 #include "utils/syscache.h"
38 static Scan *create_scan_plan(PlannerInfo *root, Path *best_path);
39 static List *build_relation_tlist(RelOptInfo *rel);
40 static bool use_physical_tlist(RelOptInfo *rel);
41 static void disuse_physical_tlist(Plan *plan, Path *path);
42 static Join *create_join_plan(PlannerInfo *root, JoinPath *best_path);
43 static Plan *create_append_plan(PlannerInfo *root, AppendPath *best_path);
44 static Result *create_result_plan(PlannerInfo *root, ResultPath *best_path);
45 static Material *create_material_plan(PlannerInfo *root, MaterialPath *best_path);
46 static Plan *create_unique_plan(PlannerInfo *root, UniquePath *best_path);
47 static SeqScan *create_seqscan_plan(PlannerInfo *root, Path *best_path,
48 List *tlist, List *scan_clauses);
49 static IndexScan *create_indexscan_plan(PlannerInfo *root, IndexPath *best_path,
50 List *tlist, List *scan_clauses,
51 List **nonlossy_clauses);
52 static BitmapHeapScan *create_bitmap_scan_plan(PlannerInfo *root,
53 BitmapHeapPath *best_path,
54 List *tlist, List *scan_clauses);
55 static Plan *create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
56 List **qual, List **indexqual);
57 static TidScan *create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
58 List *tlist, List *scan_clauses);
59 static SubqueryScan *create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
60 List *tlist, List *scan_clauses);
61 static FunctionScan *create_functionscan_plan(PlannerInfo *root, Path *best_path,
62 List *tlist, List *scan_clauses);
63 static NestLoop *create_nestloop_plan(PlannerInfo *root, NestPath *best_path,
64 Plan *outer_plan, Plan *inner_plan);
65 static MergeJoin *create_mergejoin_plan(PlannerInfo *root, MergePath *best_path,
66 Plan *outer_plan, Plan *inner_plan);
67 static HashJoin *create_hashjoin_plan(PlannerInfo *root, HashPath *best_path,
68 Plan *outer_plan, Plan *inner_plan);
69 static void fix_indexqual_references(List *indexquals, IndexPath *index_path,
70 List **fixed_indexquals,
71 List **nonlossy_indexquals,
74 static Node *fix_indexqual_operand(Node *node, IndexOptInfo *index,
76 static List *get_switched_clauses(List *clauses, Relids outerrelids);
77 static void copy_path_costsize(Plan *dest, Path *src);
78 static void copy_plan_costsize(Plan *dest, Plan *src);
79 static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
80 static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
81 Oid indexid, List *indexqual, List *indexqualorig,
82 List *indexstrategy, List *indexsubtype,
83 ScanDirection indexscandir);
84 static BitmapIndexScan *make_bitmap_indexscan(Index scanrelid, Oid indexid,
89 static BitmapHeapScan *make_bitmap_heapscan(List *qptlist,
94 static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
96 static FunctionScan *make_functionscan(List *qptlist, List *qpqual,
98 static BitmapAnd *make_bitmap_and(List *bitmapplans);
99 static BitmapOr *make_bitmap_or(List *bitmapplans);
100 static NestLoop *make_nestloop(List *tlist,
101 List *joinclauses, List *otherclauses,
102 Plan *lefttree, Plan *righttree,
104 static HashJoin *make_hashjoin(List *tlist,
105 List *joinclauses, List *otherclauses,
107 Plan *lefttree, Plan *righttree,
109 static Hash *make_hash(Plan *lefttree);
110 static MergeJoin *make_mergejoin(List *tlist,
111 List *joinclauses, List *otherclauses,
113 Plan *lefttree, Plan *righttree,
115 static Sort *make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
116 AttrNumber *sortColIdx, Oid *sortOperators);
117 static Sort *make_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree,
123 * Creates the access plan for a query by tracing backwards through the
124 * desired chain of pathnodes, starting at the node 'best_path'. For
125 * every pathnode found:
126 * (1) Create a corresponding plan node containing appropriate id,
127 * target list, and qualification information.
128 * (2) Modify qual clauses of join nodes so that subplan attributes are
129 * referenced using relative values.
130 * (3) Target lists are not modified, but will be in setrefs.c.
132 * best_path is the best access path
134 * Returns a Plan tree.
137 create_plan(PlannerInfo *root, Path *best_path)
141 switch (best_path->pathtype)
145 case T_BitmapHeapScan:
149 plan = (Plan *) create_scan_plan(root, best_path);
154 plan = (Plan *) create_join_plan(root,
155 (JoinPath *) best_path);
158 plan = (Plan *) create_append_plan(root,
159 (AppendPath *) best_path);
162 plan = (Plan *) create_result_plan(root,
163 (ResultPath *) best_path);
166 plan = (Plan *) create_material_plan(root,
167 (MaterialPath *) best_path);
170 plan = (Plan *) create_unique_plan(root,
171 (UniquePath *) best_path);
174 elog(ERROR, "unrecognized node type: %d",
175 (int) best_path->pathtype);
176 plan = NULL; /* keep compiler quiet */
185 * Create a scan plan for the parent relation of 'best_path'.
187 * Returns a Plan node.
190 create_scan_plan(PlannerInfo *root, Path *best_path)
192 RelOptInfo *rel = best_path->parent;
198 * For table scans, rather than using the relation targetlist (which is
199 * only those Vars actually needed by the query), we prefer to generate a
200 * tlist containing all Vars in order. This will allow the executor to
201 * optimize away projection of the table tuples, if possible. (Note that
202 * planner.c may replace the tlist we generate here, forcing projection to
205 if (use_physical_tlist(rel))
207 tlist = build_physical_tlist(root, rel);
208 /* if fail because of dropped cols, use regular method */
210 tlist = build_relation_tlist(rel);
213 tlist = build_relation_tlist(rel);
216 * Extract the relevant restriction clauses from the parent relation; the
217 * executor must apply all these restrictions during the scan.
219 scan_clauses = rel->baserestrictinfo;
221 switch (best_path->pathtype)
224 plan = (Scan *) create_seqscan_plan(root,
231 plan = (Scan *) create_indexscan_plan(root,
232 (IndexPath *) best_path,
238 case T_BitmapHeapScan:
239 plan = (Scan *) create_bitmap_scan_plan(root,
240 (BitmapHeapPath *) best_path,
246 plan = (Scan *) create_tidscan_plan(root,
247 (TidPath *) best_path,
253 plan = (Scan *) create_subqueryscan_plan(root,
260 plan = (Scan *) create_functionscan_plan(root,
267 elog(ERROR, "unrecognized node type: %d",
268 (int) best_path->pathtype);
269 plan = NULL; /* keep compiler quiet */
277 * Build a target list (ie, a list of TargetEntry) for a relation.
280 build_relation_tlist(RelOptInfo *rel)
286 foreach(v, rel->reltargetlist)
288 /* Do we really need to copy here? Not sure */
289 Var *var = (Var *) copyObject(lfirst(v));
291 tlist = lappend(tlist, makeTargetEntry((Expr *) var,
302 * Decide whether to use a tlist matching relation structure,
303 * rather than only those Vars actually referenced.
306 use_physical_tlist(RelOptInfo *rel)
311 * We can do this for real relation scans, subquery scans, and function
312 * scans (but not for, eg, joins).
314 if (rel->rtekind != RTE_RELATION &&
315 rel->rtekind != RTE_SUBQUERY &&
316 rel->rtekind != RTE_FUNCTION)
320 * Can't do it with inheritance cases either (mainly because Append
323 if (rel->reloptkind != RELOPT_BASEREL)
327 * Can't do it if any system columns or whole-row Vars are requested,
328 * either. (This could possibly be fixed but would take some fragile
329 * assumptions in setrefs.c, I think.)
331 for (i = rel->min_attr; i <= 0; i++)
333 if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
341 * disuse_physical_tlist
342 * Switch a plan node back to emitting only Vars actually referenced.
344 * If the plan node immediately above a scan would prefer to get only
345 * needed Vars and not a physical tlist, it must call this routine to
346 * undo the decision made by use_physical_tlist(). Currently, Hash, Sort,
347 * and Material nodes want this, so they don't have to store useless columns.
350 disuse_physical_tlist(Plan *plan, Path *path)
352 /* Only need to undo it for path types handled by create_scan_plan() */
353 switch (path->pathtype)
357 case T_BitmapHeapScan:
361 plan->targetlist = build_relation_tlist(path->parent);
370 * Create a join plan for 'best_path' and (recursively) plans for its
371 * inner and outer paths.
373 * Returns a Plan node.
376 create_join_plan(PlannerInfo *root, JoinPath *best_path)
382 outer_plan = create_plan(root, best_path->outerjoinpath);
383 inner_plan = create_plan(root, best_path->innerjoinpath);
385 switch (best_path->path.pathtype)
388 plan = (Join *) create_mergejoin_plan(root,
389 (MergePath *) best_path,
394 plan = (Join *) create_hashjoin_plan(root,
395 (HashPath *) best_path,
400 plan = (Join *) create_nestloop_plan(root,
401 (NestPath *) best_path,
406 elog(ERROR, "unrecognized node type: %d",
407 (int) best_path->path.pathtype);
408 plan = NULL; /* keep compiler quiet */
415 * * Expensive function pullups may have pulled local predicates * into
416 * this path node. Put them in the qpqual of the plan node. * JMH,
419 if (get_loc_restrictinfo(best_path) != NIL)
420 set_qpqual((Plan) plan,
421 list_concat(get_qpqual((Plan) plan),
422 get_actual_clauses(get_loc_restrictinfo(best_path))));
430 * Create an Append plan for 'best_path' and (recursively) plans
433 * Returns a Plan node.
436 create_append_plan(PlannerInfo *root, AppendPath *best_path)
439 List *tlist = build_relation_tlist(best_path->path.parent);
440 List *subplans = NIL;
444 * It is possible for the subplans list to contain only one entry, or even
445 * no entries. Handle these cases specially.
447 * XXX ideally, if there's just one entry, we'd not bother to generate an
448 * Append node but just return the single child. At the moment this does
449 * not work because the varno of the child scan plan won't match the
450 * parent-rel Vars it'll be asked to emit.
452 if (best_path->subpaths == NIL)
454 /* Generate a Result plan with constant-FALSE gating qual */
455 return (Plan *) make_result(tlist,
456 (Node *) list_make1(makeBoolConst(false,
461 /* Normal case with multiple subpaths */
462 foreach(subpaths, best_path->subpaths)
464 Path *subpath = (Path *) lfirst(subpaths);
466 subplans = lappend(subplans, create_plan(root, subpath));
469 plan = make_append(subplans, false, tlist);
471 return (Plan *) plan;
476 * Create a Result plan for 'best_path' and (recursively) plans
479 * Returns a Plan node.
482 create_result_plan(PlannerInfo *root, ResultPath *best_path)
489 if (best_path->path.parent)
490 tlist = build_relation_tlist(best_path->path.parent);
492 tlist = NIL; /* will be filled in later */
494 if (best_path->subpath)
495 subplan = create_plan(root, best_path->subpath);
499 constclauses = order_qual_clauses(root, best_path->constantqual);
501 plan = make_result(tlist, (Node *) constclauses, subplan);
507 * create_material_plan
508 * Create a Material plan for 'best_path' and (recursively) plans
511 * Returns a Plan node.
514 create_material_plan(PlannerInfo *root, MaterialPath *best_path)
519 subplan = create_plan(root, best_path->subpath);
521 /* We don't want any excess columns in the materialized tuples */
522 disuse_physical_tlist(subplan, best_path->subpath);
524 plan = make_material(subplan);
526 copy_path_costsize(&plan->plan, (Path *) best_path);
533 * Create a Unique plan for 'best_path' and (recursively) plans
536 * Returns a Plan node.
539 create_unique_plan(PlannerInfo *root, UniquePath *best_path)
548 AttrNumber *groupColIdx;
552 subplan = create_plan(root, best_path->subpath);
554 /* Done if we don't need to do any actual unique-ifying */
555 if (best_path->umethod == UNIQUE_PATH_NOOP)
559 * As constructed, the subplan has a "flat" tlist containing just the
560 * Vars needed here and at upper levels. The values we are supposed
561 * to unique-ify may be expressions in these variables. We have to
562 * add any such expressions to the subplan's tlist.
564 * The subplan may have a "physical" tlist if it is a simple scan plan.
565 * This should be left as-is if we don't need to add any expressions;
566 * but if we do have to add expressions, then a projection step will be
567 * needed at runtime anyway, and so we may as well remove unneeded items.
568 * Therefore newtlist starts from build_relation_tlist() not just a
569 * copy of the subplan's tlist; and we don't install it into the subplan
570 * unless stuff has to be added.
572 * To find the correct list of values to unique-ify, we look in the
573 * information saved for IN expressions. If this code is ever used in
574 * other scenarios, some other way of finding what to unique-ify will
578 uniq_exprs = NIL; /* just to keep compiler quiet */
579 foreach(l, root->in_info_list)
581 InClauseInfo *ininfo = (InClauseInfo *) lfirst(l);
583 if (bms_equal(ininfo->righthand, best_path->path.parent->relids))
585 uniq_exprs = ininfo->sub_targetlist;
589 if (l == NULL) /* fell out of loop? */
590 elog(ERROR, "could not find UniquePath in in_info_list");
592 /* initialize modified subplan tlist as just the "required" vars */
593 newtlist = build_relation_tlist(best_path->path.parent);
594 nextresno = list_length(newtlist) + 1;
597 foreach(l, uniq_exprs)
599 Node *uniqexpr = lfirst(l);
602 tle = tlist_member(uniqexpr, newtlist);
605 tle = makeTargetEntry((Expr *) uniqexpr,
609 newtlist = lappend(newtlist, tle);
618 * If the top plan node can't do projections, we need to add a Result
619 * node to help it along.
621 if (!is_projection_capable_plan(subplan))
622 subplan = (Plan *) make_result(newtlist, NULL, subplan);
624 subplan->targetlist = newtlist;
628 * Build control information showing which subplan output columns are to
629 * be examined by the grouping step. Unfortunately we can't merge this
630 * with the previous loop, since we didn't then know which version of the
631 * subplan tlist we'd end up using.
633 newtlist = subplan->targetlist;
634 numGroupCols = list_length(uniq_exprs);
635 groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber));
638 foreach(l, uniq_exprs)
640 Node *uniqexpr = lfirst(l);
643 tle = tlist_member(uniqexpr, newtlist);
644 if (!tle) /* shouldn't happen */
645 elog(ERROR, "failed to find unique expression in subplan tlist");
646 groupColIdx[groupColPos++] = tle->resno;
649 if (best_path->umethod == UNIQUE_PATH_HASH)
653 numGroups = (long) Min(best_path->rows, (double) LONG_MAX);
656 * Since the Agg node is going to project anyway, we can give it the
657 * minimum output tlist, without any stuff we might have added to the
660 plan = (Plan *) make_agg(root,
661 build_relation_tlist(best_path->path.parent),
672 List *sortList = NIL;
674 for (groupColPos = 0; groupColPos < numGroupCols; groupColPos++)
678 tle = get_tle_by_resno(subplan->targetlist,
679 groupColIdx[groupColPos]);
681 sortList = addTargetToSortList(NULL, tle,
682 sortList, subplan->targetlist,
683 SORTBY_ASC, NIL, false);
685 plan = (Plan *) make_sort_from_sortclauses(root, sortList, subplan);
686 plan = (Plan *) make_unique(plan, sortList);
689 /* Adjust output size estimate (other fields should be OK already) */
690 plan->plan_rows = best_path->rows;
696 /*****************************************************************************
698 * BASE-RELATION SCAN METHODS
700 *****************************************************************************/
704 * create_seqscan_plan
705 * Returns a seqscan plan for the base relation scanned by 'best_path'
706 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
709 create_seqscan_plan(PlannerInfo *root, Path *best_path,
710 List *tlist, List *scan_clauses)
713 Index scan_relid = best_path->parent->relid;
715 /* it should be a base rel... */
716 Assert(scan_relid > 0);
717 Assert(best_path->parent->rtekind == RTE_RELATION);
719 /* Reduce RestrictInfo list to bare expressions */
720 scan_clauses = get_actual_clauses(scan_clauses);
722 /* Sort clauses into best execution order */
723 scan_clauses = order_qual_clauses(root, scan_clauses);
725 scan_plan = make_seqscan(tlist,
729 copy_path_costsize(&scan_plan->plan, best_path);
735 * create_indexscan_plan
736 * Returns an indexscan plan for the base relation scanned by 'best_path'
737 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
739 * The indexquals list of the path contains implicitly-ANDed qual conditions.
740 * The list can be empty --- then no index restrictions will be applied during
743 * If nonlossy_clauses isn't NULL, *nonlossy_clauses receives a list of the
744 * nonlossy indexquals.
747 create_indexscan_plan(PlannerInfo *root,
748 IndexPath *best_path,
751 List **nonlossy_clauses)
753 List *indexquals = best_path->indexquals;
754 Index baserelid = best_path->path.parent->relid;
755 Oid indexoid = best_path->indexinfo->indexoid;
757 List *stripped_indexquals;
758 List *fixed_indexquals;
759 List *nonlossy_indexquals;
763 IndexScan *scan_plan;
765 /* it should be a base rel... */
766 Assert(baserelid > 0);
767 Assert(best_path->path.parent->rtekind == RTE_RELATION);
770 * Build "stripped" indexquals structure (no RestrictInfos) to pass to
771 * executor as indexqualorig
773 stripped_indexquals = get_actual_clauses(indexquals);
776 * The executor needs a copy with the indexkey on the left of each clause
777 * and with index attr numbers substituted for table ones. This pass also
778 * gets strategy info and looks for "lossy" operators.
780 fix_indexqual_references(indexquals, best_path,
782 &nonlossy_indexquals,
786 /* pass back nonlossy quals if caller wants 'em */
787 if (nonlossy_clauses)
788 *nonlossy_clauses = nonlossy_indexquals;
791 * If this is an innerjoin scan, the indexclauses will contain join
792 * clauses that are not present in scan_clauses (since the passed-in value
793 * is just the rel's baserestrictinfo list). We must add these clauses to
794 * scan_clauses to ensure they get checked. In most cases we will remove
795 * the join clauses again below, but if a join clause contains a special
796 * operator, we need to make sure it gets into the scan_clauses.
798 * Note: pointer comparison should be enough to determine RestrictInfo
801 if (best_path->isjoininner)
802 scan_clauses = list_union_ptr(scan_clauses, best_path->indexclauses);
805 * The qpqual list must contain all restrictions not automatically handled
806 * by the index. All the predicates in the indexquals will be checked
807 * (either by the index itself, or by nodeIndexscan.c), but if there are
808 * any "special" operators involved then they must be included in qpqual.
809 * Also, any lossy index operators must be rechecked in the qpqual. The
810 * upshot is that qpqual must contain scan_clauses minus whatever appears
811 * in nonlossy_indexquals.
813 * In normal cases simple pointer equality checks will be enough to spot
814 * duplicate RestrictInfos, so we try that first. In some situations
815 * (particularly with OR'd index conditions) we may have scan_clauses that
816 * are not equal to, but are logically implied by, the index quals; so we
817 * also try a predicate_implied_by() check to see if we can discard quals
818 * that way. (predicate_implied_by assumes its first input contains only
819 * immutable functions, so we have to check that.) We can also discard
820 * quals that are implied by a partial index's predicate.
822 * While at it, we strip off the RestrictInfos to produce a list of plain
826 foreach(l, scan_clauses)
828 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
830 Assert(IsA(rinfo, RestrictInfo));
831 if (list_member_ptr(nonlossy_indexquals, rinfo))
833 if (!contain_mutable_functions((Node *) rinfo->clause))
835 List *clausel = list_make1(rinfo->clause);
837 if (predicate_implied_by(clausel, nonlossy_indexquals))
839 if (predicate_implied_by(clausel, best_path->indexinfo->indpred))
842 qpqual = lappend(qpqual, rinfo->clause);
845 /* Sort clauses into best execution order */
846 qpqual = order_qual_clauses(root, qpqual);
848 /* Finally ready to build the plan node */
849 scan_plan = make_indexscan(tlist,
857 best_path->indexscandir);
859 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
860 /* use the indexscan-specific rows estimate, not the parent rel's */
861 scan_plan->scan.plan.plan_rows = best_path->rows;
867 * create_bitmap_scan_plan
868 * Returns a bitmap scan plan for the base relation scanned by 'best_path'
869 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
871 static BitmapHeapScan *
872 create_bitmap_scan_plan(PlannerInfo *root,
873 BitmapHeapPath *best_path,
877 Index baserelid = best_path->path.parent->relid;
878 Plan *bitmapqualplan;
879 List *bitmapqualorig;
883 BitmapHeapScan *scan_plan;
885 /* it should be a base rel... */
886 Assert(baserelid > 0);
887 Assert(best_path->path.parent->rtekind == RTE_RELATION);
889 /* Process the bitmapqual tree into a Plan tree and qual lists */
890 bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
891 &bitmapqualorig, &indexquals);
893 /* Reduce RestrictInfo list to bare expressions */
894 scan_clauses = get_actual_clauses(scan_clauses);
897 * If this is a innerjoin scan, the indexclauses will contain join clauses
898 * that are not present in scan_clauses (since the passed-in value is just
899 * the rel's baserestrictinfo list). We must add these clauses to
900 * scan_clauses to ensure they get checked. In most cases we will remove
901 * the join clauses again below, but if a join clause contains a special
902 * operator, we need to make sure it gets into the scan_clauses.
904 if (best_path->isjoininner)
906 scan_clauses = list_concat_unique(scan_clauses, bitmapqualorig);
910 * The qpqual list must contain all restrictions not automatically handled
911 * by the index. All the predicates in the indexquals will be checked
912 * (either by the index itself, or by nodeBitmapHeapscan.c), but if there
913 * are any "special" or lossy operators involved then they must be added
914 * to qpqual. The upshot is that qpquals must contain scan_clauses minus
915 * whatever appears in indexquals.
917 * In normal cases simple equal() checks will be enough to spot duplicate
918 * clauses, so we try that first. In some situations (particularly with
919 * OR'd index conditions) we may have scan_clauses that are not equal to,
920 * but are logically implied by, the index quals; so we also try a
921 * predicate_implied_by() check to see if we can discard quals that way.
922 * (predicate_implied_by assumes its first input contains only immutable
923 * functions, so we have to check that.) We can also discard quals that
924 * are implied by a partial index's predicate.
926 * XXX For the moment, we only consider partial index predicates in the
927 * simple single-index-scan case. Is it worth trying to be smart about
928 * more complex cases? Perhaps create_bitmap_subplan should be made to
929 * include predicate info in what it constructs.
932 foreach(l, scan_clauses)
934 Node *clause = (Node *) lfirst(l);
936 if (list_member(indexquals, clause))
938 if (!contain_mutable_functions(clause))
940 List *clausel = list_make1(clause);
942 if (predicate_implied_by(clausel, indexquals))
944 if (IsA(best_path->bitmapqual, IndexPath))
946 IndexPath *ipath = (IndexPath *) best_path->bitmapqual;
948 if (predicate_implied_by(clausel, ipath->indexinfo->indpred))
952 qpqual = lappend(qpqual, clause);
955 /* Sort clauses into best execution order */
956 qpqual = order_qual_clauses(root, qpqual);
959 * When dealing with special or lossy operators, we will at this point
960 * have duplicate clauses in qpqual and bitmapqualorig. We may as well
961 * drop 'em from bitmapqualorig, since there's no point in making the
964 bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
966 /* Finally ready to build the plan node */
967 scan_plan = make_bitmap_heapscan(tlist,
973 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
974 /* use the indexscan-specific rows estimate, not the parent rel's */
975 scan_plan->scan.plan.plan_rows = best_path->rows;
981 * Given a bitmapqual tree, generate the Plan tree that implements it
983 * As byproducts, we also return in *qual and *indexqual the qual lists
984 * (in implicit-AND form, without RestrictInfos) describing the original index
985 * conditions and the generated indexqual conditions. The latter is made to
986 * exclude lossy index operators.
988 * Note: if you find yourself changing this, you probably need to change
989 * make_restrictinfo_from_bitmapqual too.
992 create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
993 List **qual, List **indexqual)
997 if (IsA(bitmapqual, BitmapAndPath))
999 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
1000 List *subplans = NIL;
1001 List *subquals = NIL;
1002 List *subindexquals = NIL;
1006 * There may well be redundant quals among the subplans, since a
1007 * top-level WHERE qual might have gotten used to form several
1008 * different index quals. We don't try exceedingly hard to eliminate
1009 * redundancies, but we do eliminate obvious duplicates by using
1010 * list_concat_unique.
1012 foreach(l, apath->bitmapquals)
1018 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1019 &subqual, &subindexqual);
1020 subplans = lappend(subplans, subplan);
1021 subquals = list_concat_unique(subquals, subqual);
1022 subindexquals = list_concat_unique(subindexquals, subindexqual);
1024 plan = (Plan *) make_bitmap_and(subplans);
1025 plan->startup_cost = apath->path.startup_cost;
1026 plan->total_cost = apath->path.total_cost;
1028 clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
1029 plan->plan_width = 0; /* meaningless */
1031 *indexqual = subindexquals;
1033 else if (IsA(bitmapqual, BitmapOrPath))
1035 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
1036 List *subplans = NIL;
1037 List *subquals = NIL;
1038 List *subindexquals = NIL;
1039 bool const_true_subqual = false;
1040 bool const_true_subindexqual = false;
1044 * Here, we only detect qual-free subplans. A qual-free subplan would
1045 * cause us to generate "... OR true ..." which we may as well reduce
1046 * to just "true". We do not try to eliminate redundant subclauses
1047 * because (a) it's not as likely as in the AND case, and (b) we might
1048 * well be working with hundreds or even thousands of OR conditions,
1049 * perhaps from a long IN list. The performance of list_append_unique
1050 * would be unacceptable.
1052 foreach(l, opath->bitmapquals)
1058 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1059 &subqual, &subindexqual);
1060 subplans = lappend(subplans, subplan);
1062 const_true_subqual = true;
1063 else if (!const_true_subqual)
1064 subquals = lappend(subquals,
1065 make_ands_explicit(subqual));
1066 if (subindexqual == NIL)
1067 const_true_subindexqual = true;
1068 else if (!const_true_subindexqual)
1069 subindexquals = lappend(subindexquals,
1070 make_ands_explicit(subindexqual));
1072 plan = (Plan *) make_bitmap_or(subplans);
1073 plan->startup_cost = opath->path.startup_cost;
1074 plan->total_cost = opath->path.total_cost;
1076 clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
1077 plan->plan_width = 0; /* meaningless */
1080 * If there were constant-TRUE subquals, the OR reduces to constant
1081 * TRUE. Also, avoid generating one-element ORs, which could happen
1082 * due to redundancy elimination.
1084 if (const_true_subqual)
1086 else if (list_length(subquals) <= 1)
1089 *qual = list_make1(make_orclause(subquals));
1090 if (const_true_subindexqual)
1092 else if (list_length(subindexquals) <= 1)
1093 *indexqual = subindexquals;
1095 *indexqual = list_make1(make_orclause(subindexquals));
1097 else if (IsA(bitmapqual, IndexPath))
1099 IndexPath *ipath = (IndexPath *) bitmapqual;
1101 List *nonlossy_clauses;
1103 /* Use the regular indexscan plan build machinery... */
1104 iscan = create_indexscan_plan(root, ipath, NIL, NIL,
1106 /* then convert to a bitmap indexscan */
1107 plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
1110 iscan->indexqualorig,
1111 iscan->indexstrategy,
1112 iscan->indexsubtype);
1113 plan->startup_cost = 0.0;
1114 plan->total_cost = ipath->indextotalcost;
1116 clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
1117 plan->plan_width = 0; /* meaningless */
1118 *qual = get_actual_clauses(ipath->indexclauses);
1119 *indexqual = get_actual_clauses(nonlossy_clauses);
1123 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
1124 plan = NULL; /* keep compiler quiet */
1131 * create_tidscan_plan
1132 * Returns a tidscan plan for the base relation scanned by 'best_path'
1133 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1136 create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
1137 List *tlist, List *scan_clauses)
1140 Index scan_relid = best_path->path.parent->relid;
1142 /* it should be a base rel... */
1143 Assert(scan_relid > 0);
1144 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1146 /* Reduce RestrictInfo list to bare expressions */
1147 scan_clauses = get_actual_clauses(scan_clauses);
1149 /* Sort clauses into best execution order */
1150 scan_clauses = order_qual_clauses(root, scan_clauses);
1152 scan_plan = make_tidscan(tlist,
1155 best_path->tideval);
1157 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
1163 * create_subqueryscan_plan
1164 * Returns a subqueryscan plan for the base relation scanned by 'best_path'
1165 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1167 static SubqueryScan *
1168 create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
1169 List *tlist, List *scan_clauses)
1171 SubqueryScan *scan_plan;
1172 Index scan_relid = best_path->parent->relid;
1174 /* it should be a subquery base rel... */
1175 Assert(scan_relid > 0);
1176 Assert(best_path->parent->rtekind == RTE_SUBQUERY);
1178 /* Reduce RestrictInfo list to bare expressions */
1179 scan_clauses = get_actual_clauses(scan_clauses);
1181 /* Sort clauses into best execution order */
1182 scan_clauses = order_qual_clauses(root, scan_clauses);
1184 scan_plan = make_subqueryscan(tlist,
1187 best_path->parent->subplan);
1189 copy_path_costsize(&scan_plan->scan.plan, best_path);
1195 * create_functionscan_plan
1196 * Returns a functionscan plan for the base relation scanned by 'best_path'
1197 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1199 static FunctionScan *
1200 create_functionscan_plan(PlannerInfo *root, Path *best_path,
1201 List *tlist, List *scan_clauses)
1203 FunctionScan *scan_plan;
1204 Index scan_relid = best_path->parent->relid;
1206 /* it should be a function base rel... */
1207 Assert(scan_relid > 0);
1208 Assert(best_path->parent->rtekind == RTE_FUNCTION);
1210 /* Reduce RestrictInfo list to bare expressions */
1211 scan_clauses = get_actual_clauses(scan_clauses);
1213 /* Sort clauses into best execution order */
1214 scan_clauses = order_qual_clauses(root, scan_clauses);
1216 scan_plan = make_functionscan(tlist, scan_clauses, scan_relid);
1218 copy_path_costsize(&scan_plan->scan.plan, best_path);
1223 /*****************************************************************************
1227 *****************************************************************************/
1230 create_nestloop_plan(PlannerInfo *root,
1231 NestPath *best_path,
1235 List *tlist = build_relation_tlist(best_path->path.parent);
1236 List *joinrestrictclauses = best_path->joinrestrictinfo;
1239 NestLoop *join_plan;
1241 if (IsA(best_path->innerjoinpath, IndexPath))
1244 * An index is being used to reduce the number of tuples scanned in
1245 * the inner relation. If there are join clauses being used with the
1246 * index, we may remove those join clauses from the list of clauses
1247 * that have to be checked as qpquals at the join node.
1249 * We can also remove any join clauses that are redundant with those
1250 * being used in the index scan; prior redundancy checks will not have
1251 * caught this case because the join clauses would never have been put
1252 * in the same joininfo list.
1254 * We can skip this if the index path is an ordinary indexpath and not a
1255 * special innerjoin path.
1257 IndexPath *innerpath = (IndexPath *) best_path->innerjoinpath;
1259 if (innerpath->isjoininner)
1261 joinrestrictclauses =
1262 select_nonredundant_join_clauses(root,
1263 joinrestrictclauses,
1264 innerpath->indexclauses,
1265 IS_OUTER_JOIN(best_path->jointype));
1268 else if (IsA(best_path->innerjoinpath, BitmapHeapPath))
1271 * Same deal for bitmapped index scans.
1273 * Note: both here and above, we ignore any implicit index restrictions
1274 * associated with the use of partial indexes. This is OK because
1275 * we're only trying to prove we can dispense with some join quals;
1276 * failing to prove that doesn't result in an incorrect plan. It is
1277 * the right way to proceed because adding more quals to the stuff we
1278 * got from the original query would just make it harder to detect
1281 BitmapHeapPath *innerpath = (BitmapHeapPath *) best_path->innerjoinpath;
1283 if (innerpath->isjoininner)
1285 List *bitmapclauses;
1288 make_restrictinfo_from_bitmapqual(innerpath->bitmapqual,
1291 joinrestrictclauses =
1292 select_nonredundant_join_clauses(root,
1293 joinrestrictclauses,
1295 IS_OUTER_JOIN(best_path->jointype));
1299 /* Get the join qual clauses (in plain expression form) */
1300 if (IS_OUTER_JOIN(best_path->jointype))
1302 get_actual_join_clauses(joinrestrictclauses,
1303 &joinclauses, &otherclauses);
1307 /* We can treat all clauses alike for an inner join */
1308 joinclauses = get_actual_clauses(joinrestrictclauses);
1312 /* Sort clauses into best execution order */
1313 joinclauses = order_qual_clauses(root, joinclauses);
1314 otherclauses = order_qual_clauses(root, otherclauses);
1316 join_plan = make_nestloop(tlist,
1321 best_path->jointype);
1323 copy_path_costsize(&join_plan->join.plan, &best_path->path);
1329 create_mergejoin_plan(PlannerInfo *root,
1330 MergePath *best_path,
1334 List *tlist = build_relation_tlist(best_path->jpath.path.parent);
1338 MergeJoin *join_plan;
1340 /* Get the join qual clauses (in plain expression form) */
1341 if (IS_OUTER_JOIN(best_path->jpath.jointype))
1343 get_actual_join_clauses(best_path->jpath.joinrestrictinfo,
1344 &joinclauses, &otherclauses);
1348 /* We can treat all clauses alike for an inner join */
1349 joinclauses = get_actual_clauses(best_path->jpath.joinrestrictinfo);
1354 * Remove the mergeclauses from the list of join qual clauses, leaving the
1355 * list of quals that must be checked as qpquals.
1357 mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
1358 joinclauses = list_difference(joinclauses, mergeclauses);
1361 * Rearrange mergeclauses, if needed, so that the outer variable is always
1364 mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
1365 best_path->jpath.outerjoinpath->parent->relids);
1367 /* Sort clauses into best execution order */
1368 /* NB: do NOT reorder the mergeclauses */
1369 joinclauses = order_qual_clauses(root, joinclauses);
1370 otherclauses = order_qual_clauses(root, otherclauses);
1373 * Create explicit sort nodes for the outer and inner join paths if
1374 * necessary. The sort cost was already accounted for in the path. Make
1375 * sure there are no excess columns in the inputs if sorting.
1377 if (best_path->outersortkeys)
1379 disuse_physical_tlist(outer_plan, best_path->jpath.outerjoinpath);
1380 outer_plan = (Plan *)
1381 make_sort_from_pathkeys(root,
1383 best_path->outersortkeys);
1386 if (best_path->innersortkeys)
1388 disuse_physical_tlist(inner_plan, best_path->jpath.innerjoinpath);
1389 inner_plan = (Plan *)
1390 make_sort_from_pathkeys(root,
1392 best_path->innersortkeys);
1396 * Now we can build the mergejoin node.
1398 join_plan = make_mergejoin(tlist,
1404 best_path->jpath.jointype);
1406 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
1412 create_hashjoin_plan(PlannerInfo *root,
1413 HashPath *best_path,
1417 List *tlist = build_relation_tlist(best_path->jpath.path.parent);
1421 HashJoin *join_plan;
1424 /* Get the join qual clauses (in plain expression form) */
1425 if (IS_OUTER_JOIN(best_path->jpath.jointype))
1427 get_actual_join_clauses(best_path->jpath.joinrestrictinfo,
1428 &joinclauses, &otherclauses);
1432 /* We can treat all clauses alike for an inner join */
1433 joinclauses = get_actual_clauses(best_path->jpath.joinrestrictinfo);
1438 * Remove the hashclauses from the list of join qual clauses, leaving the
1439 * list of quals that must be checked as qpquals.
1441 hashclauses = get_actual_clauses(best_path->path_hashclauses);
1442 joinclauses = list_difference(joinclauses, hashclauses);
1445 * Rearrange hashclauses, if needed, so that the outer variable is always
1448 hashclauses = get_switched_clauses(best_path->path_hashclauses,
1449 best_path->jpath.outerjoinpath->parent->relids);
1451 /* Sort clauses into best execution order */
1452 joinclauses = order_qual_clauses(root, joinclauses);
1453 otherclauses = order_qual_clauses(root, otherclauses);
1454 hashclauses = order_qual_clauses(root, hashclauses);
1456 /* We don't want any excess columns in the hashed tuples */
1457 disuse_physical_tlist(inner_plan, best_path->jpath.innerjoinpath);
1460 * Build the hash node and hash join node.
1462 hash_plan = make_hash(inner_plan);
1463 join_plan = make_hashjoin(tlist,
1469 best_path->jpath.jointype);
1471 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
1477 /*****************************************************************************
1479 * SUPPORTING ROUTINES
1481 *****************************************************************************/
1484 * fix_indexqual_references
1485 * Adjust indexqual clauses to the form the executor's indexqual
1486 * machinery needs, and check for recheckable (lossy) index conditions.
1488 * We have five tasks here:
1489 * * Remove RestrictInfo nodes from the input clauses.
1490 * * Index keys must be represented by Var nodes with varattno set to the
1491 * index's attribute number, not the attribute number in the original rel.
1492 * * If the index key is on the right, commute the clause to put it on the
1494 * * We must construct lists of operator strategy numbers and subtypes
1495 * for the top-level operators of each index clause.
1496 * * We must detect any lossy index operators. The API is that we return
1497 * a list of the input clauses whose operators are NOT lossy.
1499 * fixed_indexquals receives a modified copy of the indexquals list --- the
1500 * original is not changed. Note also that the copy shares no substructure
1501 * with the original; this is needed in case there is a subplan in it (we need
1502 * two separate copies of the subplan tree, or things will go awry).
1504 * nonlossy_indexquals receives a list of the original input clauses (with
1505 * RestrictInfos) that contain non-lossy operators.
1507 * indexstrategy receives an integer list of strategy numbers.
1508 * indexsubtype receives an OID list of strategy subtypes.
1511 fix_indexqual_references(List *indexquals, IndexPath *index_path,
1512 List **fixed_indexquals,
1513 List **nonlossy_indexquals,
1514 List **indexstrategy,
1515 List **indexsubtype)
1517 IndexOptInfo *index = index_path->indexinfo;
1520 *fixed_indexquals = NIL;
1521 *nonlossy_indexquals = NIL;
1522 *indexstrategy = NIL;
1523 *indexsubtype = NIL;
1526 * For each qual clause, commute if needed to put the indexkey operand on
1527 * the left, and then fix its varattno. (We do not need to change the
1528 * other side of the clause.) Then determine the operator's strategy
1529 * number and subtype number, and check for lossy index behavior.
1531 foreach(l, indexquals)
1533 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1541 Assert(IsA(rinfo, RestrictInfo));
1542 clause = (OpExpr *) rinfo->clause;
1543 if (!IsA(clause, OpExpr) ||
1544 list_length(clause->args) != 2)
1545 elog(ERROR, "indexqual clause is not binary opclause");
1548 * Make a copy that will become the fixed clause.
1550 * We used to try to do a shallow copy here, but that fails if there is a
1551 * subplan in the arguments of the opclause. So just do a full copy.
1553 newclause = (OpExpr *) copyObject((Node *) clause);
1556 * Check to see if the indexkey is on the right; if so, commute the
1557 * clause. The indexkey should be the side that refers to (only) the
1560 if (!bms_equal(rinfo->left_relids, index->rel->relids))
1561 CommuteClause(newclause);
1564 * Now, determine which index attribute this is, change the indexkey
1565 * operand as needed, and get the index opclass.
1567 linitial(newclause->args) =
1568 fix_indexqual_operand(linitial(newclause->args),
1572 *fixed_indexquals = lappend(*fixed_indexquals, newclause);
1575 * Look up the (possibly commuted) operator in the operator class to
1576 * get its strategy numbers and the recheck indicator. This also
1577 * double-checks that we found an operator matching the index.
1579 get_op_opclass_properties(newclause->opno, opclass,
1580 &stratno, &stratsubtype, &recheck);
1582 *indexstrategy = lappend_int(*indexstrategy, stratno);
1583 *indexsubtype = lappend_oid(*indexsubtype, stratsubtype);
1585 /* If it's not lossy, add to nonlossy_indexquals */
1587 *nonlossy_indexquals = lappend(*nonlossy_indexquals, rinfo);
1592 fix_indexqual_operand(Node *node, IndexOptInfo *index, Oid *opclass)
1595 * We represent index keys by Var nodes having the varno of the base table
1596 * but varattno equal to the index's attribute number (index column
1597 * position). This is a bit hokey ... would be cleaner to use a
1598 * special-purpose node type that could not be mistaken for a regular Var.
1599 * But it will do for now.
1603 ListCell *indexpr_item;
1606 * Remove any binary-compatible relabeling of the indexkey
1608 if (IsA(node, RelabelType))
1609 node = (Node *) ((RelabelType *) node)->arg;
1611 if (IsA(node, Var) &&
1612 ((Var *) node)->varno == index->rel->relid)
1614 /* Try to match against simple index columns */
1615 int varatt = ((Var *) node)->varattno;
1619 for (pos = 0; pos < index->ncolumns; pos++)
1621 if (index->indexkeys[pos] == varatt)
1623 result = (Var *) copyObject(node);
1624 result->varattno = pos + 1;
1625 /* return the correct opclass, too */
1626 *opclass = index->classlist[pos];
1627 return (Node *) result;
1633 /* Try to match against index expressions */
1634 indexpr_item = list_head(index->indexprs);
1635 for (pos = 0; pos < index->ncolumns; pos++)
1637 if (index->indexkeys[pos] == 0)
1641 if (indexpr_item == NULL)
1642 elog(ERROR, "too few entries in indexprs list");
1643 indexkey = (Node *) lfirst(indexpr_item);
1644 if (indexkey && IsA(indexkey, RelabelType))
1645 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
1646 if (equal(node, indexkey))
1649 result = makeVar(index->rel->relid, pos + 1,
1650 exprType(lfirst(indexpr_item)), -1,
1652 /* return the correct opclass, too */
1653 *opclass = index->classlist[pos];
1654 return (Node *) result;
1656 indexpr_item = lnext(indexpr_item);
1661 elog(ERROR, "node is not an index attribute");
1662 *opclass = InvalidOid; /* keep compiler quiet */
1667 * get_switched_clauses
1668 * Given a list of merge or hash joinclauses (as RestrictInfo nodes),
1669 * extract the bare clauses, and rearrange the elements within the
1670 * clauses, if needed, so the outer join variable is on the left and
1671 * the inner is on the right. The original data structure is not touched;
1672 * a modified list is returned.
1675 get_switched_clauses(List *clauses, Relids outerrelids)
1682 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
1683 OpExpr *clause = (OpExpr *) restrictinfo->clause;
1685 Assert(is_opclause(clause));
1686 if (bms_is_subset(restrictinfo->right_relids, outerrelids))
1689 * Duplicate just enough of the structure to allow commuting the
1690 * clause without changing the original list. Could use
1691 * copyObject, but a complete deep copy is overkill.
1693 OpExpr *temp = makeNode(OpExpr);
1695 temp->opno = clause->opno;
1696 temp->opfuncid = InvalidOid;
1697 temp->opresulttype = clause->opresulttype;
1698 temp->opretset = clause->opretset;
1699 temp->args = list_copy(clause->args);
1700 /* Commute it --- note this modifies the temp node in-place. */
1701 CommuteClause(temp);
1702 t_list = lappend(t_list, temp);
1705 t_list = lappend(t_list, clause);
1711 * order_qual_clauses
1712 * Given a list of qual clauses that will all be evaluated at the same
1713 * plan node, sort the list into the order we want to check the quals
1716 * Ideally the order should be driven by a combination of execution cost and
1717 * selectivity, but unfortunately we have so little information about
1718 * execution cost of operators that it's really hard to do anything smart.
1719 * For now, we just move any quals that contain SubPlan references (but not
1720 * InitPlan references) to the end of the list.
1723 order_qual_clauses(PlannerInfo *root, List *clauses)
1729 /* No need to work hard if the query is subselect-free */
1730 if (!root->parse->hasSubLinks)
1737 Node *clause = (Node *) lfirst(l);
1739 if (contain_subplans(clause))
1740 withsubplans = lappend(withsubplans, clause);
1742 nosubplans = lappend(nosubplans, clause);
1745 return list_concat(nosubplans, withsubplans);
1749 * Copy cost and size info from a Path node to the Plan node created from it.
1750 * The executor won't use this info, but it's needed by EXPLAIN.
1753 copy_path_costsize(Plan *dest, Path *src)
1757 dest->startup_cost = src->startup_cost;
1758 dest->total_cost = src->total_cost;
1759 dest->plan_rows = src->parent->rows;
1760 dest->plan_width = src->parent->width;
1764 dest->startup_cost = 0;
1765 dest->total_cost = 0;
1766 dest->plan_rows = 0;
1767 dest->plan_width = 0;
1772 * Copy cost and size info from a lower plan node to an inserted node.
1773 * This is not critical, since the decisions have already been made,
1774 * but it helps produce more reasonable-looking EXPLAIN output.
1775 * (Some callers alter the info after copying it.)
1778 copy_plan_costsize(Plan *dest, Plan *src)
1782 dest->startup_cost = src->startup_cost;
1783 dest->total_cost = src->total_cost;
1784 dest->plan_rows = src->plan_rows;
1785 dest->plan_width = src->plan_width;
1789 dest->startup_cost = 0;
1790 dest->total_cost = 0;
1791 dest->plan_rows = 0;
1792 dest->plan_width = 0;
1797 /*****************************************************************************
1799 * PLAN NODE BUILDING ROUTINES
1801 * Some of these are exported because they are called to build plan nodes
1802 * in contexts where we're not deriving the plan node from a path node.
1804 *****************************************************************************/
1807 make_seqscan(List *qptlist,
1811 SeqScan *node = makeNode(SeqScan);
1812 Plan *plan = &node->plan;
1814 /* cost should be inserted by caller */
1815 plan->targetlist = qptlist;
1816 plan->qual = qpqual;
1817 plan->lefttree = NULL;
1818 plan->righttree = NULL;
1819 node->scanrelid = scanrelid;
1825 make_indexscan(List *qptlist,
1830 List *indexqualorig,
1831 List *indexstrategy,
1833 ScanDirection indexscandir)
1835 IndexScan *node = makeNode(IndexScan);
1836 Plan *plan = &node->scan.plan;
1838 /* cost should be inserted by caller */
1839 plan->targetlist = qptlist;
1840 plan->qual = qpqual;
1841 plan->lefttree = NULL;
1842 plan->righttree = NULL;
1843 node->scan.scanrelid = scanrelid;
1844 node->indexid = indexid;
1845 node->indexqual = indexqual;
1846 node->indexqualorig = indexqualorig;
1847 node->indexstrategy = indexstrategy;
1848 node->indexsubtype = indexsubtype;
1849 node->indexorderdir = indexscandir;
1854 static BitmapIndexScan *
1855 make_bitmap_indexscan(Index scanrelid,
1858 List *indexqualorig,
1859 List *indexstrategy,
1862 BitmapIndexScan *node = makeNode(BitmapIndexScan);
1863 Plan *plan = &node->scan.plan;
1865 /* cost should be inserted by caller */
1866 plan->targetlist = NIL; /* not used */
1867 plan->qual = NIL; /* not used */
1868 plan->lefttree = NULL;
1869 plan->righttree = NULL;
1870 node->scan.scanrelid = scanrelid;
1871 node->indexid = indexid;
1872 node->indexqual = indexqual;
1873 node->indexqualorig = indexqualorig;
1874 node->indexstrategy = indexstrategy;
1875 node->indexsubtype = indexsubtype;
1880 static BitmapHeapScan *
1881 make_bitmap_heapscan(List *qptlist,
1884 List *bitmapqualorig,
1887 BitmapHeapScan *node = makeNode(BitmapHeapScan);
1888 Plan *plan = &node->scan.plan;
1890 /* cost should be inserted by caller */
1891 plan->targetlist = qptlist;
1892 plan->qual = qpqual;
1893 plan->lefttree = lefttree;
1894 plan->righttree = NULL;
1895 node->scan.scanrelid = scanrelid;
1896 node->bitmapqualorig = bitmapqualorig;
1902 make_tidscan(List *qptlist,
1907 TidScan *node = makeNode(TidScan);
1908 Plan *plan = &node->scan.plan;
1910 /* cost should be inserted by caller */
1911 plan->targetlist = qptlist;
1912 plan->qual = qpqual;
1913 plan->lefttree = NULL;
1914 plan->righttree = NULL;
1915 node->scan.scanrelid = scanrelid;
1916 node->tideval = tideval;
1922 make_subqueryscan(List *qptlist,
1927 SubqueryScan *node = makeNode(SubqueryScan);
1928 Plan *plan = &node->scan.plan;
1931 * Cost is figured here for the convenience of prepunion.c. Note this is
1932 * only correct for the case where qpqual is empty; otherwise caller
1933 * should overwrite cost with a better estimate.
1935 copy_plan_costsize(plan, subplan);
1936 plan->total_cost += cpu_tuple_cost * subplan->plan_rows;
1938 plan->targetlist = qptlist;
1939 plan->qual = qpqual;
1940 plan->lefttree = NULL;
1941 plan->righttree = NULL;
1942 node->scan.scanrelid = scanrelid;
1943 node->subplan = subplan;
1948 static FunctionScan *
1949 make_functionscan(List *qptlist,
1953 FunctionScan *node = makeNode(FunctionScan);
1954 Plan *plan = &node->scan.plan;
1956 /* cost should be inserted by caller */
1957 plan->targetlist = qptlist;
1958 plan->qual = qpqual;
1959 plan->lefttree = NULL;
1960 plan->righttree = NULL;
1961 node->scan.scanrelid = scanrelid;
1967 make_append(List *appendplans, bool isTarget, List *tlist)
1969 Append *node = makeNode(Append);
1970 Plan *plan = &node->plan;
1974 * Compute cost as sum of subplan costs. We charge nothing extra for the
1975 * Append itself, which perhaps is too optimistic, but since it doesn't do
1976 * any selection or projection, it is a pretty cheap node.
1978 plan->startup_cost = 0;
1979 plan->total_cost = 0;
1980 plan->plan_rows = 0;
1981 plan->plan_width = 0;
1982 foreach(subnode, appendplans)
1984 Plan *subplan = (Plan *) lfirst(subnode);
1986 if (subnode == list_head(appendplans)) /* first node? */
1987 plan->startup_cost = subplan->startup_cost;
1988 plan->total_cost += subplan->total_cost;
1989 plan->plan_rows += subplan->plan_rows;
1990 if (plan->plan_width < subplan->plan_width)
1991 plan->plan_width = subplan->plan_width;
1994 plan->targetlist = tlist;
1996 plan->lefttree = NULL;
1997 plan->righttree = NULL;
1998 node->appendplans = appendplans;
1999 node->isTarget = isTarget;
2005 make_bitmap_and(List *bitmapplans)
2007 BitmapAnd *node = makeNode(BitmapAnd);
2008 Plan *plan = &node->plan;
2010 /* cost should be inserted by caller */
2011 plan->targetlist = NIL;
2013 plan->lefttree = NULL;
2014 plan->righttree = NULL;
2015 node->bitmapplans = bitmapplans;
2021 make_bitmap_or(List *bitmapplans)
2023 BitmapOr *node = makeNode(BitmapOr);
2024 Plan *plan = &node->plan;
2026 /* cost should be inserted by caller */
2027 plan->targetlist = NIL;
2029 plan->lefttree = NULL;
2030 plan->righttree = NULL;
2031 node->bitmapplans = bitmapplans;
2037 make_nestloop(List *tlist,
2044 NestLoop *node = makeNode(NestLoop);
2045 Plan *plan = &node->join.plan;
2047 /* cost should be inserted by caller */
2048 plan->targetlist = tlist;
2049 plan->qual = otherclauses;
2050 plan->lefttree = lefttree;
2051 plan->righttree = righttree;
2052 node->join.jointype = jointype;
2053 node->join.joinqual = joinclauses;
2059 make_hashjoin(List *tlist,
2067 HashJoin *node = makeNode(HashJoin);
2068 Plan *plan = &node->join.plan;
2070 /* cost should be inserted by caller */
2071 plan->targetlist = tlist;
2072 plan->qual = otherclauses;
2073 plan->lefttree = lefttree;
2074 plan->righttree = righttree;
2075 node->hashclauses = hashclauses;
2076 node->join.jointype = jointype;
2077 node->join.joinqual = joinclauses;
2083 make_hash(Plan *lefttree)
2085 Hash *node = makeNode(Hash);
2086 Plan *plan = &node->plan;
2088 copy_plan_costsize(plan, lefttree);
2091 * For plausibility, make startup & total costs equal total cost of input
2092 * plan; this only affects EXPLAIN display not decisions.
2094 plan->startup_cost = plan->total_cost;
2095 plan->targetlist = copyObject(lefttree->targetlist);
2097 plan->lefttree = lefttree;
2098 plan->righttree = NULL;
2104 make_mergejoin(List *tlist,
2112 MergeJoin *node = makeNode(MergeJoin);
2113 Plan *plan = &node->join.plan;
2115 /* cost should be inserted by caller */
2116 plan->targetlist = tlist;
2117 plan->qual = otherclauses;
2118 plan->lefttree = lefttree;
2119 plan->righttree = righttree;
2120 node->mergeclauses = mergeclauses;
2121 node->join.jointype = jointype;
2122 node->join.joinqual = joinclauses;
2128 * make_sort --- basic routine to build a Sort plan node
2130 * Caller must have built the sortColIdx and sortOperators arrays already.
2133 make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
2134 AttrNumber *sortColIdx, Oid *sortOperators)
2136 Sort *node = makeNode(Sort);
2137 Plan *plan = &node->plan;
2138 Path sort_path; /* dummy for result of cost_sort */
2140 copy_plan_costsize(plan, lefttree); /* only care about copying size */
2141 cost_sort(&sort_path, root, NIL,
2142 lefttree->total_cost,
2143 lefttree->plan_rows,
2144 lefttree->plan_width);
2145 plan->startup_cost = sort_path.startup_cost;
2146 plan->total_cost = sort_path.total_cost;
2147 plan->targetlist = copyObject(lefttree->targetlist);
2149 plan->lefttree = lefttree;
2150 plan->righttree = NULL;
2151 node->numCols = numCols;
2152 node->sortColIdx = sortColIdx;
2153 node->sortOperators = sortOperators;
2159 * add_sort_column --- utility subroutine for building sort info arrays
2161 * We need this routine because the same column might be selected more than
2162 * once as a sort key column; if so, the extra mentions are redundant.
2164 * Caller is assumed to have allocated the arrays large enough for the
2165 * max possible number of columns. Return value is the new column count.
2168 add_sort_column(AttrNumber colIdx, Oid sortOp,
2169 int numCols, AttrNumber *sortColIdx, Oid *sortOperators)
2173 for (i = 0; i < numCols; i++)
2175 if (sortColIdx[i] == colIdx)
2177 /* Already sorting by this col, so extra sort key is useless */
2182 /* Add the column */
2183 sortColIdx[numCols] = colIdx;
2184 sortOperators[numCols] = sortOp;
2189 * make_sort_from_pathkeys
2190 * Create sort plan to sort according to given pathkeys
2192 * 'lefttree' is the node which yields input tuples
2193 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
2195 * We must convert the pathkey information into arrays of sort key column
2196 * numbers and sort operator OIDs.
2198 * If the pathkeys include expressions that aren't simple Vars, we will
2199 * usually need to add resjunk items to the input plan's targetlist to
2200 * compute these expressions (since the Sort node itself won't do it).
2201 * If the input plan type isn't one that can do projections, this means
2202 * adding a Result node just to do the projection.
2205 make_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys)
2207 List *tlist = lefttree->targetlist;
2210 AttrNumber *sortColIdx;
2214 * We will need at most list_length(pathkeys) sort columns; possibly less
2216 numsortkeys = list_length(pathkeys);
2217 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
2218 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
2222 foreach(i, pathkeys)
2224 List *keysublist = (List *) lfirst(i);
2225 PathKeyItem *pathkey = NULL;
2226 TargetEntry *tle = NULL;
2230 * We can sort by any one of the sort key items listed in this
2231 * sublist. For now, we take the first one that corresponds to an
2232 * available Var in the tlist. If there isn't any, use the first one
2233 * that is an expression in the input's vars.
2235 * XXX if we have a choice, is there any way of figuring out which might
2236 * be cheapest to execute? (For example, int4lt is likely much
2237 * cheaper to execute than numericlt, but both might appear in the
2238 * same pathkey sublist...) Not clear that we ever will have a choice
2239 * in practice, so it may not matter.
2241 foreach(j, keysublist)
2243 pathkey = (PathKeyItem *) lfirst(j);
2244 Assert(IsA(pathkey, PathKeyItem));
2245 tle = tlist_member(pathkey->key, tlist);
2251 /* No matching Var; look for a computable expression */
2252 foreach(j, keysublist)
2257 pathkey = (PathKeyItem *) lfirst(j);
2258 exprvars = pull_var_clause(pathkey->key, false);
2259 foreach(k, exprvars)
2261 if (!tlist_member(lfirst(k), tlist))
2264 list_free(exprvars);
2266 break; /* found usable expression */
2269 elog(ERROR, "could not find pathkey item to sort");
2272 * Do we need to insert a Result node?
2274 if (!is_projection_capable_plan(lefttree))
2276 tlist = copyObject(tlist);
2277 lefttree = (Plan *) make_result(tlist, NULL, lefttree);
2281 * Add resjunk entry to input's tlist
2283 tle = makeTargetEntry((Expr *) pathkey->key,
2284 list_length(tlist) + 1,
2287 tlist = lappend(tlist, tle);
2288 lefttree->targetlist = tlist; /* just in case NIL before */
2292 * The column might already be selected as a sort key, if the pathkeys
2293 * contain duplicate entries. (This can happen in scenarios where
2294 * multiple mergejoinable clauses mention the same var, for example.)
2295 * So enter it only once in the sort arrays.
2297 numsortkeys = add_sort_column(tle->resno, pathkey->sortop,
2298 numsortkeys, sortColIdx, sortOperators);
2301 Assert(numsortkeys > 0);
2303 return make_sort(root, lefttree, numsortkeys,
2304 sortColIdx, sortOperators);
2308 * make_sort_from_sortclauses
2309 * Create sort plan to sort according to given sortclauses
2311 * 'sortcls' is a list of SortClauses
2312 * 'lefttree' is the node which yields input tuples
2315 make_sort_from_sortclauses(PlannerInfo *root, List *sortcls, Plan *lefttree)
2317 List *sub_tlist = lefttree->targetlist;
2320 AttrNumber *sortColIdx;
2324 * We will need at most list_length(sortcls) sort columns; possibly less
2326 numsortkeys = list_length(sortcls);
2327 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
2328 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
2334 SortClause *sortcl = (SortClause *) lfirst(l);
2335 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
2338 * Check for the possibility of duplicate order-by clauses --- the
2339 * parser should have removed 'em, but no point in sorting
2342 numsortkeys = add_sort_column(tle->resno, sortcl->sortop,
2343 numsortkeys, sortColIdx, sortOperators);
2346 Assert(numsortkeys > 0);
2348 return make_sort(root, lefttree, numsortkeys,
2349 sortColIdx, sortOperators);
2353 * make_sort_from_groupcols
2354 * Create sort plan to sort based on grouping columns
2356 * 'groupcls' is the list of GroupClauses
2357 * 'grpColIdx' gives the column numbers to use
2359 * This might look like it could be merged with make_sort_from_sortclauses,
2360 * but presently we *must* use the grpColIdx[] array to locate sort columns,
2361 * because the child plan's tlist is not marked with ressortgroupref info
2362 * appropriate to the grouping node. So, only the sortop is used from the
2363 * GroupClause entries.
2366 make_sort_from_groupcols(PlannerInfo *root,
2368 AttrNumber *grpColIdx,
2371 List *sub_tlist = lefttree->targetlist;
2375 AttrNumber *sortColIdx;
2379 * We will need at most list_length(groupcls) sort columns; possibly less
2381 numsortkeys = list_length(groupcls);
2382 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
2383 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
2387 foreach(l, groupcls)
2389 GroupClause *grpcl = (GroupClause *) lfirst(l);
2390 TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[grpno]);
2393 * Check for the possibility of duplicate group-by clauses --- the
2394 * parser should have removed 'em, but no point in sorting
2397 numsortkeys = add_sort_column(tle->resno, grpcl->sortop,
2398 numsortkeys, sortColIdx, sortOperators);
2402 Assert(numsortkeys > 0);
2404 return make_sort(root, lefttree, numsortkeys,
2405 sortColIdx, sortOperators);
2409 make_material(Plan *lefttree)
2411 Material *node = makeNode(Material);
2412 Plan *plan = &node->plan;
2414 /* cost should be inserted by caller */
2415 plan->targetlist = copyObject(lefttree->targetlist);
2417 plan->lefttree = lefttree;
2418 plan->righttree = NULL;
2424 * materialize_finished_plan: stick a Material node atop a completed plan
2426 * There are a couple of places where we want to attach a Material node
2427 * after completion of subquery_planner(). This currently requires hackery.
2428 * Since subquery_planner has already run SS_finalize_plan on the subplan
2429 * tree, we have to kluge up parameter lists for the Material node.
2430 * Possibly this could be fixed by postponing SS_finalize_plan processing
2431 * until setrefs.c is run?
2434 materialize_finished_plan(Plan *subplan)
2437 Path matpath; /* dummy for result of cost_material */
2439 matplan = (Plan *) make_material(subplan);
2442 cost_material(&matpath,
2443 subplan->total_cost,
2445 subplan->plan_width);
2446 matplan->startup_cost = matpath.startup_cost;
2447 matplan->total_cost = matpath.total_cost;
2448 matplan->plan_rows = subplan->plan_rows;
2449 matplan->plan_width = subplan->plan_width;
2451 /* parameter kluge --- see comments above */
2452 matplan->extParam = bms_copy(subplan->extParam);
2453 matplan->allParam = bms_copy(subplan->allParam);
2459 make_agg(PlannerInfo *root, List *tlist, List *qual,
2460 AggStrategy aggstrategy,
2461 int numGroupCols, AttrNumber *grpColIdx,
2462 long numGroups, int numAggs,
2465 Agg *node = makeNode(Agg);
2466 Plan *plan = &node->plan;
2467 Path agg_path; /* dummy for result of cost_agg */
2470 node->aggstrategy = aggstrategy;
2471 node->numCols = numGroupCols;
2472 node->grpColIdx = grpColIdx;
2473 node->numGroups = numGroups;
2475 copy_plan_costsize(plan, lefttree); /* only care about copying size */
2476 cost_agg(&agg_path, root,
2477 aggstrategy, numAggs,
2478 numGroupCols, numGroups,
2479 lefttree->startup_cost,
2480 lefttree->total_cost,
2481 lefttree->plan_rows);
2482 plan->startup_cost = agg_path.startup_cost;
2483 plan->total_cost = agg_path.total_cost;
2486 * We will produce a single output tuple if not grouping, and a tuple per
2489 if (aggstrategy == AGG_PLAIN)
2490 plan->plan_rows = 1;
2492 plan->plan_rows = numGroups;
2495 * We also need to account for the cost of evaluation of the qual (ie, the
2496 * HAVING clause) and the tlist. Note that cost_qual_eval doesn't charge
2497 * anything for Aggref nodes; this is okay since they are really
2498 * comparable to Vars.
2500 * See notes in grouping_planner about why this routine and make_group are
2501 * the only ones in this file that worry about tlist eval cost.
2505 cost_qual_eval(&qual_cost, qual);
2506 plan->startup_cost += qual_cost.startup;
2507 plan->total_cost += qual_cost.startup;
2508 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2510 cost_qual_eval(&qual_cost, tlist);
2511 plan->startup_cost += qual_cost.startup;
2512 plan->total_cost += qual_cost.startup;
2513 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2516 plan->targetlist = tlist;
2517 plan->lefttree = lefttree;
2518 plan->righttree = NULL;
2524 make_group(PlannerInfo *root,
2528 AttrNumber *grpColIdx,
2532 Group *node = makeNode(Group);
2533 Plan *plan = &node->plan;
2534 Path group_path; /* dummy for result of cost_group */
2537 node->numCols = numGroupCols;
2538 node->grpColIdx = grpColIdx;
2540 copy_plan_costsize(plan, lefttree); /* only care about copying size */
2541 cost_group(&group_path, root,
2542 numGroupCols, numGroups,
2543 lefttree->startup_cost,
2544 lefttree->total_cost,
2545 lefttree->plan_rows);
2546 plan->startup_cost = group_path.startup_cost;
2547 plan->total_cost = group_path.total_cost;
2549 /* One output tuple per estimated result group */
2550 plan->plan_rows = numGroups;
2553 * We also need to account for the cost of evaluation of the qual (ie, the
2554 * HAVING clause) and the tlist.
2556 * XXX this double-counts the cost of evaluation of any expressions used for
2557 * grouping, since in reality those will have been evaluated at a lower
2558 * plan level and will only be copied by the Group node. Worth fixing?
2560 * See notes in grouping_planner about why this routine and make_agg are the
2561 * only ones in this file that worry about tlist eval cost.
2565 cost_qual_eval(&qual_cost, qual);
2566 plan->startup_cost += qual_cost.startup;
2567 plan->total_cost += qual_cost.startup;
2568 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2570 cost_qual_eval(&qual_cost, tlist);
2571 plan->startup_cost += qual_cost.startup;
2572 plan->total_cost += qual_cost.startup;
2573 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2576 plan->targetlist = tlist;
2577 plan->lefttree = lefttree;
2578 plan->righttree = NULL;
2584 * distinctList is a list of SortClauses, identifying the targetlist items
2585 * that should be considered by the Unique filter.
2588 make_unique(Plan *lefttree, List *distinctList)
2590 Unique *node = makeNode(Unique);
2591 Plan *plan = &node->plan;
2592 int numCols = list_length(distinctList);
2594 AttrNumber *uniqColIdx;
2597 copy_plan_costsize(plan, lefttree);
2600 * Charge one cpu_operator_cost per comparison per input tuple. We assume
2601 * all columns get compared at most of the tuples. (XXX probably this is
2604 plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols;
2607 * plan->plan_rows is left as a copy of the input subplan's plan_rows; ie,
2608 * we assume the filter removes nothing. The caller must alter this if he
2609 * has a better idea.
2612 plan->targetlist = copyObject(lefttree->targetlist);
2614 plan->lefttree = lefttree;
2615 plan->righttree = NULL;
2618 * convert SortClause list into array of attr indexes, as wanted by exec
2620 Assert(numCols > 0);
2621 uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
2623 foreach(slitem, distinctList)
2625 SortClause *sortcl = (SortClause *) lfirst(slitem);
2626 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
2628 uniqColIdx[keyno++] = tle->resno;
2631 node->numCols = numCols;
2632 node->uniqColIdx = uniqColIdx;
2638 * distinctList is a list of SortClauses, identifying the targetlist items
2639 * that should be considered by the SetOp filter.
2643 make_setop(SetOpCmd cmd, Plan *lefttree,
2644 List *distinctList, AttrNumber flagColIdx)
2646 SetOp *node = makeNode(SetOp);
2647 Plan *plan = &node->plan;
2648 int numCols = list_length(distinctList);
2650 AttrNumber *dupColIdx;
2653 copy_plan_costsize(plan, lefttree);
2656 * Charge one cpu_operator_cost per comparison per input tuple. We assume
2657 * all columns get compared at most of the tuples.
2659 plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols;
2662 * We make the unsupported assumption that there will be 10% as many
2663 * tuples out as in. Any way to do better?
2665 plan->plan_rows *= 0.1;
2666 if (plan->plan_rows < 1)
2667 plan->plan_rows = 1;
2669 plan->targetlist = copyObject(lefttree->targetlist);
2671 plan->lefttree = lefttree;
2672 plan->righttree = NULL;
2675 * convert SortClause list into array of attr indexes, as wanted by exec
2677 Assert(numCols > 0);
2678 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
2680 foreach(slitem, distinctList)
2682 SortClause *sortcl = (SortClause *) lfirst(slitem);
2683 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
2685 dupColIdx[keyno++] = tle->resno;
2689 node->numCols = numCols;
2690 node->dupColIdx = dupColIdx;
2691 node->flagColIdx = flagColIdx;
2697 * Note: offset_est and count_est are passed in to save having to repeat
2698 * work already done to estimate the values of the limitOffset and limitCount
2699 * expressions. Their values are as returned by preprocess_limit (0 means
2700 * "not relevant", -1 means "couldn't estimate"). Keep the code below in sync
2701 * with that function!
2704 make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount,
2705 int offset_est, int count_est)
2707 Limit *node = makeNode(Limit);
2708 Plan *plan = &node->plan;
2710 copy_plan_costsize(plan, lefttree);
2713 * Adjust the output rows count and costs according to the offset/limit.
2714 * This is only a cosmetic issue if we are at top level, but if we are
2715 * building a subquery then it's important to report correct info to the
2718 * When the offset or count couldn't be estimated, use 10% of the estimated
2719 * number of rows emitted from the subplan.
2721 if (offset_est != 0)
2726 offset_rows = (double) offset_est;
2728 offset_rows = clamp_row_est(lefttree->plan_rows * 0.10);
2729 if (offset_rows > plan->plan_rows)
2730 offset_rows = plan->plan_rows;
2731 if (plan->plan_rows > 0)
2732 plan->startup_cost +=
2733 (plan->total_cost - plan->startup_cost)
2734 * offset_rows / plan->plan_rows;
2735 plan->plan_rows -= offset_rows;
2736 if (plan->plan_rows < 1)
2737 plan->plan_rows = 1;
2745 count_rows = (double) count_est;
2747 count_rows = clamp_row_est(lefttree->plan_rows * 0.10);
2748 if (count_rows > plan->plan_rows)
2749 count_rows = plan->plan_rows;
2750 if (plan->plan_rows > 0)
2751 plan->total_cost = plan->startup_cost +
2752 (plan->total_cost - plan->startup_cost)
2753 * count_rows / plan->plan_rows;
2754 plan->plan_rows = count_rows;
2755 if (plan->plan_rows < 1)
2756 plan->plan_rows = 1;
2759 plan->targetlist = copyObject(lefttree->targetlist);
2761 plan->lefttree = lefttree;
2762 plan->righttree = NULL;
2764 node->limitOffset = limitOffset;
2765 node->limitCount = limitCount;
2771 make_result(List *tlist,
2772 Node *resconstantqual,
2775 Result *node = makeNode(Result);
2776 Plan *plan = &node->plan;
2779 copy_plan_costsize(plan, subplan);
2782 plan->startup_cost = 0;
2783 plan->total_cost = cpu_tuple_cost;
2784 plan->plan_rows = 1; /* wrong if we have a set-valued function? */
2785 plan->plan_width = 0; /* XXX try to be smarter? */
2788 if (resconstantqual)
2792 cost_qual_eval(&qual_cost, (List *) resconstantqual);
2793 /* resconstantqual is evaluated once at startup */
2794 plan->startup_cost += qual_cost.startup + qual_cost.per_tuple;
2795 plan->total_cost += qual_cost.startup + qual_cost.per_tuple;
2798 plan->targetlist = tlist;
2800 plan->lefttree = subplan;
2801 plan->righttree = NULL;
2802 node->resconstantqual = resconstantqual;
2808 * is_projection_capable_plan
2809 * Check whether a given Plan node is able to do projection.
2812 is_projection_capable_plan(Plan *plan)
2814 /* Most plan types can project, so just list the ones that can't */
2815 switch (nodeTag(plan))