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.200 2005/10/13 00:06:46 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
199 * is only those Vars actually needed by the query), we prefer to
200 * generate a tlist containing all Vars in order. This will allow the
201 * executor to optimize away projection of the table tuples, if
202 * possible. (Note that planner.c may replace the tlist we generate
203 * here, forcing projection to occur.)
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;
217 * the 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 * OK for subquery and function scans; otherwise, can't do it for
312 * anything except real relations.
314 if (rel->rtekind != RTE_RELATION)
316 if (rel->rtekind == RTE_SUBQUERY)
318 if (rel->rtekind == RTE_FUNCTION)
324 * Can't do it with inheritance cases either (mainly because Append
327 if (rel->reloptkind != RELOPT_BASEREL)
331 * Can't do it if any system columns are requested, either. (This
332 * could possibly be fixed but would take some fragile assumptions in
333 * setrefs.c, I think.)
335 for (i = rel->min_attr; i <= 0; i++)
337 if (!bms_is_empty(rel->attr_needed[i - rel->min_attr]))
344 * disuse_physical_tlist
345 * Switch a plan node back to emitting only Vars actually referenced.
347 * If the plan node immediately above a scan would prefer to get only
348 * needed Vars and not a physical tlist, it must call this routine to
349 * undo the decision made by use_physical_tlist(). Currently, Hash, Sort,
350 * and Material nodes want this, so they don't have to store useless columns.
353 disuse_physical_tlist(Plan *plan, Path *path)
355 /* Only need to undo it for path types handled by create_scan_plan() */
356 switch (path->pathtype)
360 case T_BitmapHeapScan:
364 plan->targetlist = build_relation_tlist(path->parent);
373 * Create a join plan for 'best_path' and (recursively) plans for its
374 * inner and outer paths.
376 * Returns a Plan node.
379 create_join_plan(PlannerInfo *root, JoinPath *best_path)
385 outer_plan = create_plan(root, best_path->outerjoinpath);
386 inner_plan = create_plan(root, best_path->innerjoinpath);
388 switch (best_path->path.pathtype)
391 plan = (Join *) create_mergejoin_plan(root,
392 (MergePath *) best_path,
397 plan = (Join *) create_hashjoin_plan(root,
398 (HashPath *) best_path,
403 plan = (Join *) create_nestloop_plan(root,
404 (NestPath *) best_path,
409 elog(ERROR, "unrecognized node type: %d",
410 (int) best_path->path.pathtype);
411 plan = NULL; /* keep compiler quiet */
418 * * Expensive function pullups may have pulled local predicates *
419 * into this path node. Put them in the qpqual of the plan node. *
422 if (get_loc_restrictinfo(best_path) != NIL)
423 set_qpqual((Plan) plan,
424 list_concat(get_qpqual((Plan) plan),
425 get_actual_clauses(get_loc_restrictinfo(best_path))));
433 * Create an Append plan for 'best_path' and (recursively) plans
436 * Returns a Plan node.
439 create_append_plan(PlannerInfo *root, AppendPath *best_path)
442 List *tlist = build_relation_tlist(best_path->path.parent);
443 List *subplans = NIL;
447 * It is possible for the subplans list to contain only one entry,
448 * or even no entries. Handle these cases specially.
450 * XXX ideally, if there's just one entry, we'd not bother to generate
451 * an Append node but just return the single child. At the moment this
452 * does not work because the varno of the child scan plan won't match
453 * the parent-rel Vars it'll be asked to emit.
455 if (best_path->subpaths == NIL)
457 /* Generate a Result plan with constant-FALSE gating qual */
458 return (Plan *) make_result(tlist,
459 (Node *) list_make1(makeBoolConst(false,
464 /* Normal case with multiple subpaths */
465 foreach(subpaths, best_path->subpaths)
467 Path *subpath = (Path *) lfirst(subpaths);
469 subplans = lappend(subplans, create_plan(root, subpath));
472 plan = make_append(subplans, false, tlist);
474 return (Plan *) plan;
479 * Create a Result plan for 'best_path' and (recursively) plans
482 * Returns a Plan node.
485 create_result_plan(PlannerInfo *root, ResultPath *best_path)
492 if (best_path->path.parent)
493 tlist = build_relation_tlist(best_path->path.parent);
495 tlist = NIL; /* will be filled in later */
497 if (best_path->subpath)
498 subplan = create_plan(root, best_path->subpath);
502 constclauses = order_qual_clauses(root, best_path->constantqual);
504 plan = make_result(tlist, (Node *) constclauses, subplan);
510 * create_material_plan
511 * Create a Material plan for 'best_path' and (recursively) plans
514 * Returns a Plan node.
517 create_material_plan(PlannerInfo *root, MaterialPath *best_path)
522 subplan = create_plan(root, best_path->subpath);
524 /* We don't want any excess columns in the materialized tuples */
525 disuse_physical_tlist(subplan, best_path->subpath);
527 plan = make_material(subplan);
529 copy_path_costsize(&plan->plan, (Path *) best_path);
536 * Create a Unique plan for 'best_path' and (recursively) plans
539 * Returns a Plan node.
542 create_unique_plan(PlannerInfo *root, UniquePath *best_path)
551 AttrNumber *groupColIdx;
555 subplan = create_plan(root, best_path->subpath);
557 /* Done if we don't need to do any actual unique-ifying */
558 if (best_path->umethod == UNIQUE_PATH_NOOP)
562 * As constructed, the subplan has a "flat" tlist containing just the
563 * Vars needed here and at upper levels. The values we are supposed
564 * to unique-ify may be expressions in these variables. We have to
565 * add any such expressions to the subplan's tlist.
567 * The subplan may have a "physical" tlist if it is a simple scan plan.
568 * This should be left as-is if we don't need to add any expressions;
569 * but if we do have to add expressions, then a projection step will be
570 * needed at runtime anyway, and so we may as well remove unneeded items.
571 * Therefore newtlist starts from build_relation_tlist() not just a
572 * copy of the subplan's tlist; and we don't install it into the subplan
573 * unless stuff has to be added.
575 * To find the correct list of values to unique-ify, we look in the
576 * information saved for IN expressions. If this code is ever used in
577 * other scenarios, some other way of finding what to unique-ify will
581 uniq_exprs = NIL; /* just to keep compiler quiet */
582 foreach(l, root->in_info_list)
584 InClauseInfo *ininfo = (InClauseInfo *) lfirst(l);
586 if (bms_equal(ininfo->righthand, best_path->path.parent->relids))
588 uniq_exprs = ininfo->sub_targetlist;
592 if (l == NULL) /* fell out of loop? */
593 elog(ERROR, "could not find UniquePath in in_info_list");
595 /* initialize modified subplan tlist as just the "required" vars */
596 newtlist = build_relation_tlist(best_path->path.parent);
597 nextresno = list_length(newtlist) + 1;
600 foreach(l, uniq_exprs)
602 Node *uniqexpr = lfirst(l);
605 tle = tlist_member(uniqexpr, newtlist);
608 tle = makeTargetEntry((Expr *) uniqexpr,
612 newtlist = lappend(newtlist, tle);
621 * If the top plan node can't do projections, we need to add a
622 * Result node to help it along.
624 if (!is_projection_capable_plan(subplan))
625 subplan = (Plan *) make_result(newtlist, NULL, subplan);
627 subplan->targetlist = newtlist;
631 * Build control information showing which subplan output columns are
632 * to be examined by the grouping step. Unfortunately we can't merge this
633 * with the previous loop, since we didn't then know which version of the
634 * subplan tlist we'd end up using.
636 newtlist = subplan->targetlist;
637 numGroupCols = list_length(uniq_exprs);
638 groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber));
641 foreach(l, uniq_exprs)
643 Node *uniqexpr = lfirst(l);
646 tle = tlist_member(uniqexpr, newtlist);
647 if (!tle) /* shouldn't happen */
648 elog(ERROR, "failed to find unique expression in subplan tlist");
649 groupColIdx[groupColPos++] = tle->resno;
652 if (best_path->umethod == UNIQUE_PATH_HASH)
656 numGroups = (long) Min(best_path->rows, (double) LONG_MAX);
659 * Since the Agg node is going to project anyway, we can give it
660 * the minimum output tlist, without any stuff we might have added
661 * to the subplan tlist.
663 plan = (Plan *) make_agg(root,
664 build_relation_tlist(best_path->path.parent),
675 List *sortList = NIL;
677 for (groupColPos = 0; groupColPos < numGroupCols; groupColPos++)
681 tle = get_tle_by_resno(subplan->targetlist,
682 groupColIdx[groupColPos]);
684 sortList = addTargetToSortList(NULL, tle,
685 sortList, subplan->targetlist,
686 SORTBY_ASC, NIL, false);
688 plan = (Plan *) make_sort_from_sortclauses(root, sortList, subplan);
689 plan = (Plan *) make_unique(plan, sortList);
692 /* Adjust output size estimate (other fields should be OK already) */
693 plan->plan_rows = best_path->rows;
699 /*****************************************************************************
701 * BASE-RELATION SCAN METHODS
703 *****************************************************************************/
707 * create_seqscan_plan
708 * Returns a seqscan plan for the base relation scanned by 'best_path'
709 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
712 create_seqscan_plan(PlannerInfo *root, Path *best_path,
713 List *tlist, List *scan_clauses)
716 Index scan_relid = best_path->parent->relid;
718 /* it should be a base rel... */
719 Assert(scan_relid > 0);
720 Assert(best_path->parent->rtekind == RTE_RELATION);
722 /* Reduce RestrictInfo list to bare expressions */
723 scan_clauses = get_actual_clauses(scan_clauses);
725 /* Sort clauses into best execution order */
726 scan_clauses = order_qual_clauses(root, scan_clauses);
728 scan_plan = make_seqscan(tlist,
732 copy_path_costsize(&scan_plan->plan, best_path);
738 * create_indexscan_plan
739 * Returns an indexscan plan for the base relation scanned by 'best_path'
740 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
742 * The indexquals list of the path contains implicitly-ANDed qual conditions.
743 * The list can be empty --- then no index restrictions will be applied during
746 * If nonlossy_clauses isn't NULL, *nonlossy_clauses receives a list of the
747 * nonlossy indexquals.
750 create_indexscan_plan(PlannerInfo *root,
751 IndexPath *best_path,
754 List **nonlossy_clauses)
756 List *indexquals = best_path->indexquals;
757 Index baserelid = best_path->path.parent->relid;
758 Oid indexoid = best_path->indexinfo->indexoid;
760 List *stripped_indexquals;
761 List *fixed_indexquals;
762 List *nonlossy_indexquals;
766 IndexScan *scan_plan;
768 /* it should be a base rel... */
769 Assert(baserelid > 0);
770 Assert(best_path->path.parent->rtekind == RTE_RELATION);
773 * Build "stripped" indexquals structure (no RestrictInfos) to pass to
774 * executor as indexqualorig
776 stripped_indexquals = get_actual_clauses(indexquals);
779 * The executor needs a copy with the indexkey on the left of each
780 * clause and with index attr numbers substituted for table ones. This
781 * pass also gets strategy info and looks for "lossy" operators.
783 fix_indexqual_references(indexquals, best_path,
785 &nonlossy_indexquals,
789 /* pass back nonlossy quals if caller wants 'em */
790 if (nonlossy_clauses)
791 *nonlossy_clauses = nonlossy_indexquals;
794 * If this is an innerjoin scan, the indexclauses will contain join
795 * clauses that are not present in scan_clauses (since the passed-in
796 * value is just the rel's baserestrictinfo list). We must add these
797 * clauses to scan_clauses to ensure they get checked. In most cases
798 * we will remove the join clauses again below, but if a join clause
799 * contains a special operator, we need to make sure it gets into the
802 * Note: pointer comparison should be enough to determine RestrictInfo
805 if (best_path->isjoininner)
806 scan_clauses = list_union_ptr(scan_clauses, best_path->indexclauses);
809 * The qpqual list must contain all restrictions not automatically
810 * handled by the index. All the predicates in the indexquals will be
811 * checked (either by the index itself, or by nodeIndexscan.c), but if
812 * there are any "special" operators involved then they must be included
813 * in qpqual. Also, any lossy index operators must be rechecked in
814 * the qpqual. The upshot is that qpqual must contain scan_clauses
815 * minus whatever appears in nonlossy_indexquals.
817 * In normal cases simple pointer equality checks will be enough to
818 * spot duplicate RestrictInfos, so we try that first. In some situations
819 * (particularly with OR'd index conditions) we may have scan_clauses
820 * that are not equal to, but are logically implied by, the index quals;
821 * so we also try a predicate_implied_by() check to see if we can discard
822 * quals that way. (predicate_implied_by assumes its first input contains
823 * only immutable functions, so we have to check that.) We can also
824 * discard quals that are implied by a partial index's predicate.
826 * While at it, we strip off the RestrictInfos to produce a list of
830 foreach(l, scan_clauses)
832 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
834 Assert(IsA(rinfo, RestrictInfo));
835 if (list_member_ptr(nonlossy_indexquals, rinfo))
837 if (!contain_mutable_functions((Node *) rinfo->clause))
839 List *clausel = list_make1(rinfo->clause);
841 if (predicate_implied_by(clausel, nonlossy_indexquals))
843 if (predicate_implied_by(clausel, best_path->indexinfo->indpred))
846 qpqual = lappend(qpqual, rinfo->clause);
849 /* Sort clauses into best execution order */
850 qpqual = order_qual_clauses(root, qpqual);
852 /* Finally ready to build the plan node */
853 scan_plan = make_indexscan(tlist,
861 best_path->indexscandir);
863 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
864 /* use the indexscan-specific rows estimate, not the parent rel's */
865 scan_plan->scan.plan.plan_rows = best_path->rows;
871 * create_bitmap_scan_plan
872 * Returns a bitmap scan plan for the base relation scanned by 'best_path'
873 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
875 static BitmapHeapScan *
876 create_bitmap_scan_plan(PlannerInfo *root,
877 BitmapHeapPath *best_path,
881 Index baserelid = best_path->path.parent->relid;
882 Plan *bitmapqualplan;
883 List *bitmapqualorig;
887 BitmapHeapScan *scan_plan;
889 /* it should be a base rel... */
890 Assert(baserelid > 0);
891 Assert(best_path->path.parent->rtekind == RTE_RELATION);
893 /* Process the bitmapqual tree into a Plan tree and qual lists */
894 bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
895 &bitmapqualorig, &indexquals);
897 /* Reduce RestrictInfo list to bare expressions */
898 scan_clauses = get_actual_clauses(scan_clauses);
901 * If this is a innerjoin scan, the indexclauses will contain join
902 * clauses that are not present in scan_clauses (since the passed-in
903 * value is just the rel's baserestrictinfo list). We must add these
904 * clauses to scan_clauses to ensure they get checked. In most cases
905 * we will remove the join clauses again below, but if a join clause
906 * contains a special operator, we need to make sure it gets into the
909 if (best_path->isjoininner)
911 scan_clauses = list_concat_unique(scan_clauses, bitmapqualorig);
915 * The qpqual list must contain all restrictions not automatically
916 * handled by the index. All the predicates in the indexquals will be
917 * checked (either by the index itself, or by nodeBitmapHeapscan.c),
918 * but if there are any "special" or lossy operators involved then they
919 * must be added to qpqual. The upshot is that qpquals must contain
920 * scan_clauses minus whatever appears in indexquals.
922 * In normal cases simple equal() checks will be enough to spot duplicate
923 * clauses, so we try that first. In some situations (particularly with
924 * OR'd index conditions) we may have scan_clauses that are not equal to,
925 * but are logically implied by, the index quals; so we also try a
926 * predicate_implied_by() check to see if we can discard quals that way.
927 * (predicate_implied_by assumes its first input contains only immutable
928 * functions, so we have to check that.) We can also discard quals that
929 * are implied by a partial index's predicate.
931 * XXX For the moment, we only consider partial index predicates in the
932 * simple single-index-scan case. Is it worth trying to be smart about
933 * more complex cases? Perhaps create_bitmap_subplan should be made to
934 * include predicate info in what it constructs.
937 foreach(l, scan_clauses)
939 Node *clause = (Node *) lfirst(l);
941 if (list_member(indexquals, clause))
943 if (!contain_mutable_functions(clause))
945 List *clausel = list_make1(clause);
947 if (predicate_implied_by(clausel, indexquals))
949 if (IsA(best_path->bitmapqual, IndexPath))
951 IndexPath *ipath = (IndexPath *) best_path->bitmapqual;
953 if (predicate_implied_by(clausel, ipath->indexinfo->indpred))
957 qpqual = lappend(qpqual, clause);
960 /* Sort clauses into best execution order */
961 qpqual = order_qual_clauses(root, qpqual);
964 * When dealing with special or lossy operators, we will at this point
965 * have duplicate clauses in qpqual and bitmapqualorig. We may as well
966 * drop 'em from bitmapqualorig, since there's no point in making the
969 bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
971 /* Finally ready to build the plan node */
972 scan_plan = make_bitmap_heapscan(tlist,
978 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
979 /* use the indexscan-specific rows estimate, not the parent rel's */
980 scan_plan->scan.plan.plan_rows = best_path->rows;
986 * Given a bitmapqual tree, generate the Plan tree that implements it
988 * As byproducts, we also return in *qual and *indexqual the qual lists
989 * (in implicit-AND form, without RestrictInfos) describing the original index
990 * conditions and the generated indexqual conditions. The latter is made to
991 * exclude lossy index operators.
993 * Note: if you find yourself changing this, you probably need to change
994 * make_restrictinfo_from_bitmapqual too.
997 create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual,
998 List **qual, List **indexqual)
1002 if (IsA(bitmapqual, BitmapAndPath))
1004 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
1005 List *subplans = NIL;
1006 List *subquals = NIL;
1007 List *subindexquals = NIL;
1011 * There may well be redundant quals among the subplans, since a
1012 * top-level WHERE qual might have gotten used to form several
1013 * different index quals. We don't try exceedingly hard to
1014 * eliminate redundancies, but we do eliminate obvious duplicates
1015 * by using list_concat_unique.
1017 foreach(l, apath->bitmapquals)
1023 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1024 &subqual, &subindexqual);
1025 subplans = lappend(subplans, subplan);
1026 subquals = list_concat_unique(subquals, subqual);
1027 subindexquals = list_concat_unique(subindexquals, subindexqual);
1029 plan = (Plan *) make_bitmap_and(subplans);
1030 plan->startup_cost = apath->path.startup_cost;
1031 plan->total_cost = apath->path.total_cost;
1033 clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
1034 plan->plan_width = 0; /* meaningless */
1036 *indexqual = subindexquals;
1038 else if (IsA(bitmapqual, BitmapOrPath))
1040 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
1041 List *subplans = NIL;
1042 List *subquals = NIL;
1043 List *subindexquals = NIL;
1044 bool const_true_subqual = false;
1045 bool const_true_subindexqual = false;
1049 * Here, we only detect qual-free subplans. A qual-free subplan would
1050 * cause us to generate "... OR true ..." which we may as well reduce
1051 * to just "true". We do not try to eliminate redundant subclauses
1052 * because (a) it's not as likely as in the AND case, and (b) we might
1053 * well be working with hundreds or even thousands of OR conditions,
1054 * perhaps from a long IN list. The performance of list_append_unique
1055 * would be unacceptable.
1057 foreach(l, opath->bitmapquals)
1063 subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
1064 &subqual, &subindexqual);
1065 subplans = lappend(subplans, subplan);
1067 const_true_subqual = true;
1068 else if (!const_true_subqual)
1069 subquals = lappend(subquals,
1070 make_ands_explicit(subqual));
1071 if (subindexqual == NIL)
1072 const_true_subindexqual = true;
1073 else if (!const_true_subindexqual)
1074 subindexquals = lappend(subindexquals,
1075 make_ands_explicit(subindexqual));
1077 plan = (Plan *) make_bitmap_or(subplans);
1078 plan->startup_cost = opath->path.startup_cost;
1079 plan->total_cost = opath->path.total_cost;
1081 clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
1082 plan->plan_width = 0; /* meaningless */
1084 * If there were constant-TRUE subquals, the OR reduces to constant
1085 * TRUE. Also, avoid generating one-element ORs, which could happen
1086 * due to redundancy elimination.
1088 if (const_true_subqual)
1090 else if (list_length(subquals) <= 1)
1093 *qual = list_make1(make_orclause(subquals));
1094 if (const_true_subindexqual)
1096 else if (list_length(subindexquals) <= 1)
1097 *indexqual = subindexquals;
1099 *indexqual = list_make1(make_orclause(subindexquals));
1101 else if (IsA(bitmapqual, IndexPath))
1103 IndexPath *ipath = (IndexPath *) bitmapqual;
1105 List *nonlossy_clauses;
1107 /* Use the regular indexscan plan build machinery... */
1108 iscan = create_indexscan_plan(root, ipath, NIL, NIL,
1110 /* then convert to a bitmap indexscan */
1111 plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
1114 iscan->indexqualorig,
1115 iscan->indexstrategy,
1116 iscan->indexsubtype);
1117 plan->startup_cost = 0.0;
1118 plan->total_cost = ipath->indextotalcost;
1120 clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
1121 plan->plan_width = 0; /* meaningless */
1122 *qual = get_actual_clauses(ipath->indexclauses);
1123 *indexqual = get_actual_clauses(nonlossy_clauses);
1127 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
1128 plan = NULL; /* keep compiler quiet */
1135 * create_tidscan_plan
1136 * Returns a tidscan plan for the base relation scanned by 'best_path'
1137 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1140 create_tidscan_plan(PlannerInfo *root, TidPath *best_path,
1141 List *tlist, List *scan_clauses)
1144 Index scan_relid = best_path->path.parent->relid;
1146 /* it should be a base rel... */
1147 Assert(scan_relid > 0);
1148 Assert(best_path->path.parent->rtekind == RTE_RELATION);
1150 /* Reduce RestrictInfo list to bare expressions */
1151 scan_clauses = get_actual_clauses(scan_clauses);
1153 /* Sort clauses into best execution order */
1154 scan_clauses = order_qual_clauses(root, scan_clauses);
1156 scan_plan = make_tidscan(tlist,
1159 best_path->tideval);
1161 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
1167 * create_subqueryscan_plan
1168 * Returns a subqueryscan plan for the base relation scanned by 'best_path'
1169 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1171 static SubqueryScan *
1172 create_subqueryscan_plan(PlannerInfo *root, Path *best_path,
1173 List *tlist, List *scan_clauses)
1175 SubqueryScan *scan_plan;
1176 Index scan_relid = best_path->parent->relid;
1178 /* it should be a subquery base rel... */
1179 Assert(scan_relid > 0);
1180 Assert(best_path->parent->rtekind == RTE_SUBQUERY);
1182 /* Reduce RestrictInfo list to bare expressions */
1183 scan_clauses = get_actual_clauses(scan_clauses);
1185 /* Sort clauses into best execution order */
1186 scan_clauses = order_qual_clauses(root, scan_clauses);
1188 scan_plan = make_subqueryscan(tlist,
1191 best_path->parent->subplan);
1193 copy_path_costsize(&scan_plan->scan.plan, best_path);
1199 * create_functionscan_plan
1200 * Returns a functionscan plan for the base relation scanned by 'best_path'
1201 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
1203 static FunctionScan *
1204 create_functionscan_plan(PlannerInfo *root, Path *best_path,
1205 List *tlist, List *scan_clauses)
1207 FunctionScan *scan_plan;
1208 Index scan_relid = best_path->parent->relid;
1210 /* it should be a function base rel... */
1211 Assert(scan_relid > 0);
1212 Assert(best_path->parent->rtekind == RTE_FUNCTION);
1214 /* Reduce RestrictInfo list to bare expressions */
1215 scan_clauses = get_actual_clauses(scan_clauses);
1217 /* Sort clauses into best execution order */
1218 scan_clauses = order_qual_clauses(root, scan_clauses);
1220 scan_plan = make_functionscan(tlist, scan_clauses, scan_relid);
1222 copy_path_costsize(&scan_plan->scan.plan, best_path);
1227 /*****************************************************************************
1231 *****************************************************************************/
1234 create_nestloop_plan(PlannerInfo *root,
1235 NestPath *best_path,
1239 List *tlist = build_relation_tlist(best_path->path.parent);
1240 List *joinrestrictclauses = best_path->joinrestrictinfo;
1243 NestLoop *join_plan;
1245 if (IsA(best_path->innerjoinpath, IndexPath))
1248 * An index is being used to reduce the number of tuples scanned
1249 * in the inner relation. If there are join clauses being used
1250 * with the index, we may remove those join clauses from the list
1251 * of clauses that have to be checked as qpquals at the join node.
1253 * We can also remove any join clauses that are redundant with those
1254 * being used in the index scan; prior redundancy checks will not
1255 * have caught this case because the join clauses would never have
1256 * been put in the same joininfo list.
1258 * We can skip this if the index path is an ordinary indexpath and
1259 * not a special innerjoin path.
1261 IndexPath *innerpath = (IndexPath *) best_path->innerjoinpath;
1263 if (innerpath->isjoininner)
1265 joinrestrictclauses =
1266 select_nonredundant_join_clauses(root,
1267 joinrestrictclauses,
1268 innerpath->indexclauses,
1269 IS_OUTER_JOIN(best_path->jointype));
1272 else if (IsA(best_path->innerjoinpath, BitmapHeapPath))
1275 * Same deal for bitmapped index scans.
1277 * Note: both here and above, we ignore any implicit index restrictions
1278 * associated with the use of partial indexes. This is OK because
1279 * we're only trying to prove we can dispense with some join quals;
1280 * failing to prove that doesn't result in an incorrect plan. It is
1281 * the right way to proceed because adding more quals to the stuff
1282 * we got from the original query would just make it harder to detect
1285 BitmapHeapPath *innerpath = (BitmapHeapPath *) best_path->innerjoinpath;
1287 if (innerpath->isjoininner)
1289 List *bitmapclauses;
1292 make_restrictinfo_from_bitmapqual(innerpath->bitmapqual,
1295 joinrestrictclauses =
1296 select_nonredundant_join_clauses(root,
1297 joinrestrictclauses,
1299 IS_OUTER_JOIN(best_path->jointype));
1303 /* Get the join qual clauses (in plain expression form) */
1304 if (IS_OUTER_JOIN(best_path->jointype))
1306 get_actual_join_clauses(joinrestrictclauses,
1307 &joinclauses, &otherclauses);
1311 /* We can treat all clauses alike for an inner join */
1312 joinclauses = get_actual_clauses(joinrestrictclauses);
1316 /* Sort clauses into best execution order */
1317 joinclauses = order_qual_clauses(root, joinclauses);
1318 otherclauses = order_qual_clauses(root, otherclauses);
1320 join_plan = make_nestloop(tlist,
1325 best_path->jointype);
1327 copy_path_costsize(&join_plan->join.plan, &best_path->path);
1333 create_mergejoin_plan(PlannerInfo *root,
1334 MergePath *best_path,
1338 List *tlist = build_relation_tlist(best_path->jpath.path.parent);
1342 MergeJoin *join_plan;
1344 /* Get the join qual clauses (in plain expression form) */
1345 if (IS_OUTER_JOIN(best_path->jpath.jointype))
1347 get_actual_join_clauses(best_path->jpath.joinrestrictinfo,
1348 &joinclauses, &otherclauses);
1352 /* We can treat all clauses alike for an inner join */
1353 joinclauses = get_actual_clauses(best_path->jpath.joinrestrictinfo);
1358 * Remove the mergeclauses from the list of join qual clauses, leaving
1359 * the list of quals that must be checked as qpquals.
1361 mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
1362 joinclauses = list_difference(joinclauses, mergeclauses);
1365 * Rearrange mergeclauses, if needed, so that the outer variable is
1366 * always on the left.
1368 mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
1369 best_path->jpath.outerjoinpath->parent->relids);
1371 /* Sort clauses into best execution order */
1372 /* NB: do NOT reorder the mergeclauses */
1373 joinclauses = order_qual_clauses(root, joinclauses);
1374 otherclauses = order_qual_clauses(root, otherclauses);
1377 * Create explicit sort nodes for the outer and inner join paths if
1378 * necessary. The sort cost was already accounted for in the path.
1379 * Make sure there are no excess columns in the inputs if sorting.
1381 if (best_path->outersortkeys)
1383 disuse_physical_tlist(outer_plan, best_path->jpath.outerjoinpath);
1384 outer_plan = (Plan *)
1385 make_sort_from_pathkeys(root,
1387 best_path->outersortkeys);
1390 if (best_path->innersortkeys)
1392 disuse_physical_tlist(inner_plan, best_path->jpath.innerjoinpath);
1393 inner_plan = (Plan *)
1394 make_sort_from_pathkeys(root,
1396 best_path->innersortkeys);
1400 * Now we can build the mergejoin node.
1402 join_plan = make_mergejoin(tlist,
1408 best_path->jpath.jointype);
1410 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
1416 create_hashjoin_plan(PlannerInfo *root,
1417 HashPath *best_path,
1421 List *tlist = build_relation_tlist(best_path->jpath.path.parent);
1425 HashJoin *join_plan;
1428 /* Get the join qual clauses (in plain expression form) */
1429 if (IS_OUTER_JOIN(best_path->jpath.jointype))
1431 get_actual_join_clauses(best_path->jpath.joinrestrictinfo,
1432 &joinclauses, &otherclauses);
1436 /* We can treat all clauses alike for an inner join */
1437 joinclauses = get_actual_clauses(best_path->jpath.joinrestrictinfo);
1442 * Remove the hashclauses from the list of join qual clauses, leaving
1443 * the list of quals that must be checked as qpquals.
1445 hashclauses = get_actual_clauses(best_path->path_hashclauses);
1446 joinclauses = list_difference(joinclauses, hashclauses);
1449 * Rearrange hashclauses, if needed, so that the outer variable is
1450 * always on the left.
1452 hashclauses = get_switched_clauses(best_path->path_hashclauses,
1453 best_path->jpath.outerjoinpath->parent->relids);
1455 /* Sort clauses into best execution order */
1456 joinclauses = order_qual_clauses(root, joinclauses);
1457 otherclauses = order_qual_clauses(root, otherclauses);
1458 hashclauses = order_qual_clauses(root, hashclauses);
1460 /* We don't want any excess columns in the hashed tuples */
1461 disuse_physical_tlist(inner_plan, best_path->jpath.innerjoinpath);
1464 * Build the hash node and hash join node.
1466 hash_plan = make_hash(inner_plan);
1467 join_plan = make_hashjoin(tlist,
1473 best_path->jpath.jointype);
1475 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
1481 /*****************************************************************************
1483 * SUPPORTING ROUTINES
1485 *****************************************************************************/
1488 * fix_indexqual_references
1489 * Adjust indexqual clauses to the form the executor's indexqual
1490 * machinery needs, and check for recheckable (lossy) index conditions.
1492 * We have five tasks here:
1493 * * Remove RestrictInfo nodes from the input clauses.
1494 * * Index keys must be represented by Var nodes with varattno set to the
1495 * index's attribute number, not the attribute number in the original rel.
1496 * * If the index key is on the right, commute the clause to put it on the
1498 * * We must construct lists of operator strategy numbers and subtypes
1499 * for the top-level operators of each index clause.
1500 * * We must detect any lossy index operators. The API is that we return
1501 * a list of the input clauses whose operators are NOT lossy.
1503 * fixed_indexquals receives a modified copy of the indexquals list --- the
1504 * original is not changed. Note also that the copy shares no substructure
1505 * with the original; this is needed in case there is a subplan in it (we need
1506 * two separate copies of the subplan tree, or things will go awry).
1508 * nonlossy_indexquals receives a list of the original input clauses (with
1509 * RestrictInfos) that contain non-lossy operators.
1511 * indexstrategy receives an integer list of strategy numbers.
1512 * indexsubtype receives an OID list of strategy subtypes.
1515 fix_indexqual_references(List *indexquals, IndexPath *index_path,
1516 List **fixed_indexquals,
1517 List **nonlossy_indexquals,
1518 List **indexstrategy,
1519 List **indexsubtype)
1521 IndexOptInfo *index = index_path->indexinfo;
1524 *fixed_indexquals = NIL;
1525 *nonlossy_indexquals = NIL;
1526 *indexstrategy = NIL;
1527 *indexsubtype = NIL;
1530 * For each qual clause, commute if needed to put the indexkey operand on
1531 * the left, and then fix its varattno. (We do not need to change the
1532 * other side of the clause.) Then determine the operator's strategy
1533 * number and subtype number, and check for lossy index behavior.
1535 foreach(l, indexquals)
1537 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1545 Assert(IsA(rinfo, RestrictInfo));
1546 clause = (OpExpr *) rinfo->clause;
1547 if (!IsA(clause, OpExpr) ||
1548 list_length(clause->args) != 2)
1549 elog(ERROR, "indexqual clause is not binary opclause");
1552 * Make a copy that will become the fixed clause.
1554 * We used to try to do a shallow copy here, but that fails if there
1555 * is a subplan in the arguments of the opclause. So just do a
1558 newclause = (OpExpr *) copyObject((Node *) clause);
1561 * Check to see if the indexkey is on the right; if so, commute
1562 * the clause. The indexkey should be the side that refers to
1563 * (only) the base relation.
1565 if (!bms_equal(rinfo->left_relids, index->rel->relids))
1566 CommuteClause(newclause);
1569 * Now, determine which index attribute this is, change the
1570 * indexkey operand as needed, and get the index opclass.
1572 linitial(newclause->args) =
1573 fix_indexqual_operand(linitial(newclause->args),
1577 *fixed_indexquals = lappend(*fixed_indexquals, newclause);
1580 * Look up the (possibly commuted) operator in the operator class
1581 * to get its strategy numbers and the recheck indicator. This
1582 * also double-checks that we found an operator matching the
1585 get_op_opclass_properties(newclause->opno, opclass,
1586 &stratno, &stratsubtype, &recheck);
1588 *indexstrategy = lappend_int(*indexstrategy, stratno);
1589 *indexsubtype = lappend_oid(*indexsubtype, stratsubtype);
1591 /* If it's not lossy, add to nonlossy_indexquals */
1593 *nonlossy_indexquals = lappend(*nonlossy_indexquals, rinfo);
1598 fix_indexqual_operand(Node *node, IndexOptInfo *index, Oid *opclass)
1601 * We represent index keys by Var nodes having the varno of the base
1602 * table but varattno equal to the index's attribute number (index
1603 * column position). This is a bit hokey ... would be cleaner to use
1604 * a special-purpose node type that could not be mistaken for a
1605 * regular Var. But it will do for now.
1609 ListCell *indexpr_item;
1612 * Remove any binary-compatible relabeling of the indexkey
1614 if (IsA(node, RelabelType))
1615 node = (Node *) ((RelabelType *) node)->arg;
1617 if (IsA(node, Var) &&
1618 ((Var *) node)->varno == index->rel->relid)
1620 /* Try to match against simple index columns */
1621 int varatt = ((Var *) node)->varattno;
1625 for (pos = 0; pos < index->ncolumns; pos++)
1627 if (index->indexkeys[pos] == varatt)
1629 result = (Var *) copyObject(node);
1630 result->varattno = pos + 1;
1631 /* return the correct opclass, too */
1632 *opclass = index->classlist[pos];
1633 return (Node *) result;
1639 /* Try to match against index expressions */
1640 indexpr_item = list_head(index->indexprs);
1641 for (pos = 0; pos < index->ncolumns; pos++)
1643 if (index->indexkeys[pos] == 0)
1647 if (indexpr_item == NULL)
1648 elog(ERROR, "too few entries in indexprs list");
1649 indexkey = (Node *) lfirst(indexpr_item);
1650 if (indexkey && IsA(indexkey, RelabelType))
1651 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
1652 if (equal(node, indexkey))
1655 result = makeVar(index->rel->relid, pos + 1,
1656 exprType(lfirst(indexpr_item)), -1,
1658 /* return the correct opclass, too */
1659 *opclass = index->classlist[pos];
1660 return (Node *) result;
1662 indexpr_item = lnext(indexpr_item);
1667 elog(ERROR, "node is not an index attribute");
1668 *opclass = InvalidOid; /* keep compiler quiet */
1673 * get_switched_clauses
1674 * Given a list of merge or hash joinclauses (as RestrictInfo nodes),
1675 * extract the bare clauses, and rearrange the elements within the
1676 * clauses, if needed, so the outer join variable is on the left and
1677 * the inner is on the right. The original data structure is not touched;
1678 * a modified list is returned.
1681 get_switched_clauses(List *clauses, Relids outerrelids)
1688 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(l);
1689 OpExpr *clause = (OpExpr *) restrictinfo->clause;
1691 Assert(is_opclause(clause));
1692 if (bms_is_subset(restrictinfo->right_relids, outerrelids))
1695 * Duplicate just enough of the structure to allow commuting
1696 * the clause without changing the original list. Could use
1697 * copyObject, but a complete deep copy is overkill.
1699 OpExpr *temp = makeNode(OpExpr);
1701 temp->opno = clause->opno;
1702 temp->opfuncid = InvalidOid;
1703 temp->opresulttype = clause->opresulttype;
1704 temp->opretset = clause->opretset;
1705 temp->args = list_copy(clause->args);
1706 /* Commute it --- note this modifies the temp node in-place. */
1707 CommuteClause(temp);
1708 t_list = lappend(t_list, temp);
1711 t_list = lappend(t_list, clause);
1717 * order_qual_clauses
1718 * Given a list of qual clauses that will all be evaluated at the same
1719 * plan node, sort the list into the order we want to check the quals
1722 * Ideally the order should be driven by a combination of execution cost and
1723 * selectivity, but unfortunately we have so little information about
1724 * execution cost of operators that it's really hard to do anything smart.
1725 * For now, we just move any quals that contain SubPlan references (but not
1726 * InitPlan references) to the end of the list.
1729 order_qual_clauses(PlannerInfo *root, List *clauses)
1735 /* No need to work hard if the query is subselect-free */
1736 if (!root->parse->hasSubLinks)
1743 Node *clause = (Node *) lfirst(l);
1745 if (contain_subplans(clause))
1746 withsubplans = lappend(withsubplans, clause);
1748 nosubplans = lappend(nosubplans, clause);
1751 return list_concat(nosubplans, withsubplans);
1755 * Copy cost and size info from a Path node to the Plan node created from it.
1756 * The executor won't use this info, but it's needed by EXPLAIN.
1759 copy_path_costsize(Plan *dest, Path *src)
1763 dest->startup_cost = src->startup_cost;
1764 dest->total_cost = src->total_cost;
1765 dest->plan_rows = src->parent->rows;
1766 dest->plan_width = src->parent->width;
1770 dest->startup_cost = 0;
1771 dest->total_cost = 0;
1772 dest->plan_rows = 0;
1773 dest->plan_width = 0;
1778 * Copy cost and size info from a lower plan node to an inserted node.
1779 * This is not critical, since the decisions have already been made,
1780 * but it helps produce more reasonable-looking EXPLAIN output.
1781 * (Some callers alter the info after copying it.)
1784 copy_plan_costsize(Plan *dest, Plan *src)
1788 dest->startup_cost = src->startup_cost;
1789 dest->total_cost = src->total_cost;
1790 dest->plan_rows = src->plan_rows;
1791 dest->plan_width = src->plan_width;
1795 dest->startup_cost = 0;
1796 dest->total_cost = 0;
1797 dest->plan_rows = 0;
1798 dest->plan_width = 0;
1803 /*****************************************************************************
1805 * PLAN NODE BUILDING ROUTINES
1807 * Some of these are exported because they are called to build plan nodes
1808 * in contexts where we're not deriving the plan node from a path node.
1810 *****************************************************************************/
1813 make_seqscan(List *qptlist,
1817 SeqScan *node = makeNode(SeqScan);
1818 Plan *plan = &node->plan;
1820 /* cost should be inserted by caller */
1821 plan->targetlist = qptlist;
1822 plan->qual = qpqual;
1823 plan->lefttree = NULL;
1824 plan->righttree = NULL;
1825 node->scanrelid = scanrelid;
1831 make_indexscan(List *qptlist,
1836 List *indexqualorig,
1837 List *indexstrategy,
1839 ScanDirection indexscandir)
1841 IndexScan *node = makeNode(IndexScan);
1842 Plan *plan = &node->scan.plan;
1844 /* cost should be inserted by caller */
1845 plan->targetlist = qptlist;
1846 plan->qual = qpqual;
1847 plan->lefttree = NULL;
1848 plan->righttree = NULL;
1849 node->scan.scanrelid = scanrelid;
1850 node->indexid = indexid;
1851 node->indexqual = indexqual;
1852 node->indexqualorig = indexqualorig;
1853 node->indexstrategy = indexstrategy;
1854 node->indexsubtype = indexsubtype;
1855 node->indexorderdir = indexscandir;
1860 static BitmapIndexScan *
1861 make_bitmap_indexscan(Index scanrelid,
1864 List *indexqualorig,
1865 List *indexstrategy,
1868 BitmapIndexScan *node = makeNode(BitmapIndexScan);
1869 Plan *plan = &node->scan.plan;
1871 /* cost should be inserted by caller */
1872 plan->targetlist = NIL; /* not used */
1873 plan->qual = NIL; /* not used */
1874 plan->lefttree = NULL;
1875 plan->righttree = NULL;
1876 node->scan.scanrelid = scanrelid;
1877 node->indexid = indexid;
1878 node->indexqual = indexqual;
1879 node->indexqualorig = indexqualorig;
1880 node->indexstrategy = indexstrategy;
1881 node->indexsubtype = indexsubtype;
1886 static BitmapHeapScan *
1887 make_bitmap_heapscan(List *qptlist,
1890 List *bitmapqualorig,
1893 BitmapHeapScan *node = makeNode(BitmapHeapScan);
1894 Plan *plan = &node->scan.plan;
1896 /* cost should be inserted by caller */
1897 plan->targetlist = qptlist;
1898 plan->qual = qpqual;
1899 plan->lefttree = lefttree;
1900 plan->righttree = NULL;
1901 node->scan.scanrelid = scanrelid;
1902 node->bitmapqualorig = bitmapqualorig;
1908 make_tidscan(List *qptlist,
1913 TidScan *node = makeNode(TidScan);
1914 Plan *plan = &node->scan.plan;
1916 /* cost should be inserted by caller */
1917 plan->targetlist = qptlist;
1918 plan->qual = qpqual;
1919 plan->lefttree = NULL;
1920 plan->righttree = NULL;
1921 node->scan.scanrelid = scanrelid;
1922 node->tideval = tideval;
1928 make_subqueryscan(List *qptlist,
1933 SubqueryScan *node = makeNode(SubqueryScan);
1934 Plan *plan = &node->scan.plan;
1937 * Cost is figured here for the convenience of prepunion.c. Note this
1938 * is only correct for the case where qpqual is empty; otherwise
1939 * caller should overwrite cost with a better estimate.
1941 copy_plan_costsize(plan, subplan);
1942 plan->total_cost += cpu_tuple_cost * subplan->plan_rows;
1944 plan->targetlist = qptlist;
1945 plan->qual = qpqual;
1946 plan->lefttree = NULL;
1947 plan->righttree = NULL;
1948 node->scan.scanrelid = scanrelid;
1949 node->subplan = subplan;
1954 static FunctionScan *
1955 make_functionscan(List *qptlist,
1959 FunctionScan *node = makeNode(FunctionScan);
1960 Plan *plan = &node->scan.plan;
1962 /* cost should be inserted by caller */
1963 plan->targetlist = qptlist;
1964 plan->qual = qpqual;
1965 plan->lefttree = NULL;
1966 plan->righttree = NULL;
1967 node->scan.scanrelid = scanrelid;
1973 make_append(List *appendplans, bool isTarget, List *tlist)
1975 Append *node = makeNode(Append);
1976 Plan *plan = &node->plan;
1980 * Compute cost as sum of subplan costs. We charge nothing extra for
1981 * the Append itself, which perhaps is too optimistic, but since it
1982 * doesn't do any selection or projection, it is a pretty cheap node.
1984 plan->startup_cost = 0;
1985 plan->total_cost = 0;
1986 plan->plan_rows = 0;
1987 plan->plan_width = 0;
1988 foreach(subnode, appendplans)
1990 Plan *subplan = (Plan *) lfirst(subnode);
1992 if (subnode == list_head(appendplans)) /* first node? */
1993 plan->startup_cost = subplan->startup_cost;
1994 plan->total_cost += subplan->total_cost;
1995 plan->plan_rows += subplan->plan_rows;
1996 if (plan->plan_width < subplan->plan_width)
1997 plan->plan_width = subplan->plan_width;
2000 plan->targetlist = tlist;
2002 plan->lefttree = NULL;
2003 plan->righttree = NULL;
2004 node->appendplans = appendplans;
2005 node->isTarget = isTarget;
2011 make_bitmap_and(List *bitmapplans)
2013 BitmapAnd *node = makeNode(BitmapAnd);
2014 Plan *plan = &node->plan;
2016 /* cost should be inserted by caller */
2017 plan->targetlist = NIL;
2019 plan->lefttree = NULL;
2020 plan->righttree = NULL;
2021 node->bitmapplans = bitmapplans;
2027 make_bitmap_or(List *bitmapplans)
2029 BitmapOr *node = makeNode(BitmapOr);
2030 Plan *plan = &node->plan;
2032 /* cost should be inserted by caller */
2033 plan->targetlist = NIL;
2035 plan->lefttree = NULL;
2036 plan->righttree = NULL;
2037 node->bitmapplans = bitmapplans;
2043 make_nestloop(List *tlist,
2050 NestLoop *node = makeNode(NestLoop);
2051 Plan *plan = &node->join.plan;
2053 /* cost should be inserted by caller */
2054 plan->targetlist = tlist;
2055 plan->qual = otherclauses;
2056 plan->lefttree = lefttree;
2057 plan->righttree = righttree;
2058 node->join.jointype = jointype;
2059 node->join.joinqual = joinclauses;
2065 make_hashjoin(List *tlist,
2073 HashJoin *node = makeNode(HashJoin);
2074 Plan *plan = &node->join.plan;
2076 /* cost should be inserted by caller */
2077 plan->targetlist = tlist;
2078 plan->qual = otherclauses;
2079 plan->lefttree = lefttree;
2080 plan->righttree = righttree;
2081 node->hashclauses = hashclauses;
2082 node->join.jointype = jointype;
2083 node->join.joinqual = joinclauses;
2089 make_hash(Plan *lefttree)
2091 Hash *node = makeNode(Hash);
2092 Plan *plan = &node->plan;
2094 copy_plan_costsize(plan, lefttree);
2097 * For plausibility, make startup & total costs equal total cost of
2098 * input plan; this only affects EXPLAIN display not decisions.
2100 plan->startup_cost = plan->total_cost;
2101 plan->targetlist = copyObject(lefttree->targetlist);
2103 plan->lefttree = lefttree;
2104 plan->righttree = NULL;
2110 make_mergejoin(List *tlist,
2118 MergeJoin *node = makeNode(MergeJoin);
2119 Plan *plan = &node->join.plan;
2121 /* cost should be inserted by caller */
2122 plan->targetlist = tlist;
2123 plan->qual = otherclauses;
2124 plan->lefttree = lefttree;
2125 plan->righttree = righttree;
2126 node->mergeclauses = mergeclauses;
2127 node->join.jointype = jointype;
2128 node->join.joinqual = joinclauses;
2134 * make_sort --- basic routine to build a Sort plan node
2136 * Caller must have built the sortColIdx and sortOperators arrays already.
2139 make_sort(PlannerInfo *root, Plan *lefttree, int numCols,
2140 AttrNumber *sortColIdx, Oid *sortOperators)
2142 Sort *node = makeNode(Sort);
2143 Plan *plan = &node->plan;
2144 Path sort_path; /* dummy for result of cost_sort */
2146 copy_plan_costsize(plan, lefttree); /* only care about copying size */
2147 cost_sort(&sort_path, root, NIL,
2148 lefttree->total_cost,
2149 lefttree->plan_rows,
2150 lefttree->plan_width);
2151 plan->startup_cost = sort_path.startup_cost;
2152 plan->total_cost = sort_path.total_cost;
2153 plan->targetlist = copyObject(lefttree->targetlist);
2155 plan->lefttree = lefttree;
2156 plan->righttree = NULL;
2157 node->numCols = numCols;
2158 node->sortColIdx = sortColIdx;
2159 node->sortOperators = sortOperators;
2165 * add_sort_column --- utility subroutine for building sort info arrays
2167 * We need this routine because the same column might be selected more than
2168 * once as a sort key column; if so, the extra mentions are redundant.
2170 * Caller is assumed to have allocated the arrays large enough for the
2171 * max possible number of columns. Return value is the new column count.
2174 add_sort_column(AttrNumber colIdx, Oid sortOp,
2175 int numCols, AttrNumber *sortColIdx, Oid *sortOperators)
2179 for (i = 0; i < numCols; i++)
2181 if (sortColIdx[i] == colIdx)
2183 /* Already sorting by this col, so extra sort key is useless */
2188 /* Add the column */
2189 sortColIdx[numCols] = colIdx;
2190 sortOperators[numCols] = sortOp;
2195 * make_sort_from_pathkeys
2196 * Create sort plan to sort according to given pathkeys
2198 * 'lefttree' is the node which yields input tuples
2199 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
2201 * We must convert the pathkey information into arrays of sort key column
2202 * numbers and sort operator OIDs.
2204 * If the pathkeys include expressions that aren't simple Vars, we will
2205 * usually need to add resjunk items to the input plan's targetlist to
2206 * compute these expressions (since the Sort node itself won't do it).
2207 * If the input plan type isn't one that can do projections, this means
2208 * adding a Result node just to do the projection.
2211 make_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys)
2213 List *tlist = lefttree->targetlist;
2216 AttrNumber *sortColIdx;
2220 * We will need at most list_length(pathkeys) sort columns; possibly
2223 numsortkeys = list_length(pathkeys);
2224 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
2225 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
2229 foreach(i, pathkeys)
2231 List *keysublist = (List *) lfirst(i);
2232 PathKeyItem *pathkey = NULL;
2233 TargetEntry *tle = NULL;
2237 * We can sort by any one of the sort key items listed in this
2238 * sublist. For now, we take the first one that corresponds to an
2239 * available Var in the tlist. If there isn't any, use the first
2240 * one that is an expression in the input's vars.
2242 * XXX if we have a choice, is there any way of figuring out which
2243 * might be cheapest to execute? (For example, int4lt is likely
2244 * much cheaper to execute than numericlt, but both might appear
2245 * in the same pathkey sublist...) Not clear that we ever will
2246 * have a choice in practice, so it may not matter.
2248 foreach(j, keysublist)
2250 pathkey = (PathKeyItem *) lfirst(j);
2251 Assert(IsA(pathkey, PathKeyItem));
2252 tle = tlist_member(pathkey->key, tlist);
2258 /* No matching Var; look for a computable expression */
2259 foreach(j, keysublist)
2264 pathkey = (PathKeyItem *) lfirst(j);
2265 exprvars = pull_var_clause(pathkey->key, false);
2266 foreach(k, exprvars)
2268 if (!tlist_member(lfirst(k), tlist))
2271 list_free(exprvars);
2273 break; /* found usable expression */
2276 elog(ERROR, "could not find pathkey item to sort");
2279 * Do we need to insert a Result node?
2281 if (!is_projection_capable_plan(lefttree))
2283 tlist = copyObject(tlist);
2284 lefttree = (Plan *) make_result(tlist, NULL, lefttree);
2288 * Add resjunk entry to input's tlist
2290 tle = makeTargetEntry((Expr *) pathkey->key,
2291 list_length(tlist) + 1,
2294 tlist = lappend(tlist, tle);
2295 lefttree->targetlist = tlist; /* just in case NIL before */
2299 * The column might already be selected as a sort key, if the
2300 * pathkeys contain duplicate entries. (This can happen in
2301 * scenarios where multiple mergejoinable clauses mention the same
2302 * var, for example.) So enter it only once in the sort arrays.
2304 numsortkeys = add_sort_column(tle->resno, pathkey->sortop,
2305 numsortkeys, sortColIdx, sortOperators);
2308 Assert(numsortkeys > 0);
2310 return make_sort(root, lefttree, numsortkeys,
2311 sortColIdx, sortOperators);
2315 * make_sort_from_sortclauses
2316 * Create sort plan to sort according to given sortclauses
2318 * 'sortcls' is a list of SortClauses
2319 * 'lefttree' is the node which yields input tuples
2322 make_sort_from_sortclauses(PlannerInfo *root, List *sortcls, Plan *lefttree)
2324 List *sub_tlist = lefttree->targetlist;
2327 AttrNumber *sortColIdx;
2331 * We will need at most list_length(sortcls) sort columns; possibly
2334 numsortkeys = list_length(sortcls);
2335 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
2336 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
2342 SortClause *sortcl = (SortClause *) lfirst(l);
2343 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
2346 * Check for the possibility of duplicate order-by clauses --- the
2347 * parser should have removed 'em, but no point in sorting
2350 numsortkeys = add_sort_column(tle->resno, sortcl->sortop,
2351 numsortkeys, sortColIdx, sortOperators);
2354 Assert(numsortkeys > 0);
2356 return make_sort(root, lefttree, numsortkeys,
2357 sortColIdx, sortOperators);
2361 * make_sort_from_groupcols
2362 * Create sort plan to sort based on grouping columns
2364 * 'groupcls' is the list of GroupClauses
2365 * 'grpColIdx' gives the column numbers to use
2367 * This might look like it could be merged with make_sort_from_sortclauses,
2368 * but presently we *must* use the grpColIdx[] array to locate sort columns,
2369 * because the child plan's tlist is not marked with ressortgroupref info
2370 * appropriate to the grouping node. So, only the sortop is used from the
2371 * GroupClause entries.
2374 make_sort_from_groupcols(PlannerInfo *root,
2376 AttrNumber *grpColIdx,
2379 List *sub_tlist = lefttree->targetlist;
2383 AttrNumber *sortColIdx;
2387 * We will need at most list_length(groupcls) sort columns; possibly
2390 numsortkeys = list_length(groupcls);
2391 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
2392 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
2396 foreach(l, groupcls)
2398 GroupClause *grpcl = (GroupClause *) lfirst(l);
2399 TargetEntry *tle = get_tle_by_resno(sub_tlist, grpColIdx[grpno]);
2402 * Check for the possibility of duplicate group-by clauses --- the
2403 * parser should have removed 'em, but no point in sorting
2406 numsortkeys = add_sort_column(tle->resno, grpcl->sortop,
2407 numsortkeys, sortColIdx, sortOperators);
2411 Assert(numsortkeys > 0);
2413 return make_sort(root, lefttree, numsortkeys,
2414 sortColIdx, sortOperators);
2418 make_material(Plan *lefttree)
2420 Material *node = makeNode(Material);
2421 Plan *plan = &node->plan;
2423 /* cost should be inserted by caller */
2424 plan->targetlist = copyObject(lefttree->targetlist);
2426 plan->lefttree = lefttree;
2427 plan->righttree = NULL;
2433 * materialize_finished_plan: stick a Material node atop a completed plan
2435 * There are a couple of places where we want to attach a Material node
2436 * after completion of subquery_planner(). This currently requires hackery.
2437 * Since subquery_planner has already run SS_finalize_plan on the subplan
2438 * tree, we have to kluge up parameter lists for the Material node.
2439 * Possibly this could be fixed by postponing SS_finalize_plan processing
2440 * until setrefs.c is run?
2443 materialize_finished_plan(Plan *subplan)
2446 Path matpath; /* dummy for result of cost_material */
2448 matplan = (Plan *) make_material(subplan);
2451 cost_material(&matpath,
2452 subplan->total_cost,
2454 subplan->plan_width);
2455 matplan->startup_cost = matpath.startup_cost;
2456 matplan->total_cost = matpath.total_cost;
2457 matplan->plan_rows = subplan->plan_rows;
2458 matplan->plan_width = subplan->plan_width;
2460 /* parameter kluge --- see comments above */
2461 matplan->extParam = bms_copy(subplan->extParam);
2462 matplan->allParam = bms_copy(subplan->allParam);
2468 make_agg(PlannerInfo *root, List *tlist, List *qual,
2469 AggStrategy aggstrategy,
2470 int numGroupCols, AttrNumber *grpColIdx,
2471 long numGroups, int numAggs,
2474 Agg *node = makeNode(Agg);
2475 Plan *plan = &node->plan;
2476 Path agg_path; /* dummy for result of cost_agg */
2479 node->aggstrategy = aggstrategy;
2480 node->numCols = numGroupCols;
2481 node->grpColIdx = grpColIdx;
2482 node->numGroups = numGroups;
2484 copy_plan_costsize(plan, lefttree); /* only care about copying size */
2485 cost_agg(&agg_path, root,
2486 aggstrategy, numAggs,
2487 numGroupCols, numGroups,
2488 lefttree->startup_cost,
2489 lefttree->total_cost,
2490 lefttree->plan_rows);
2491 plan->startup_cost = agg_path.startup_cost;
2492 plan->total_cost = agg_path.total_cost;
2495 * We will produce a single output tuple if not grouping, and a tuple
2496 * per group otherwise.
2498 if (aggstrategy == AGG_PLAIN)
2499 plan->plan_rows = 1;
2501 plan->plan_rows = numGroups;
2504 * We also need to account for the cost of evaluation of the qual (ie,
2505 * the HAVING clause) and the tlist. Note that cost_qual_eval doesn't
2506 * charge anything for Aggref nodes; this is okay since they are
2507 * really comparable to Vars.
2509 * See notes in grouping_planner about why this routine and make_group
2510 * are the only ones in this file that worry about tlist eval cost.
2514 cost_qual_eval(&qual_cost, qual);
2515 plan->startup_cost += qual_cost.startup;
2516 plan->total_cost += qual_cost.startup;
2517 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2519 cost_qual_eval(&qual_cost, tlist);
2520 plan->startup_cost += qual_cost.startup;
2521 plan->total_cost += qual_cost.startup;
2522 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2525 plan->targetlist = tlist;
2526 plan->lefttree = lefttree;
2527 plan->righttree = NULL;
2533 make_group(PlannerInfo *root,
2537 AttrNumber *grpColIdx,
2541 Group *node = makeNode(Group);
2542 Plan *plan = &node->plan;
2543 Path group_path; /* dummy for result of cost_group */
2546 node->numCols = numGroupCols;
2547 node->grpColIdx = grpColIdx;
2549 copy_plan_costsize(plan, lefttree); /* only care about copying size */
2550 cost_group(&group_path, root,
2551 numGroupCols, numGroups,
2552 lefttree->startup_cost,
2553 lefttree->total_cost,
2554 lefttree->plan_rows);
2555 plan->startup_cost = group_path.startup_cost;
2556 plan->total_cost = group_path.total_cost;
2558 /* One output tuple per estimated result group */
2559 plan->plan_rows = numGroups;
2562 * We also need to account for the cost of evaluation of the qual (ie,
2563 * the HAVING clause) and the tlist.
2565 * XXX this double-counts the cost of evaluation of any expressions used
2566 * for grouping, since in reality those will have been evaluated at a
2567 * lower plan level and will only be copied by the Group node. Worth
2570 * See notes in grouping_planner about why this routine and make_agg are
2571 * the only ones in this file that worry about tlist eval cost.
2575 cost_qual_eval(&qual_cost, qual);
2576 plan->startup_cost += qual_cost.startup;
2577 plan->total_cost += qual_cost.startup;
2578 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2580 cost_qual_eval(&qual_cost, tlist);
2581 plan->startup_cost += qual_cost.startup;
2582 plan->total_cost += qual_cost.startup;
2583 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2586 plan->targetlist = tlist;
2587 plan->lefttree = lefttree;
2588 plan->righttree = NULL;
2594 * distinctList is a list of SortClauses, identifying the targetlist items
2595 * that should be considered by the Unique filter.
2598 make_unique(Plan *lefttree, List *distinctList)
2600 Unique *node = makeNode(Unique);
2601 Plan *plan = &node->plan;
2602 int numCols = list_length(distinctList);
2604 AttrNumber *uniqColIdx;
2607 copy_plan_costsize(plan, lefttree);
2610 * Charge one cpu_operator_cost per comparison per input tuple. We
2611 * assume all columns get compared at most of the tuples. (XXX
2612 * probably this is an overestimate.)
2614 plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols;
2617 * plan->plan_rows is left as a copy of the input subplan's plan_rows;
2618 * ie, we assume the filter removes nothing. The caller must alter
2619 * this if he has a better idea.
2622 plan->targetlist = copyObject(lefttree->targetlist);
2624 plan->lefttree = lefttree;
2625 plan->righttree = NULL;
2628 * convert SortClause list into array of attr indexes, as wanted by
2631 Assert(numCols > 0);
2632 uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
2634 foreach(slitem, distinctList)
2636 SortClause *sortcl = (SortClause *) lfirst(slitem);
2637 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
2639 uniqColIdx[keyno++] = tle->resno;
2642 node->numCols = numCols;
2643 node->uniqColIdx = uniqColIdx;
2649 * distinctList is a list of SortClauses, identifying the targetlist items
2650 * that should be considered by the SetOp filter.
2654 make_setop(SetOpCmd cmd, Plan *lefttree,
2655 List *distinctList, AttrNumber flagColIdx)
2657 SetOp *node = makeNode(SetOp);
2658 Plan *plan = &node->plan;
2659 int numCols = list_length(distinctList);
2661 AttrNumber *dupColIdx;
2664 copy_plan_costsize(plan, lefttree);
2667 * Charge one cpu_operator_cost per comparison per input tuple. We
2668 * assume all columns get compared at most of the tuples.
2670 plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols;
2673 * We make the unsupported assumption that there will be 10% as many
2674 * tuples out as in. Any way to do better?
2676 plan->plan_rows *= 0.1;
2677 if (plan->plan_rows < 1)
2678 plan->plan_rows = 1;
2680 plan->targetlist = copyObject(lefttree->targetlist);
2682 plan->lefttree = lefttree;
2683 plan->righttree = NULL;
2686 * convert SortClause list into array of attr indexes, as wanted by
2689 Assert(numCols > 0);
2690 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
2692 foreach(slitem, distinctList)
2694 SortClause *sortcl = (SortClause *) lfirst(slitem);
2695 TargetEntry *tle = get_sortgroupclause_tle(sortcl, plan->targetlist);
2697 dupColIdx[keyno++] = tle->resno;
2701 node->numCols = numCols;
2702 node->dupColIdx = dupColIdx;
2703 node->flagColIdx = flagColIdx;
2709 * Note: offset_est and count_est are passed in to save having to repeat
2710 * work already done to estimate the values of the limitOffset and limitCount
2711 * expressions. Their values are as returned by preprocess_limit (0 means
2712 * "not relevant", -1 means "couldn't estimate"). Keep the code below in sync
2713 * with that function!
2716 make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount,
2717 int offset_est, int count_est)
2719 Limit *node = makeNode(Limit);
2720 Plan *plan = &node->plan;
2722 copy_plan_costsize(plan, lefttree);
2725 * Adjust the output rows count and costs according to the offset/limit.
2726 * This is only a cosmetic issue if we are at top level, but if we are
2727 * building a subquery then it's important to report correct info to the
2730 * When the offset or count couldn't be estimated, use 10% of the
2731 * estimated number of rows emitted from the subplan.
2733 if (offset_est != 0)
2738 offset_rows = (double) offset_est;
2740 offset_rows = clamp_row_est(lefttree->plan_rows * 0.10);
2741 if (offset_rows > plan->plan_rows)
2742 offset_rows = plan->plan_rows;
2743 if (plan->plan_rows > 0)
2744 plan->startup_cost +=
2745 (plan->total_cost - plan->startup_cost)
2746 * offset_rows / plan->plan_rows;
2747 plan->plan_rows -= offset_rows;
2748 if (plan->plan_rows < 1)
2749 plan->plan_rows = 1;
2757 count_rows = (double) count_est;
2759 count_rows = clamp_row_est(lefttree->plan_rows * 0.10);
2760 if (count_rows > plan->plan_rows)
2761 count_rows = plan->plan_rows;
2762 if (plan->plan_rows > 0)
2763 plan->total_cost = plan->startup_cost +
2764 (plan->total_cost - plan->startup_cost)
2765 * count_rows / plan->plan_rows;
2766 plan->plan_rows = count_rows;
2767 if (plan->plan_rows < 1)
2768 plan->plan_rows = 1;
2771 plan->targetlist = copyObject(lefttree->targetlist);
2773 plan->lefttree = lefttree;
2774 plan->righttree = NULL;
2776 node->limitOffset = limitOffset;
2777 node->limitCount = limitCount;
2783 make_result(List *tlist,
2784 Node *resconstantqual,
2787 Result *node = makeNode(Result);
2788 Plan *plan = &node->plan;
2791 copy_plan_costsize(plan, subplan);
2794 plan->startup_cost = 0;
2795 plan->total_cost = cpu_tuple_cost;
2796 plan->plan_rows = 1; /* wrong if we have a set-valued function? */
2797 plan->plan_width = 0; /* XXX try to be smarter? */
2800 if (resconstantqual)
2804 cost_qual_eval(&qual_cost, (List *) resconstantqual);
2805 /* resconstantqual is evaluated once at startup */
2806 plan->startup_cost += qual_cost.startup + qual_cost.per_tuple;
2807 plan->total_cost += qual_cost.startup + qual_cost.per_tuple;
2810 plan->targetlist = tlist;
2812 plan->lefttree = subplan;
2813 plan->righttree = NULL;
2814 node->resconstantqual = resconstantqual;
2820 * is_projection_capable_plan
2821 * Check whether a given Plan node is able to do projection.
2824 is_projection_capable_plan(Plan *plan)
2826 /* Most plan types can project, so just list the ones that can't */
2827 switch (nodeTag(plan))