1 /*-------------------------------------------------------------------------
4 * Routines to plan a single query
6 * What's in a name, anyway? The top-level entry point of the planner/
7 * optimizer is over in planner.c, not here as you might think from the
8 * file name. But this is the main code for planning a basic join operation,
9 * shorn of features like subselects, inheritance, aggregates, grouping,
10 * and so on. (Those are the things planner.c deals with.)
12 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
17 * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/planmain.c,v 1.77 2003/08/04 00:43:20 momjian Exp $
19 *-------------------------------------------------------------------------
23 #include "optimizer/clauses.h"
24 #include "optimizer/cost.h"
25 #include "optimizer/pathnode.h"
26 #include "optimizer/paths.h"
27 #include "optimizer/planmain.h"
30 /*--------------------
32 * Generate a path (that is, a simplified plan) for a basic query,
33 * which may involve joins but not any fancier features.
35 * Since query_planner does not handle the toplevel processing (grouping,
36 * sorting, etc) it cannot select the best path by itself. It selects
37 * two paths: the cheapest path that produces all the required tuples,
38 * independent of any ordering considerations, and the cheapest path that
39 * produces the expected fraction of the required tuples in the required
40 * ordering, if there is a path that is cheaper for this than just sorting
41 * the output of the cheapest overall path. The caller (grouping_planner)
42 * will make the final decision about which to use.
45 * root is the query to plan
46 * tlist is the target list the query should produce (NOT root->targetList!)
47 * tuple_fraction is the fraction of tuples we expect will be retrieved
50 * *cheapest_path receives the overall-cheapest path for the query
51 * *sorted_path receives the cheapest presorted path for the query,
52 * if any (NULL if there is no useful presorted path)
54 * Note: the Query node also includes a query_pathkeys field, which is both
55 * an input and an output of query_planner(). The input value signals
56 * query_planner that the indicated sort order is wanted in the final output
57 * plan. But this value has not yet been "canonicalized", since the needed
58 * info does not get computed until we scan the qual clauses. We canonicalize
59 * it as soon as that task is done. (The main reason query_pathkeys is a
60 * Query field and not a passed parameter is that the low-level routines in
61 * indxpath.c need to see it.)
63 * tuple_fraction is interpreted as follows:
64 * 0: expect all tuples to be retrieved (normal case)
65 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
66 * from the plan to be retrieved
67 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
68 * expected to be retrieved (ie, a LIMIT specification)
72 query_planner(Query *root, List *tlist, double tuple_fraction,
73 Path **cheapest_path, Path **sorted_path)
76 RelOptInfo *final_rel;
81 * If the query has an empty join tree, then it's something easy like
82 * "SELECT 2+2;" or "INSERT ... VALUES()". Fall through quickly.
84 if (root->jointree->fromlist == NIL)
86 *cheapest_path = (Path *) create_result_path(NULL, NULL,
87 (List *) root->jointree->quals);
93 * Pull out any non-variable WHERE clauses so these can be put in a
94 * toplevel "Result" node, where they will gate execution of the whole
95 * plan (the Result will not invoke its descendant plan unless the
96 * quals are true). Note that any *really* non-variable quals will
97 * have been optimized away by eval_const_expressions(). What we're
98 * mostly interested in here is quals that depend only on outer-level
99 * vars, although if the qual reduces to "WHERE FALSE" this path will
102 root->jointree->quals = (Node *)
103 pull_constant_clauses((List *) root->jointree->quals,
107 * init planner lists to empty
109 * NOTE: in_info_list was set up by subquery_planner, do not touch here
111 root->base_rel_list = NIL;
112 root->other_rel_list = NIL;
113 root->join_rel_list = NIL;
114 root->equi_key_list = NIL;
117 * Construct RelOptInfo nodes for all base relations in query.
119 add_base_rels_to_query(root, (Node *) root->jointree);
122 * Examine the targetlist and qualifications, adding entries to
123 * baserel targetlists for all referenced Vars. Restrict and join
124 * clauses are added to appropriate lists belonging to the mentioned
125 * relations. We also build lists of equijoined keys for pathkey
128 * Note: all subplan nodes will have "flat" (var-only) tlists. This
129 * implies that all expression evaluations are done at the root of the
130 * plan tree. Once upon a time there was code to try to push
131 * expensive function calls down to lower plan nodes, but that's dead
132 * code and has been for a long time...
134 build_base_rel_tlists(root, tlist);
136 (void) distribute_quals_to_rels(root, (Node *) root->jointree);
139 * Use the completed lists of equijoined keys to deduce any implied
140 * but unstated equalities (for example, A=B and B=C imply A=C).
142 generate_implied_equalities(root);
145 * We should now have all the pathkey equivalence sets built, so it's
146 * now possible to convert the requested query_pathkeys to canonical
149 root->query_pathkeys = canonicalize_pathkeys(root, root->query_pathkeys);
152 * Ready to do the primary planning.
154 final_rel = make_one_rel(root);
156 if (!final_rel || !final_rel->cheapest_total_path)
157 elog(ERROR, "failed to construct the join relation");
160 * Now that we have an estimate of the final rel's size, we can
161 * convert a tuple_fraction specified as an absolute count (ie, a
162 * LIMIT option) into a fraction of the total tuples.
164 if (tuple_fraction >= 1.0)
165 tuple_fraction /= final_rel->rows;
168 * Pick out the cheapest-total path and the cheapest presorted path
169 * for the requested pathkeys (if there is one). We should take the
170 * tuple fraction into account when selecting the cheapest presorted
171 * path, but not when selecting the cheapest-total path, since if we
172 * have to sort then we'll have to fetch all the tuples. (But there's
173 * a special case: if query_pathkeys is NIL, meaning order doesn't
174 * matter, then the "cheapest presorted" path will be the cheapest
175 * overall for the tuple fraction.)
177 * The cheapest-total path is also the one to use if grouping_planner
178 * decides to use hashed aggregation, so we return it separately even
179 * if this routine thinks the presorted path is the winner.
181 cheapestpath = final_rel->cheapest_total_path;
184 get_cheapest_fractional_path_for_pathkeys(final_rel->pathlist,
185 root->query_pathkeys,
188 /* Don't return same path in both guises; just wastes effort */
189 if (sortedpath == cheapestpath)
193 * Forget about the presorted path if it would be cheaper to sort the
194 * cheapest-total path. Here we need consider only the behavior at
195 * the tuple fraction point.
199 Path sort_path; /* dummy for result of cost_sort */
201 if (root->query_pathkeys == NIL ||
202 pathkeys_contained_in(root->query_pathkeys,
203 cheapestpath->pathkeys))
205 /* No sort needed for cheapest path */
206 sort_path.startup_cost = cheapestpath->startup_cost;
207 sort_path.total_cost = cheapestpath->total_cost;
211 /* Figure cost for sorting */
212 cost_sort(&sort_path, root, root->query_pathkeys,
213 cheapestpath->total_cost,
214 final_rel->rows, final_rel->width);
217 if (compare_fractional_path_costs(sortedpath, &sort_path,
220 /* Presorted path is a loser */
226 * If we have constant quals, add a toplevel Result step to process
231 cheapestpath = (Path *) create_result_path(final_rel,
235 sortedpath = (Path *) create_result_path(final_rel,
240 *cheapest_path = cheapestpath;
241 *sorted_path = sortedpath;