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-2002, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
13 * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/createplan.c,v 1.139 2003/05/06 00:20:32 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/paths.h"
26 #include "optimizer/planmain.h"
27 #include "optimizer/restrictinfo.h"
28 #include "optimizer/tlist.h"
29 #include "optimizer/var.h"
30 #include "parser/parse_clause.h"
31 #include "parser/parse_expr.h"
32 #include "utils/lsyscache.h"
33 #include "utils/syscache.h"
36 static Scan *create_scan_plan(Query *root, Path *best_path);
37 static bool use_physical_tlist(RelOptInfo *rel);
38 static void disuse_physical_tlist(Plan *plan, Path *path);
39 static Join *create_join_plan(Query *root, JoinPath *best_path);
40 static Append *create_append_plan(Query *root, AppendPath *best_path);
41 static Result *create_result_plan(Query *root, ResultPath *best_path);
42 static Material *create_material_plan(Query *root, MaterialPath *best_path);
43 static Plan *create_unique_plan(Query *root, UniquePath *best_path);
44 static SeqScan *create_seqscan_plan(Path *best_path, List *tlist,
46 static IndexScan *create_indexscan_plan(Query *root, IndexPath *best_path,
47 List *tlist, List *scan_clauses);
48 static TidScan *create_tidscan_plan(TidPath *best_path, List *tlist,
50 static SubqueryScan *create_subqueryscan_plan(Path *best_path,
51 List *tlist, List *scan_clauses);
52 static FunctionScan *create_functionscan_plan(Path *best_path,
53 List *tlist, List *scan_clauses);
54 static NestLoop *create_nestloop_plan(Query *root,
55 NestPath *best_path, List *tlist,
56 List *joinclauses, List *otherclauses,
57 Plan *outer_plan, Plan *inner_plan);
58 static MergeJoin *create_mergejoin_plan(Query *root,
59 MergePath *best_path, List *tlist,
60 List *joinclauses, List *otherclauses,
61 Plan *outer_plan, Plan *inner_plan);
62 static HashJoin *create_hashjoin_plan(Query *root,
63 HashPath *best_path, List *tlist,
64 List *joinclauses, List *otherclauses,
65 Plan *outer_plan, Plan *inner_plan);
66 static void fix_indxqual_references(List *indexquals, IndexPath *index_path,
67 List **fixed_indexquals,
68 List **recheck_indexquals);
69 static void fix_indxqual_sublist(List *indexqual,
70 Relids baserelids, int baserelid,
72 List **fixed_quals, List **recheck_quals);
73 static Node *fix_indxqual_operand(Node *node, int baserelid,
76 static List *get_switched_clauses(List *clauses, Relids outerrelids);
77 static List *order_qual_clauses(Query *root, List *clauses);
78 static void copy_path_costsize(Plan *dest, Path *src);
79 static void copy_plan_costsize(Plan *dest, Plan *src);
80 static SeqScan *make_seqscan(List *qptlist, List *qpqual, Index scanrelid);
81 static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
82 List *indxid, List *indxqual,
84 ScanDirection indexscandir);
85 static TidScan *make_tidscan(List *qptlist, List *qpqual, Index scanrelid,
87 static FunctionScan *make_functionscan(List *qptlist, List *qpqual,
89 static NestLoop *make_nestloop(List *tlist,
90 List *joinclauses, List *otherclauses,
91 Plan *lefttree, Plan *righttree,
93 static HashJoin *make_hashjoin(List *tlist,
94 List *joinclauses, List *otherclauses,
96 Plan *lefttree, Plan *righttree,
98 static Hash *make_hash(List *tlist, List *hashkeys, Plan *lefttree);
99 static MergeJoin *make_mergejoin(List *tlist,
100 List *joinclauses, List *otherclauses,
102 Plan *lefttree, Plan *righttree,
104 static Sort *make_sort(Query *root, List *tlist, Plan *lefttree, int numCols,
105 AttrNumber *sortColIdx, Oid *sortOperators);
106 static Sort *make_sort_from_pathkeys(Query *root, Plan *lefttree,
107 Relids relids, List *pathkeys);
112 * Creates the access plan for a query by tracing backwards through the
113 * desired chain of pathnodes, starting at the node 'best_path'. For
114 * every pathnode found:
115 * (1) Create a corresponding plan node containing appropriate id,
116 * target list, and qualification information.
117 * (2) Modify qual clauses of join nodes so that subplan attributes are
118 * referenced using relative values.
119 * (3) Target lists are not modified, but will be in setrefs.c.
121 * best_path is the best access path
123 * Returns a Plan tree.
126 create_plan(Query *root, Path *best_path)
130 switch (best_path->pathtype)
137 plan = (Plan *) create_scan_plan(root, best_path);
142 plan = (Plan *) create_join_plan(root,
143 (JoinPath *) best_path);
146 plan = (Plan *) create_append_plan(root,
147 (AppendPath *) best_path);
150 plan = (Plan *) create_result_plan(root,
151 (ResultPath *) best_path);
154 plan = (Plan *) create_material_plan(root,
155 (MaterialPath *) best_path);
158 plan = (Plan *) create_unique_plan(root,
159 (UniquePath *) best_path);
162 elog(ERROR, "create_plan: unknown pathtype %d",
163 best_path->pathtype);
164 plan = NULL; /* keep compiler quiet */
168 #ifdef NOT_USED /* fix xfunc */
169 /* sort clauses by cost/(1-selectivity) -- JMH 2/26/92 */
170 if (XfuncMode != XFUNC_OFF)
172 set_qpqual((Plan) plan,
173 lisp_qsort(get_qpqual((Plan) plan),
174 xfunc_clause_compare));
175 if (XfuncMode != XFUNC_NOR)
176 /* sort the disjuncts within each clause by cost -- JMH 3/4/92 */
177 xfunc_disjunct_sort(plan->qpqual);
186 * Create a scan plan for the parent relation of 'best_path'.
188 * Returns a Plan node.
191 create_scan_plan(Query *root, Path *best_path)
193 RelOptInfo *rel = best_path->parent;
199 * For table scans, rather than using the relation targetlist (which is
200 * only those Vars actually needed by the query), we prefer to generate a
201 * tlist containing all Vars in order. This will allow the executor to
202 * optimize away projection of the table tuples, if possible. (Note that
203 * planner.c may replace the tlist we generate here, forcing projection to
206 if (use_physical_tlist(rel))
212 foreach(v, rel->varlist)
214 Var *var = (Var *) lfirst(v);
216 tlist = lappend(tlist, create_tl_element(var, resdomno));
221 tlist = rel->targetlist;
224 * Extract the relevant restriction clauses from the parent relation;
225 * the executor must apply all these restrictions during the scan.
227 scan_clauses = get_actual_clauses(rel->baserestrictinfo);
229 /* Sort clauses into best execution order */
230 scan_clauses = order_qual_clauses(root, scan_clauses);
232 switch (best_path->pathtype)
235 plan = (Scan *) create_seqscan_plan(best_path,
241 plan = (Scan *) create_indexscan_plan(root,
242 (IndexPath *) best_path,
248 plan = (Scan *) create_tidscan_plan((TidPath *) best_path,
254 plan = (Scan *) create_subqueryscan_plan(best_path,
260 plan = (Scan *) create_functionscan_plan(best_path,
266 elog(ERROR, "create_scan_plan: unknown node type: %d",
267 best_path->pathtype);
268 plan = NULL; /* keep compiler quiet */
277 * Decide whether to use a tlist matching relation structure,
278 * rather than only those Vars actually referenced.
281 use_physical_tlist(RelOptInfo *rel)
286 * Currently, can't do this for subquery or function scans. (This
287 * is mainly because we don't set up the necessary info when creating
288 * their RelOptInfo nodes.)
290 if (rel->rtekind != RTE_RELATION)
293 * Can't do it with inheritance cases either (mainly because Append
296 if (rel->reloptkind != RELOPT_BASEREL)
299 * Can't do it if any system columns are requested, either. (This could
300 * possibly be fixed but would take some fragile assumptions in setrefs.c,
303 foreach(t, rel->targetlist)
305 TargetEntry *tle = (TargetEntry *) lfirst(t);
306 Var *var = (Var *) tle->expr;
308 if (!var || !IsA(var, Var))
309 return false; /* probably can't happen */
310 if (var->varattno <= 0)
311 return false; /* system column! */
317 * disuse_physical_tlist
318 * Switch a plan node back to emitting only Vars actually referenced.
320 * If the plan node immediately above a scan would prefer to get only
321 * needed Vars and not a physical tlist, it must call this routine to
322 * undo the decision made by use_physical_tlist(). Currently, Hash, Sort,
323 * and Material nodes want this, so they don't have to store useless columns.
326 disuse_physical_tlist(Plan *plan, Path *path)
328 /* Only need to undo it for path types handled by create_scan_plan() */
329 switch (path->pathtype)
336 plan->targetlist = path->parent->targetlist;
345 * Create a join plan for 'best_path' and (recursively) plans for its
346 * inner and outer paths.
348 * Returns a Plan node.
351 create_join_plan(Query *root, JoinPath *best_path)
353 List *join_tlist = best_path->path.parent->targetlist;
360 outer_plan = create_plan(root, best_path->outerjoinpath);
361 inner_plan = create_plan(root, best_path->innerjoinpath);
363 if (IS_OUTER_JOIN(best_path->jointype))
365 get_actual_join_clauses(best_path->joinrestrictinfo,
366 &joinclauses, &otherclauses);
370 /* We can treat all clauses alike for an inner join */
371 joinclauses = get_actual_clauses(best_path->joinrestrictinfo);
375 switch (best_path->path.pathtype)
378 plan = (Join *) create_mergejoin_plan(root,
379 (MergePath *) best_path,
387 plan = (Join *) create_hashjoin_plan(root,
388 (HashPath *) best_path,
396 plan = (Join *) create_nestloop_plan(root,
397 (NestPath *) best_path,
405 elog(ERROR, "create_join_plan: unknown node type: %d",
406 best_path->path.pathtype);
407 plan = NULL; /* keep compiler quiet */
414 * * Expensive function pullups may have pulled local predicates *
415 * into this path node. Put them in the qpqual of the plan node. *
418 if (get_loc_restrictinfo(best_path) != NIL)
419 set_qpqual((Plan) plan,
420 nconc(get_qpqual((Plan) plan),
421 get_actual_clauses(get_loc_restrictinfo(best_path))));
429 * Create an Append plan for 'best_path' and (recursively) plans
432 * Returns a Plan node.
435 create_append_plan(Query *root, AppendPath *best_path)
438 List *tlist = best_path->path.parent->targetlist;
439 List *subplans = NIL;
442 foreach(subpaths, best_path->subpaths)
444 Path *subpath = (Path *) lfirst(subpaths);
446 subplans = lappend(subplans, create_plan(root, subpath));
449 plan = make_append(subplans, false, tlist);
456 * Create a Result plan for 'best_path' and (recursively) plans
459 * Returns a Plan node.
462 create_result_plan(Query *root, ResultPath *best_path)
469 if (best_path->path.parent)
470 tlist = best_path->path.parent->targetlist;
472 tlist = NIL; /* will be filled in later */
474 if (best_path->subpath)
475 subplan = create_plan(root, best_path->subpath);
479 constclauses = order_qual_clauses(root, best_path->constantqual);
481 plan = make_result(tlist, (Node *) constclauses, subplan);
487 * create_material_plan
488 * Create a Material plan for 'best_path' and (recursively) plans
491 * Returns a Plan node.
494 create_material_plan(Query *root, MaterialPath *best_path)
499 subplan = create_plan(root, best_path->subpath);
501 /* We don't want any excess columns in the materialized tuples */
502 disuse_physical_tlist(subplan, best_path->subpath);
504 plan = make_material(subplan->targetlist, subplan);
506 copy_path_costsize(&plan->plan, (Path *) best_path);
513 * Create a Unique plan for 'best_path' and (recursively) plans
516 * Returns a Plan node.
519 create_unique_plan(Query *root, UniquePath *best_path)
523 List *sub_targetlist;
527 subplan = create_plan(root, best_path->subpath);
530 * If the subplan came from an IN subselect (currently always the case),
531 * we need to instantiate the correct output targetlist for the subselect,
532 * rather than using the flattened tlist.
534 sub_targetlist = NIL;
535 foreach(l, root->in_info_list)
537 InClauseInfo *ininfo = (InClauseInfo *) lfirst(l);
539 if (bms_equal(ininfo->righthand, best_path->path.parent->relids))
541 sub_targetlist = ininfo->sub_targetlist;
549 * Transform list of plain Vars into targetlist
551 List *newtlist = NIL;
554 foreach(l, sub_targetlist)
556 Node *tlexpr = lfirst(l);
559 tle = makeTargetEntry(makeResdom(resno,
565 newtlist = lappend(newtlist, tle);
569 * If the top plan node can't do projections, we need to add a
570 * Result node to help it along.
572 * Currently, the only non-projection-capable plan type
573 * we can see here is Append.
575 if (IsA(subplan, Append))
576 subplan = (Plan *) make_result(newtlist, NULL, subplan);
578 subplan->targetlist = newtlist;
581 my_tlist = copyObject(subplan->targetlist);
583 if (best_path->use_hash)
585 int numGroupCols = length(my_tlist);
587 AttrNumber *groupColIdx;
590 numGroups = (long) Min(best_path->rows, (double) LONG_MAX);
592 groupColIdx = (AttrNumber *) palloc(numGroupCols * sizeof(AttrNumber));
593 for (i = 0; i < numGroupCols; i++)
594 groupColIdx[i] = i+1;
596 plan = (Plan *) make_agg(root,
610 sortList = addAllTargetsToSortList(NIL, my_tlist);
611 plan = (Plan *) make_sort_from_sortclauses(root, my_tlist,
613 plan = (Plan *) make_unique(my_tlist, plan, sortList);
616 plan->plan_rows = best_path->rows;
622 /*****************************************************************************
624 * BASE-RELATION SCAN METHODS
626 *****************************************************************************/
630 * create_seqscan_plan
631 * Returns a seqscan plan for the base relation scanned by 'best_path'
632 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
635 create_seqscan_plan(Path *best_path, List *tlist, List *scan_clauses)
638 Index scan_relid = best_path->parent->relid;
640 /* it should be a base rel... */
641 Assert(scan_relid > 0);
642 Assert(best_path->parent->rtekind == RTE_RELATION);
644 scan_plan = make_seqscan(tlist,
648 copy_path_costsize(&scan_plan->plan, best_path);
654 * create_indexscan_plan
655 * Returns a indexscan plan for the base relation scanned by 'best_path'
656 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
658 * The indexqual of the path contains a sublist of implicitly-ANDed qual
659 * conditions for each scan of the index(es); if there is more than one
660 * scan then the retrieved tuple sets are ORed together. The indexqual
661 * and indexinfo lists must have the same length, ie, the number of scans
662 * that will occur. Note it is possible for a qual condition sublist
663 * to be empty --- then no index restrictions will be applied during that
667 create_indexscan_plan(Query *root,
668 IndexPath *best_path,
672 List *indxqual = best_path->indexqual;
673 Index baserelid = best_path->path.parent->relid;
675 Expr *indxqual_or_expr = NULL;
676 List *fixed_indxqual;
677 List *recheck_indxqual;
680 IndexScan *scan_plan;
682 /* it should be a base rel... */
683 Assert(baserelid > 0);
684 Assert(best_path->path.parent->rtekind == RTE_RELATION);
687 * Build list of index OIDs.
690 foreach(ixinfo, best_path->indexinfo)
692 IndexOptInfo *index = (IndexOptInfo *) lfirst(ixinfo);
694 indexids = lappendo(indexids, index->indexoid);
698 * The qpqual list must contain all restrictions not automatically
699 * handled by the index. Normally the predicates in the indxqual are
700 * checked fully by the index, but if the index is "lossy" for a
701 * particular operator (as signaled by the amopreqcheck flag in
702 * pg_amop), then we need to double-check that predicate in qpqual,
703 * because the index may return more tuples than match the predicate.
705 * Since the indexquals were generated from the restriction clauses given
706 * by scan_clauses, there will normally be some duplications between
707 * the lists. We get rid of the duplicates, then add back if lossy.
709 if (length(indxqual) > 1)
712 * Build an expression representation of the indexqual, expanding
713 * the implicit OR and AND semantics of the first- and
714 * second-level lists.
716 List *orclauses = NIL;
719 foreach(orclause, indxqual)
721 orclauses = lappend(orclauses,
722 make_ands_explicit(lfirst(orclause)));
724 indxqual_or_expr = make_orclause(orclauses);
726 qpqual = set_difference(scan_clauses, makeList1(indxqual_or_expr));
728 else if (indxqual != NIL)
731 * Here, we can simply treat the first sublist as an independent
732 * set of qual expressions, since there is no top-level OR
735 qpqual = set_difference(scan_clauses, lfirst(indxqual));
738 qpqual = scan_clauses;
741 * The executor needs a copy with the indexkey on the left of each
742 * clause and with index attr numbers substituted for table ones. This
743 * pass also looks for "lossy" operators.
745 fix_indxqual_references(indxqual, best_path,
746 &fixed_indxqual, &recheck_indxqual);
749 * If there were any "lossy" operators, need to add back the
750 * appropriate qual clauses to the qpqual. When there is just one
751 * indexscan being performed (ie, we have simple AND semantics), we
752 * can just add the lossy clauses themselves to qpqual. If we have
753 * OR-of-ANDs, we'd better add the entire original indexqual to make
754 * sure that the semantics are correct.
756 if (recheck_indxqual != NIL)
758 if (indxqual_or_expr)
760 /* Better do a deep copy of the original scanclauses */
761 qpqual = lappend(qpqual, copyObject(indxqual_or_expr));
765 /* Subroutine already copied quals, so just append to list */
766 Assert(length(recheck_indxqual) == 1);
767 qpqual = nconc(qpqual, (List *) lfirst(recheck_indxqual));
771 /* Finally ready to build the plan node */
772 scan_plan = make_indexscan(tlist,
778 best_path->indexscandir);
780 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
781 /* use the indexscan-specific rows estimate, not the parent rel's */
782 scan_plan->scan.plan.plan_rows = best_path->rows;
788 * create_tidscan_plan
789 * Returns a tidscan plan for the base relation scanned by 'best_path'
790 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
793 create_tidscan_plan(TidPath *best_path, List *tlist, List *scan_clauses)
796 Index scan_relid = best_path->path.parent->relid;
798 /* it should be a base rel... */
799 Assert(scan_relid > 0);
800 Assert(best_path->path.parent->rtekind == RTE_RELATION);
802 scan_plan = make_tidscan(tlist,
807 copy_path_costsize(&scan_plan->scan.plan, &best_path->path);
813 * create_subqueryscan_plan
814 * Returns a subqueryscan plan for the base relation scanned by 'best_path'
815 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
817 static SubqueryScan *
818 create_subqueryscan_plan(Path *best_path, List *tlist, List *scan_clauses)
820 SubqueryScan *scan_plan;
821 Index scan_relid = best_path->parent->relid;
823 /* it should be a subquery base rel... */
824 Assert(scan_relid > 0);
825 Assert(best_path->parent->rtekind == RTE_SUBQUERY);
827 scan_plan = make_subqueryscan(tlist,
830 best_path->parent->subplan);
836 * create_functionscan_plan
837 * Returns a functionscan plan for the base relation scanned by 'best_path'
838 * with restriction clauses 'scan_clauses' and targetlist 'tlist'.
840 static FunctionScan *
841 create_functionscan_plan(Path *best_path, List *tlist, List *scan_clauses)
843 FunctionScan *scan_plan;
844 Index scan_relid = best_path->parent->relid;
846 /* it should be a function base rel... */
847 Assert(scan_relid > 0);
848 Assert(best_path->parent->rtekind == RTE_FUNCTION);
850 scan_plan = make_functionscan(tlist, scan_clauses, scan_relid);
852 copy_path_costsize(&scan_plan->scan.plan, best_path);
857 /*****************************************************************************
861 *****************************************************************************/
864 create_nestloop_plan(Query *root,
874 if (IsA(inner_plan, IndexScan))
877 * An index is being used to reduce the number of tuples scanned
878 * in the inner relation. If there are join clauses being used
879 * with the index, we may remove those join clauses from the list of
880 * clauses that have to be checked as qpquals at the join node ---
881 * but only if there's just one indexscan in the inner path
882 * (otherwise, several different sets of clauses are being ORed
885 * Note we must compare against indxqualorig not the "fixed" indxqual
886 * (which has index attnos instead of relation attnos, and may have
887 * been commuted as well).
889 IndexScan *innerscan = (IndexScan *) inner_plan;
890 List *indxqualorig = innerscan->indxqualorig;
892 if (length(indxqualorig) == 1) /* single indexscan? */
894 /* No work needed if indxqual refers only to its own relation... */
895 if (NumRelids((Node *) indxqualorig) > 1)
896 joinclauses = set_difference(joinclauses,
897 lfirst(indxqualorig));
901 join_plan = make_nestloop(tlist,
906 best_path->jointype);
908 copy_path_costsize(&join_plan->join.plan, &best_path->path);
914 create_mergejoin_plan(Query *root,
915 MergePath *best_path,
923 MergeJoin *join_plan;
926 * Remove the mergeclauses from the list of join qual clauses, leaving
927 * the list of quals that must be checked as qpquals.
929 mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
930 joinclauses = set_difference(joinclauses, mergeclauses);
933 * Rearrange mergeclauses, if needed, so that the outer variable
934 * is always on the left.
936 mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
937 best_path->jpath.outerjoinpath->parent->relids);
940 * Create explicit sort nodes for the outer and inner join paths if
941 * necessary. The sort cost was already accounted for in the path.
942 * Make sure there are no excess columns in the inputs if sorting.
944 if (best_path->outersortkeys)
946 disuse_physical_tlist(outer_plan, best_path->jpath.outerjoinpath);
947 outer_plan = (Plan *)
948 make_sort_from_pathkeys(root,
950 best_path->jpath.outerjoinpath->parent->relids,
951 best_path->outersortkeys);
954 if (best_path->innersortkeys)
956 disuse_physical_tlist(inner_plan, best_path->jpath.innerjoinpath);
957 inner_plan = (Plan *)
958 make_sort_from_pathkeys(root,
960 best_path->jpath.innerjoinpath->parent->relids,
961 best_path->innersortkeys);
965 * Now we can build the mergejoin node.
967 join_plan = make_mergejoin(tlist,
973 best_path->jpath.jointype);
975 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
981 create_hashjoin_plan(Query *root,
996 * Remove the hashclauses from the list of join qual clauses, leaving
997 * the list of quals that must be checked as qpquals.
999 hashclauses = get_actual_clauses(best_path->path_hashclauses);
1000 joinclauses = set_difference(joinclauses, hashclauses);
1003 * Rearrange hashclauses, if needed, so that the outer variable
1004 * is always on the left.
1006 hashclauses = get_switched_clauses(best_path->path_hashclauses,
1007 best_path->jpath.outerjoinpath->parent->relids);
1010 * Extract the inner hash keys (right-hand operands of the hashclauses)
1011 * to put in the Hash node.
1013 innerhashkeys = NIL;
1014 foreach(hcl, hashclauses)
1016 innerhashkeys = lappend(innerhashkeys, get_rightop(lfirst(hcl)));
1019 /* We don't want any excess columns in the hashed tuples */
1020 disuse_physical_tlist(inner_plan, best_path->jpath.innerjoinpath);
1023 * Build the hash node and hash join node.
1025 hash_plan = make_hash(inner_plan->targetlist,
1028 join_plan = make_hashjoin(tlist,
1034 best_path->jpath.jointype);
1036 copy_path_costsize(&join_plan->join.plan, &best_path->jpath.path);
1042 /*****************************************************************************
1044 * SUPPORTING ROUTINES
1046 *****************************************************************************/
1049 * fix_indxqual_references
1050 * Adjust indexqual clauses to the form the executor's indexqual
1051 * machinery needs, and check for recheckable (lossy) index conditions.
1053 * We have four tasks here:
1054 * * Index keys must be represented by Var nodes with varattno set to the
1055 * index's attribute number, not the attribute number in the original rel.
1056 * * indxpath.c may have selected an index that is binary-compatible with
1057 * the actual expression operator, but not exactly the same datatype.
1058 * We must replace the expression's operator with the binary-compatible
1059 * equivalent operator that the index will recognize.
1060 * * If the index key is on the right, commute the clause to put it on the
1061 * left. (Someday the executor might not need this, but for now it does.)
1062 * * If the indexable operator is marked 'amopreqcheck' in pg_amop, then
1063 * the index is "lossy" for this operator: it may return more tuples than
1064 * actually satisfy the operator condition. For each such operator, we
1065 * must add (the original form of) the indexqual clause to the "qpquals"
1066 * of the indexscan node, where the operator will be re-evaluated to
1069 * This code used to be entirely bogus for multi-index scans. Now it keeps
1070 * track of which index applies to each subgroup of index qual clauses...
1072 * Both the input list and the output lists have the form of lists of sublists
1073 * of qual clauses --- the top-level list has one entry for each indexscan
1074 * to be performed. The semantics are OR-of-ANDs.
1076 * fixed_indexquals receives a modified copy of the indexqual list --- the
1077 * original is not changed. Note also that the copy shares no substructure
1078 * with the original; this is needed in case there is a subplan in it (we need
1079 * two separate copies of the subplan tree, or things will go awry).
1081 * recheck_indexquals similarly receives a full copy of whichever clauses
1085 fix_indxqual_references(List *indexquals, IndexPath *index_path,
1086 List **fixed_indexquals, List **recheck_indexquals)
1088 List *fixed_quals = NIL;
1089 List *recheck_quals = NIL;
1090 Relids baserelids = index_path->path.parent->relids;
1091 int baserelid = index_path->path.parent->relid;
1092 List *ixinfo = index_path->indexinfo;
1095 foreach(i, indexquals)
1097 List *indexqual = lfirst(i);
1098 IndexOptInfo *index = (IndexOptInfo *) lfirst(ixinfo);
1102 fix_indxqual_sublist(indexqual, baserelids, baserelid, index,
1103 &fixed_qual, &recheck_qual);
1104 fixed_quals = lappend(fixed_quals, fixed_qual);
1105 if (recheck_qual != NIL)
1106 recheck_quals = lappend(recheck_quals, recheck_qual);
1108 ixinfo = lnext(ixinfo);
1111 *fixed_indexquals = fixed_quals;
1112 *recheck_indexquals = recheck_quals;
1116 * Fix the sublist of indexquals to be used in a particular scan.
1118 * For each qual clause, commute if needed to put the indexkey operand on the
1119 * left, and then fix its varattno. (We do not need to change the other side
1120 * of the clause.) Also change the operator if necessary, and check for
1121 * lossy index behavior.
1123 * Returns two lists: the list of fixed indexquals, and the list (usually
1124 * empty) of original clauses that must be rechecked as qpquals because
1125 * the index is lossy for this operator type.
1128 fix_indxqual_sublist(List *indexqual,
1129 Relids baserelids, int baserelid,
1130 IndexOptInfo *index,
1131 List **fixed_quals, List **recheck_quals)
1133 List *fixed_qual = NIL;
1134 List *recheck_qual = NIL;
1137 foreach(i, indexqual)
1139 OpExpr *clause = (OpExpr *) lfirst(i);
1144 if (!IsA(clause, OpExpr) || length(clause->args) != 2)
1145 elog(ERROR, "fix_indxqual_sublist: indexqual clause is not binary opclause");
1148 * Make a copy that will become the fixed clause.
1150 * We used to try to do a shallow copy here, but that fails if there
1151 * is a subplan in the arguments of the opclause. So just do a
1154 newclause = (OpExpr *) copyObject((Node *) clause);
1157 * Check to see if the indexkey is on the right; if so, commute
1158 * the clause. The indexkey should be the side that refers to
1159 * (only) the base relation.
1161 leftvarnos = pull_varnos((Node *) lfirst(newclause->args));
1162 if (!bms_equal(leftvarnos, baserelids))
1163 CommuteClause(newclause);
1164 bms_free(leftvarnos);
1167 * Now, determine which index attribute this is, change the
1168 * indexkey operand as needed, and get the index opclass.
1170 lfirst(newclause->args) = fix_indxqual_operand(lfirst(newclause->args),
1175 fixed_qual = lappend(fixed_qual, newclause);
1178 * Finally, check to see if index is lossy for this operator. If
1179 * so, add (a copy of) original form of clause to recheck list.
1181 if (op_requires_recheck(newclause->opno, opclass))
1182 recheck_qual = lappend(recheck_qual,
1183 copyObject((Node *) clause));
1186 *fixed_quals = fixed_qual;
1187 *recheck_quals = recheck_qual;
1191 fix_indxqual_operand(Node *node, int baserelid, IndexOptInfo *index,
1195 * Remove any binary-compatible relabeling of the indexkey
1197 if (IsA(node, RelabelType))
1198 node = (Node *) ((RelabelType *) node)->arg;
1201 * We represent index keys by Var nodes having the varno of the base
1202 * table but varattno equal to the index's attribute number (index
1203 * column position). This is a bit hokey ... would be cleaner to use
1204 * a special-purpose node type that could not be mistaken for a
1205 * regular Var. But it will do for now.
1209 /* If it's a var, find which index key position it occupies */
1210 Assert(index->indproc == InvalidOid);
1212 if (((Var *) node)->varno == baserelid)
1214 int varatt = ((Var *) node)->varattno;
1217 for (pos = 0; pos < index->nkeys; pos++)
1219 if (index->indexkeys[pos] == varatt)
1221 Node *newnode = copyObject(node);
1223 ((Var *) newnode)->varattno = pos + 1;
1224 /* return the correct opclass, too */
1225 *opclass = index->classlist[pos];
1232 * Oops, this Var isn't an indexkey!
1234 elog(ERROR, "fix_indxqual_operand: var is not index attribute");
1238 * Else, it must be a func expression matching a functional index.
1239 * Since we currently only support single-column functional indexes,
1240 * the returned varattno must be 1.
1242 Assert(index->indproc != InvalidOid);
1243 Assert(is_funcclause(node)); /* not a very thorough check, but easy */
1245 /* classlist[0] is the only class of a functional index */
1246 *opclass = index->classlist[0];
1248 return (Node *) makeVar(baserelid, 1, exprType(node), -1, 0);
1252 * get_switched_clauses
1253 * Given a list of merge or hash joinclauses (as RestrictInfo nodes),
1254 * extract the bare clauses, and rearrange the elements within the
1255 * clauses, if needed, so the outer join variable is on the left and
1256 * the inner is on the right. The original data structure is not touched;
1257 * a modified list is returned.
1260 get_switched_clauses(List *clauses, Relids outerrelids)
1267 RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(i);
1268 OpExpr *clause = (OpExpr *) restrictinfo->clause;
1270 Assert(is_opclause(clause));
1271 if (bms_is_subset(restrictinfo->right_relids, outerrelids))
1274 * Duplicate just enough of the structure to allow commuting
1275 * the clause without changing the original list. Could use
1276 * copyObject, but a complete deep copy is overkill.
1278 OpExpr *temp = makeNode(OpExpr);
1280 temp->opno = clause->opno;
1281 temp->opfuncid = InvalidOid;
1282 temp->opresulttype = clause->opresulttype;
1283 temp->opretset = clause->opretset;
1284 temp->args = listCopy(clause->args);
1285 /* Commute it --- note this modifies the temp node in-place. */
1286 CommuteClause(temp);
1287 t_list = lappend(t_list, temp);
1290 t_list = lappend(t_list, clause);
1296 * order_qual_clauses
1297 * Given a list of qual clauses that will all be evaluated at the same
1298 * plan node, sort the list into the order we want to check the quals
1301 * Ideally the order should be driven by a combination of execution cost and
1302 * selectivity, but unfortunately we have so little information about
1303 * execution cost of operators that it's really hard to do anything smart.
1304 * For now, we just move any quals that contain SubPlan references (but not
1305 * InitPlan references) to the end of the list.
1308 order_qual_clauses(Query *root, List *clauses)
1314 /* No need to work hard if the query is subselect-free */
1315 if (!root->hasSubLinks)
1318 nosubplans = withsubplans = NIL;
1321 Node *clause = lfirst(l);
1323 if (contain_subplans(clause))
1324 withsubplans = lappend(withsubplans, clause);
1326 nosubplans = lappend(nosubplans, clause);
1329 return nconc(nosubplans, withsubplans);
1333 * Copy cost and size info from a Path node to the Plan node created from it.
1334 * The executor won't use this info, but it's needed by EXPLAIN.
1337 copy_path_costsize(Plan *dest, Path *src)
1341 dest->startup_cost = src->startup_cost;
1342 dest->total_cost = src->total_cost;
1343 dest->plan_rows = src->parent->rows;
1344 dest->plan_width = src->parent->width;
1348 dest->startup_cost = 0;
1349 dest->total_cost = 0;
1350 dest->plan_rows = 0;
1351 dest->plan_width = 0;
1356 * Copy cost and size info from a lower plan node to an inserted node.
1357 * This is not critical, since the decisions have already been made,
1358 * but it helps produce more reasonable-looking EXPLAIN output.
1359 * (Some callers alter the info after copying it.)
1362 copy_plan_costsize(Plan *dest, Plan *src)
1366 dest->startup_cost = src->startup_cost;
1367 dest->total_cost = src->total_cost;
1368 dest->plan_rows = src->plan_rows;
1369 dest->plan_width = src->plan_width;
1373 dest->startup_cost = 0;
1374 dest->total_cost = 0;
1375 dest->plan_rows = 0;
1376 dest->plan_width = 0;
1381 /*****************************************************************************
1383 * PLAN NODE BUILDING ROUTINES
1385 * Some of these are exported because they are called to build plan nodes
1386 * in contexts where we're not deriving the plan node from a path node.
1388 *****************************************************************************/
1391 make_seqscan(List *qptlist,
1395 SeqScan *node = makeNode(SeqScan);
1396 Plan *plan = &node->plan;
1398 /* cost should be inserted by caller */
1399 plan->targetlist = qptlist;
1400 plan->qual = qpqual;
1401 plan->lefttree = NULL;
1402 plan->righttree = NULL;
1403 node->scanrelid = scanrelid;
1409 make_indexscan(List *qptlist,
1415 ScanDirection indexscandir)
1417 IndexScan *node = makeNode(IndexScan);
1418 Plan *plan = &node->scan.plan;
1420 /* cost should be inserted by caller */
1421 plan->targetlist = qptlist;
1422 plan->qual = qpqual;
1423 plan->lefttree = NULL;
1424 plan->righttree = NULL;
1425 node->scan.scanrelid = scanrelid;
1426 node->indxid = indxid;
1427 node->indxqual = indxqual;
1428 node->indxqualorig = indxqualorig;
1429 node->indxorderdir = indexscandir;
1435 make_tidscan(List *qptlist,
1440 TidScan *node = makeNode(TidScan);
1441 Plan *plan = &node->scan.plan;
1443 /* cost should be inserted by caller */
1444 plan->targetlist = qptlist;
1445 plan->qual = qpqual;
1446 plan->lefttree = NULL;
1447 plan->righttree = NULL;
1448 node->scan.scanrelid = scanrelid;
1449 node->tideval = tideval;
1455 make_subqueryscan(List *qptlist,
1460 SubqueryScan *node = makeNode(SubqueryScan);
1461 Plan *plan = &node->scan.plan;
1463 /* cost is figured here for the convenience of prepunion.c */
1464 copy_plan_costsize(plan, subplan);
1465 plan->targetlist = qptlist;
1466 plan->qual = qpqual;
1467 plan->lefttree = NULL;
1468 plan->righttree = NULL;
1469 node->scan.scanrelid = scanrelid;
1470 node->subplan = subplan;
1475 static FunctionScan *
1476 make_functionscan(List *qptlist,
1480 FunctionScan *node = makeNode(FunctionScan);
1481 Plan *plan = &node->scan.plan;
1483 /* cost should be inserted by caller */
1484 plan->targetlist = qptlist;
1485 plan->qual = qpqual;
1486 plan->lefttree = NULL;
1487 plan->righttree = NULL;
1488 node->scan.scanrelid = scanrelid;
1494 make_append(List *appendplans, bool isTarget, List *tlist)
1496 Append *node = makeNode(Append);
1497 Plan *plan = &node->plan;
1500 /* compute costs from subplan costs */
1501 plan->startup_cost = 0;
1502 plan->total_cost = 0;
1503 plan->plan_rows = 0;
1504 plan->plan_width = 0;
1505 foreach(subnode, appendplans)
1507 Plan *subplan = (Plan *) lfirst(subnode);
1509 if (subnode == appendplans) /* first node? */
1510 plan->startup_cost = subplan->startup_cost;
1511 plan->total_cost += subplan->total_cost;
1512 plan->plan_rows += subplan->plan_rows;
1513 if (plan->plan_width < subplan->plan_width)
1514 plan->plan_width = subplan->plan_width;
1516 plan->targetlist = tlist;
1518 plan->lefttree = NULL;
1519 plan->righttree = NULL;
1520 node->appendplans = appendplans;
1521 node->isTarget = isTarget;
1527 make_nestloop(List *tlist,
1534 NestLoop *node = makeNode(NestLoop);
1535 Plan *plan = &node->join.plan;
1537 /* cost should be inserted by caller */
1538 plan->targetlist = tlist;
1539 plan->qual = otherclauses;
1540 plan->lefttree = lefttree;
1541 plan->righttree = righttree;
1542 node->join.jointype = jointype;
1543 node->join.joinqual = joinclauses;
1549 make_hashjoin(List *tlist,
1557 HashJoin *node = makeNode(HashJoin);
1558 Plan *plan = &node->join.plan;
1560 /* cost should be inserted by caller */
1561 plan->targetlist = tlist;
1562 plan->qual = otherclauses;
1563 plan->lefttree = lefttree;
1564 plan->righttree = righttree;
1565 node->hashclauses = hashclauses;
1566 node->join.jointype = jointype;
1567 node->join.joinqual = joinclauses;
1573 make_hash(List *tlist, List *hashkeys, Plan *lefttree)
1575 Hash *node = makeNode(Hash);
1576 Plan *plan = &node->plan;
1578 copy_plan_costsize(plan, lefttree);
1581 * For plausibility, make startup & total costs equal total cost of
1582 * input plan; this only affects EXPLAIN display not decisions.
1584 plan->startup_cost = plan->total_cost;
1585 plan->targetlist = tlist;
1587 plan->lefttree = lefttree;
1588 plan->righttree = NULL;
1589 node->hashkeys = hashkeys;
1595 make_mergejoin(List *tlist,
1603 MergeJoin *node = makeNode(MergeJoin);
1604 Plan *plan = &node->join.plan;
1606 /* cost should be inserted by caller */
1607 plan->targetlist = tlist;
1608 plan->qual = otherclauses;
1609 plan->lefttree = lefttree;
1610 plan->righttree = righttree;
1611 node->mergeclauses = mergeclauses;
1612 node->join.jointype = jointype;
1613 node->join.joinqual = joinclauses;
1619 * make_sort --- basic routine to build a Sort plan node
1621 * Caller must have built the sortColIdx and sortOperators arrays already.
1624 make_sort(Query *root, List *tlist, Plan *lefttree, int numCols,
1625 AttrNumber *sortColIdx, Oid *sortOperators)
1627 Sort *node = makeNode(Sort);
1628 Plan *plan = &node->plan;
1629 Path sort_path; /* dummy for result of cost_sort */
1631 copy_plan_costsize(plan, lefttree); /* only care about copying size */
1632 cost_sort(&sort_path, root, NIL,
1633 lefttree->total_cost,
1634 lefttree->plan_rows,
1635 lefttree->plan_width);
1636 plan->startup_cost = sort_path.startup_cost;
1637 plan->total_cost = sort_path.total_cost;
1638 plan->targetlist = tlist;
1640 plan->lefttree = lefttree;
1641 plan->righttree = NULL;
1642 node->numCols = numCols;
1643 node->sortColIdx = sortColIdx;
1644 node->sortOperators = sortOperators;
1650 * add_sort_column --- utility subroutine for building sort info arrays
1652 * We need this routine because the same column might be selected more than
1653 * once as a sort key column; if so, the extra mentions are redundant.
1655 * Caller is assumed to have allocated the arrays large enough for the
1656 * max possible number of columns. Return value is the new column count.
1659 add_sort_column(AttrNumber colIdx, Oid sortOp,
1660 int numCols, AttrNumber *sortColIdx, Oid *sortOperators)
1664 for (i = 0; i < numCols; i++)
1666 if (sortColIdx[i] == colIdx)
1668 /* Already sorting by this col, so extra sort key is useless */
1673 /* Add the column */
1674 sortColIdx[numCols] = colIdx;
1675 sortOperators[numCols] = sortOp;
1680 * make_sort_from_pathkeys
1681 * Create sort plan to sort according to given pathkeys
1683 * 'lefttree' is the node which yields input tuples
1684 * 'relids' is the set of relids represented by the input node
1685 * 'pathkeys' is the list of pathkeys by which the result is to be sorted
1687 * We must convert the pathkey information into arrays of sort key column
1688 * numbers and sort operator OIDs.
1690 * If the pathkeys include expressions that aren't simple Vars, we will
1691 * usually need to add resjunk items to the input plan's targetlist to
1692 * compute these expressions (since the Sort node itself won't do it).
1693 * If the input plan type isn't one that can do projections, this means
1694 * adding a Result node just to do the projection.
1697 make_sort_from_pathkeys(Query *root, Plan *lefttree,
1698 Relids relids, List *pathkeys)
1700 List *tlist = lefttree->targetlist;
1704 AttrNumber *sortColIdx;
1707 /* We will need at most length(pathkeys) sort columns; possibly less */
1708 numsortkeys = length(pathkeys);
1709 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
1710 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
1714 foreach(i, pathkeys)
1716 List *keysublist = (List *) lfirst(i);
1717 PathKeyItem *pathkey = NULL;
1718 Resdom *resdom = NULL;
1722 * We can sort by any one of the sort key items listed in this
1723 * sublist. For now, we take the first one that corresponds to an
1724 * available Var in the tlist. If there isn't any, use the
1725 * first one that is an expression in the input's vars.
1727 * XXX if we have a choice, is there any way of figuring out which
1728 * might be cheapest to execute? (For example, int4lt is likely
1729 * much cheaper to execute than numericlt, but both might appear
1730 * in the same pathkey sublist...) Not clear that we ever will
1731 * have a choice in practice, so it may not matter.
1733 foreach(j, keysublist)
1735 pathkey = lfirst(j);
1736 Assert(IsA(pathkey, PathKeyItem));
1737 resdom = tlist_member(pathkey->key, tlist);
1743 /* No matching Var; look for an expression */
1744 foreach(j, keysublist)
1746 pathkey = lfirst(j);
1747 if (bms_is_subset(pull_varnos(pathkey->key), relids))
1751 elog(ERROR, "make_sort_from_pathkeys: cannot find pathkey item to sort");
1753 * Do we need to insert a Result node?
1755 * Currently, the only non-projection-capable plan type
1756 * we can see here is Append.
1758 if (IsA(lefttree, Append))
1760 tlist = copyObject(tlist);
1761 lefttree = (Plan *) make_result(tlist, NULL, lefttree);
1764 * Add resjunk entry to input's tlist
1766 resdom = makeResdom(length(tlist) + 1,
1767 exprType(pathkey->key),
1768 exprTypmod(pathkey->key),
1771 tlist = lappend(tlist,
1772 makeTargetEntry(resdom,
1773 (Expr *) pathkey->key));
1774 lefttree->targetlist = tlist; /* just in case NIL before */
1777 * The column might already be selected as a sort key, if the
1778 * pathkeys contain duplicate entries. (This can happen in
1779 * scenarios where multiple mergejoinable clauses mention the same
1780 * var, for example.) So enter it only once in the sort arrays.
1782 numsortkeys = add_sort_column(resdom->resno, pathkey->sortop,
1783 numsortkeys, sortColIdx, sortOperators);
1786 Assert(numsortkeys > 0);
1788 /* Give Sort node its own copy of the tlist (still necessary?) */
1789 sort_tlist = copyObject(tlist);
1791 return make_sort(root, sort_tlist, lefttree, numsortkeys,
1792 sortColIdx, sortOperators);
1796 * make_sort_from_sortclauses
1797 * Create sort plan to sort according to given sortclauses
1799 * 'tlist' is the targetlist
1800 * 'lefttree' is the node which yields input tuples
1801 * 'sortcls' is a list of SortClauses
1804 make_sort_from_sortclauses(Query *root, List *tlist,
1805 Plan *lefttree, List *sortcls)
1810 AttrNumber *sortColIdx;
1813 /* We will need at most length(sortcls) sort columns; possibly less */
1814 numsortkeys = length(sortcls);
1815 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
1816 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
1822 SortClause *sortcl = (SortClause *) lfirst(i);
1823 TargetEntry *tle = get_sortgroupclause_tle(sortcl, tlist);
1824 Resdom *resdom = tle->resdom;
1827 * Check for the possibility of duplicate order-by clauses --- the
1828 * parser should have removed 'em, but no point in sorting redundantly.
1830 numsortkeys = add_sort_column(resdom->resno, sortcl->sortop,
1831 numsortkeys, sortColIdx, sortOperators);
1834 Assert(numsortkeys > 0);
1836 /* Give Sort node its own copy of the tlist (still necessary?) */
1837 sort_tlist = copyObject(tlist);
1839 return make_sort(root, sort_tlist, lefttree, numsortkeys,
1840 sortColIdx, sortOperators);
1844 * make_sort_from_groupcols
1845 * Create sort plan to sort based on grouping columns
1847 * 'groupcls' is the list of GroupClauses
1848 * 'grpColIdx' gives the column numbers to use
1850 * This might look like it could be merged with make_sort_from_sortclauses,
1851 * but presently we *must* use the grpColIdx[] array to locate sort columns,
1852 * because the child plan's tlist is not marked with ressortgroupref info
1853 * appropriate to the grouping node. So, only the sortop is used from the
1854 * GroupClause entries.
1857 make_sort_from_groupcols(Query *root,
1859 AttrNumber *grpColIdx,
1862 List *sub_tlist = lefttree->targetlist;
1867 AttrNumber *sortColIdx;
1870 /* We will need at most length(groupcls) sort columns; possibly less */
1871 numsortkeys = length(groupcls);
1872 sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
1873 sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
1877 foreach(i, groupcls)
1879 GroupClause *grpcl = (GroupClause *) lfirst(i);
1880 TargetEntry *tle = nth(grpColIdx[grpno] - 1, sub_tlist);
1881 Resdom *resdom = tle->resdom;
1884 * Check for the possibility of duplicate group-by clauses --- the
1885 * parser should have removed 'em, but no point in sorting redundantly.
1887 numsortkeys = add_sort_column(resdom->resno, grpcl->sortop,
1888 numsortkeys, sortColIdx, sortOperators);
1892 Assert(numsortkeys > 0);
1894 /* Give Sort node its own copy of the tlist (still necessary?) */
1895 sort_tlist = copyObject(sub_tlist);
1897 return make_sort(root, sort_tlist, lefttree, numsortkeys,
1898 sortColIdx, sortOperators);
1902 make_material(List *tlist, Plan *lefttree)
1904 Material *node = makeNode(Material);
1905 Plan *plan = &node->plan;
1907 /* cost should be inserted by caller */
1908 plan->targetlist = tlist;
1910 plan->lefttree = lefttree;
1911 plan->righttree = NULL;
1917 * materialize_finished_plan: stick a Material node atop a completed plan
1919 * There are a couple of places where we want to attach a Material node
1920 * after completion of subquery_planner(). This currently requires hackery.
1921 * Since subquery_planner has already run SS_finalize_plan on the subplan
1922 * tree, we have to kluge up parameter lists for the Material node.
1923 * Possibly this could be fixed by postponing SS_finalize_plan processing
1924 * until setrefs.c is run?
1927 materialize_finished_plan(Plan *subplan)
1930 Path matpath; /* dummy for result of cost_material */
1932 matplan = (Plan *) make_material(subplan->targetlist, subplan);
1935 cost_material(&matpath,
1936 subplan->total_cost,
1938 subplan->plan_width);
1939 matplan->startup_cost = matpath.startup_cost;
1940 matplan->total_cost = matpath.total_cost;
1941 matplan->plan_rows = subplan->plan_rows;
1942 matplan->plan_width = subplan->plan_width;
1944 /* parameter kluge --- see comments above */
1945 matplan->extParam = bms_copy(subplan->extParam);
1946 matplan->allParam = bms_copy(subplan->allParam);
1952 make_agg(Query *root, List *tlist, List *qual,
1953 AggStrategy aggstrategy,
1954 int numGroupCols, AttrNumber *grpColIdx,
1955 long numGroups, int numAggs,
1958 Agg *node = makeNode(Agg);
1959 Plan *plan = &node->plan;
1960 Path agg_path; /* dummy for result of cost_agg */
1963 node->aggstrategy = aggstrategy;
1964 node->numCols = numGroupCols;
1965 node->grpColIdx = grpColIdx;
1966 node->numGroups = numGroups;
1968 copy_plan_costsize(plan, lefttree); /* only care about copying size */
1969 cost_agg(&agg_path, root,
1970 aggstrategy, numAggs,
1971 numGroupCols, numGroups,
1972 lefttree->startup_cost,
1973 lefttree->total_cost,
1974 lefttree->plan_rows);
1975 plan->startup_cost = agg_path.startup_cost;
1976 plan->total_cost = agg_path.total_cost;
1979 * We will produce a single output tuple if not grouping,
1980 * and a tuple per group otherwise.
1982 if (aggstrategy == AGG_PLAIN)
1983 plan->plan_rows = 1;
1985 plan->plan_rows = numGroups;
1988 * We also need to account for the cost of evaluation of the qual
1989 * (ie, the HAVING clause) and the tlist. Note that cost_qual_eval
1990 * doesn't charge anything for Aggref nodes; this is okay since
1991 * they are really comparable to Vars.
1993 * See notes in grouping_planner about why this routine and make_group
1994 * are the only ones in this file that worry about tlist eval cost.
1998 cost_qual_eval(&qual_cost, qual);
1999 plan->startup_cost += qual_cost.startup;
2000 plan->total_cost += qual_cost.startup;
2001 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2003 cost_qual_eval(&qual_cost, tlist);
2004 plan->startup_cost += qual_cost.startup;
2005 plan->total_cost += qual_cost.startup;
2006 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2009 plan->targetlist = tlist;
2010 plan->lefttree = lefttree;
2011 plan->righttree = (Plan *) NULL;
2017 make_group(Query *root,
2020 AttrNumber *grpColIdx,
2024 Group *node = makeNode(Group);
2025 Plan *plan = &node->plan;
2026 Path group_path; /* dummy for result of cost_group */
2029 node->numCols = numGroupCols;
2030 node->grpColIdx = grpColIdx;
2032 copy_plan_costsize(plan, lefttree); /* only care about copying size */
2033 cost_group(&group_path, root,
2034 numGroupCols, numGroups,
2035 lefttree->startup_cost,
2036 lefttree->total_cost,
2037 lefttree->plan_rows);
2038 plan->startup_cost = group_path.startup_cost;
2039 plan->total_cost = group_path.total_cost;
2041 /* One output tuple per estimated result group */
2042 plan->plan_rows = numGroups;
2045 * We also need to account for the cost of evaluation of the tlist.
2047 * XXX this double-counts the cost of evaluation of any expressions
2048 * used for grouping, since in reality those will have been evaluated
2049 * at a lower plan level and will only be copied by the Group node.
2052 * See notes in grouping_planner about why this routine and make_agg
2053 * are the only ones in this file that worry about tlist eval cost.
2055 cost_qual_eval(&qual_cost, tlist);
2056 plan->startup_cost += qual_cost.startup;
2057 plan->total_cost += qual_cost.startup;
2058 plan->total_cost += qual_cost.per_tuple * plan->plan_rows;
2061 plan->targetlist = tlist;
2062 plan->lefttree = lefttree;
2063 plan->righttree = (Plan *) NULL;
2069 * distinctList is a list of SortClauses, identifying the targetlist items
2070 * that should be considered by the Unique filter.
2073 make_unique(List *tlist, Plan *lefttree, List *distinctList)
2075 Unique *node = makeNode(Unique);
2076 Plan *plan = &node->plan;
2077 int numCols = length(distinctList);
2079 AttrNumber *uniqColIdx;
2082 copy_plan_costsize(plan, lefttree);
2085 * Charge one cpu_operator_cost per comparison per input tuple. We
2086 * assume all columns get compared at most of the tuples. (XXX probably
2087 * this is an overestimate.)
2089 plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols;
2092 * plan->plan_rows is left as a copy of the input subplan's plan_rows;
2093 * ie, we assume the filter removes nothing. The caller must alter this
2094 * if he has a better idea.
2097 plan->targetlist = tlist;
2099 plan->lefttree = lefttree;
2100 plan->righttree = NULL;
2103 * convert SortClause list into array of attr indexes, as wanted by
2106 Assert(numCols > 0);
2107 uniqColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
2109 foreach(slitem, distinctList)
2111 SortClause *sortcl = (SortClause *) lfirst(slitem);
2112 TargetEntry *tle = get_sortgroupclause_tle(sortcl, tlist);
2114 uniqColIdx[keyno++] = tle->resdom->resno;
2117 node->numCols = numCols;
2118 node->uniqColIdx = uniqColIdx;
2124 * distinctList is a list of SortClauses, identifying the targetlist items
2125 * that should be considered by the SetOp filter.
2129 make_setop(SetOpCmd cmd, List *tlist, Plan *lefttree,
2130 List *distinctList, AttrNumber flagColIdx)
2132 SetOp *node = makeNode(SetOp);
2133 Plan *plan = &node->plan;
2134 int numCols = length(distinctList);
2136 AttrNumber *dupColIdx;
2139 copy_plan_costsize(plan, lefttree);
2142 * Charge one cpu_operator_cost per comparison per input tuple. We
2143 * assume all columns get compared at most of the tuples.
2145 plan->total_cost += cpu_operator_cost * plan->plan_rows * numCols;
2148 * We make the unsupported assumption that there will be 10% as many
2149 * tuples out as in. Any way to do better?
2151 plan->plan_rows *= 0.1;
2152 if (plan->plan_rows < 1)
2153 plan->plan_rows = 1;
2155 plan->targetlist = tlist;
2157 plan->lefttree = lefttree;
2158 plan->righttree = NULL;
2161 * convert SortClause list into array of attr indexes, as wanted by
2164 Assert(numCols > 0);
2165 dupColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
2167 foreach(slitem, distinctList)
2169 SortClause *sortcl = (SortClause *) lfirst(slitem);
2170 TargetEntry *tle = get_sortgroupclause_tle(sortcl, tlist);
2172 dupColIdx[keyno++] = tle->resdom->resno;
2176 node->numCols = numCols;
2177 node->dupColIdx = dupColIdx;
2178 node->flagColIdx = flagColIdx;
2184 make_limit(List *tlist, Plan *lefttree,
2185 Node *limitOffset, Node *limitCount)
2187 Limit *node = makeNode(Limit);
2188 Plan *plan = &node->plan;
2190 copy_plan_costsize(plan, lefttree);
2193 * If offset/count are constants, adjust the output rows count and
2194 * costs accordingly. This is only a cosmetic issue if we are at top
2195 * level, but if we are building a subquery then it's important to
2196 * report correct info to the outer planner.
2198 if (limitOffset && IsA(limitOffset, Const))
2200 Const *limito = (Const *) limitOffset;
2201 int32 offset = DatumGetInt32(limito->constvalue);
2203 if (!limito->constisnull && offset > 0)
2205 if (offset > plan->plan_rows)
2206 offset = (int32) plan->plan_rows;
2207 if (plan->plan_rows > 0)
2208 plan->startup_cost +=
2209 (plan->total_cost - plan->startup_cost)
2210 * ((double) offset) / plan->plan_rows;
2211 plan->plan_rows -= offset;
2212 if (plan->plan_rows < 1)
2213 plan->plan_rows = 1;
2216 if (limitCount && IsA(limitCount, Const))
2218 Const *limitc = (Const *) limitCount;
2219 int32 count = DatumGetInt32(limitc->constvalue);
2221 if (!limitc->constisnull && count >= 0)
2223 if (count > plan->plan_rows)
2224 count = (int32) plan->plan_rows;
2225 if (plan->plan_rows > 0)
2226 plan->total_cost = plan->startup_cost +
2227 (plan->total_cost - plan->startup_cost)
2228 * ((double) count) / plan->plan_rows;
2229 plan->plan_rows = count;
2230 if (plan->plan_rows < 1)
2231 plan->plan_rows = 1;
2235 plan->targetlist = tlist;
2237 plan->lefttree = lefttree;
2238 plan->righttree = NULL;
2240 node->limitOffset = limitOffset;
2241 node->limitCount = limitCount;
2247 make_result(List *tlist,
2248 Node *resconstantqual,
2251 Result *node = makeNode(Result);
2252 Plan *plan = &node->plan;
2255 copy_plan_costsize(plan, subplan);
2258 plan->startup_cost = 0;
2259 plan->total_cost = cpu_tuple_cost;
2260 plan->plan_rows = 1; /* wrong if we have a set-valued function? */
2261 plan->plan_width = 0; /* XXX try to be smarter? */
2264 if (resconstantqual)
2268 cost_qual_eval(&qual_cost, (List *) resconstantqual);
2269 /* resconstantqual is evaluated once at startup */
2270 plan->startup_cost += qual_cost.startup + qual_cost.per_tuple;
2271 plan->total_cost += qual_cost.startup + qual_cost.per_tuple;
2274 plan->targetlist = tlist;
2276 plan->lefttree = subplan;
2277 plan->righttree = NULL;
2278 node->resconstantqual = resconstantqual;