1 /*-------------------------------------------------------------------------
4 * The query optimizer external interface.
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/optimizer/plan/planner.c,v 1.202 2006/07/11 17:26:58 momjian Exp $
13 *-------------------------------------------------------------------------
20 #include "catalog/pg_operator.h"
21 #include "catalog/pg_type.h"
22 #include "executor/executor.h"
23 #include "executor/nodeAgg.h"
24 #include "miscadmin.h"
25 #include "nodes/makefuncs.h"
26 #include "optimizer/clauses.h"
27 #include "optimizer/cost.h"
28 #include "optimizer/pathnode.h"
29 #include "optimizer/paths.h"
30 #include "optimizer/planmain.h"
31 #include "optimizer/planner.h"
32 #include "optimizer/prep.h"
33 #include "optimizer/subselect.h"
34 #include "optimizer/tlist.h"
35 #include "optimizer/var.h"
36 #ifdef OPTIMIZER_DEBUG
37 #include "nodes/print.h"
39 #include "parser/parse_expr.h"
40 #include "parser/parse_oper.h"
41 #include "parser/parsetree.h"
42 #include "utils/selfuncs.h"
43 #include "utils/syscache.h"
46 ParamListInfo PlannerBoundParamList = NULL; /* current boundParams */
49 /* Expression kind codes for preprocess_expression */
50 #define EXPRKIND_QUAL 0
51 #define EXPRKIND_TARGET 1
52 #define EXPRKIND_RTFUNC 2
53 #define EXPRKIND_LIMIT 3
54 #define EXPRKIND_ININFO 4
55 #define EXPRKIND_APPINFO 5
58 static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
59 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
60 static Plan *inheritance_planner(PlannerInfo *root);
61 static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
62 static double preprocess_limit(PlannerInfo *root,
63 double tuple_fraction,
64 int *offset_est, int *count_est);
65 static bool choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
66 Path *cheapest_path, Path *sorted_path,
67 double dNumGroups, AggClauseCounts *agg_counts);
68 static bool hash_safe_grouping(PlannerInfo *root);
69 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
70 AttrNumber **groupColIdx, bool *need_tlist_eval);
71 static void locate_grouping_columns(PlannerInfo *root,
74 AttrNumber *groupColIdx);
75 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
78 /*****************************************************************************
80 * Query optimizer entry point
82 *****************************************************************************/
84 planner(Query *parse, bool isCursor, int cursorOptions,
85 ParamListInfo boundParams)
87 double tuple_fraction;
89 Index save_PlannerQueryLevel;
90 List *save_PlannerParamList;
91 ParamListInfo save_PlannerBoundParamList;
94 * The planner can be called recursively (an example is when
95 * eval_const_expressions tries to pre-evaluate an SQL function). So,
96 * these global state variables must be saved and restored.
98 * Query level and the param list cannot be moved into the per-query
99 * PlannerInfo structure since their whole purpose is communication across
100 * multiple sub-queries. Also, boundParams is explicitly info from outside
101 * the query, and so is likewise better handled as a global variable.
103 * Note we do NOT save and restore PlannerPlanId: it exists to assign
104 * unique IDs to SubPlan nodes, and we want those IDs to be unique for the
105 * life of a backend. Also, PlannerInitPlan is saved/restored in
106 * subquery_planner, not here.
108 save_PlannerQueryLevel = PlannerQueryLevel;
109 save_PlannerParamList = PlannerParamList;
110 save_PlannerBoundParamList = PlannerBoundParamList;
112 /* Initialize state for handling outer-level references and params */
113 PlannerQueryLevel = 0; /* will be 1 in top-level subquery_planner */
114 PlannerParamList = NIL;
115 PlannerBoundParamList = boundParams;
117 /* Determine what fraction of the plan is likely to be scanned */
121 * We have no real idea how many tuples the user will ultimately FETCH
122 * from a cursor, but it seems a good bet that he doesn't want 'em
123 * all. Optimize for 10% retrieval (you gotta better number? Should
124 * this be a SETtable parameter?)
126 tuple_fraction = 0.10;
130 /* Default assumption is we need all the tuples */
131 tuple_fraction = 0.0;
134 /* primary planning entry point (may recurse for subqueries) */
135 result_plan = subquery_planner(parse, tuple_fraction, NULL);
137 /* check we popped out the right number of levels */
138 Assert(PlannerQueryLevel == 0);
141 * If creating a plan for a scrollable cursor, make sure it can run
142 * backwards on demand. Add a Material node at the top at need.
144 if (isCursor && (cursorOptions & CURSOR_OPT_SCROLL))
146 if (!ExecSupportsBackwardScan(result_plan))
147 result_plan = materialize_finished_plan(result_plan);
150 /* final cleanup of the plan */
151 result_plan = set_plan_references(result_plan, parse->rtable);
153 /* executor wants to know total number of Params used overall */
154 result_plan->nParamExec = list_length(PlannerParamList);
156 /* restore state for outer planner, if any */
157 PlannerQueryLevel = save_PlannerQueryLevel;
158 PlannerParamList = save_PlannerParamList;
159 PlannerBoundParamList = save_PlannerBoundParamList;
165 /*--------------------
167 * Invokes the planner on a subquery. We recurse to here for each
168 * sub-SELECT found in the query tree.
170 * parse is the querytree produced by the parser & rewriter.
171 * tuple_fraction is the fraction of tuples we expect will be retrieved.
172 * tuple_fraction is interpreted as explained for grouping_planner, below.
174 * If subquery_pathkeys isn't NULL, it receives a list of pathkeys indicating
175 * the output sort ordering of the completed plan.
177 * Basically, this routine does the stuff that should only be done once
178 * per Query object. It then calls grouping_planner. At one time,
179 * grouping_planner could be invoked recursively on the same Query object;
180 * that's not currently true, but we keep the separation between the two
181 * routines anyway, in case we need it again someday.
183 * subquery_planner will be called recursively to handle sub-Query nodes
184 * found within the query's expressions and rangetable.
186 * Returns a query plan.
187 *--------------------
190 subquery_planner(Query *parse, double tuple_fraction,
191 List **subquery_pathkeys)
193 List *saved_initplan = PlannerInitPlan;
194 int saved_planid = PlannerPlanId;
200 /* Set up for a new level of subquery */
202 PlannerInitPlan = NIL;
204 /* Create a PlannerInfo data structure for this subquery */
205 root = makeNode(PlannerInfo);
207 root->in_info_list = NIL;
208 root->append_rel_list = NIL;
211 * Look for IN clauses at the top level of WHERE, and transform them into
212 * joins. Note that this step only handles IN clauses originally at top
213 * level of WHERE; if we pull up any subqueries in the next step, their
214 * INs are processed just before pulling them up.
216 if (parse->hasSubLinks)
217 parse->jointree->quals = pull_up_IN_clauses(root,
218 parse->jointree->quals);
221 * Check to see if any subqueries in the rangetable can be merged into
224 parse->jointree = (FromExpr *)
225 pull_up_subqueries(root, (Node *) parse->jointree, false, false);
228 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
229 * avoid the expense of doing flatten_join_alias_vars(). Also check for
230 * outer joins --- if none, we can skip reduce_outer_joins() and some
231 * other processing. This must be done after we have done
232 * pull_up_subqueries, of course.
234 * Note: if reduce_outer_joins manages to eliminate all outer joins,
235 * root->hasOuterJoins is not reset currently. This is OK since its
236 * purpose is merely to suppress unnecessary processing in simple cases.
238 root->hasJoinRTEs = false;
239 root->hasOuterJoins = false;
240 foreach(l, parse->rtable)
242 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
244 if (rte->rtekind == RTE_JOIN)
246 root->hasJoinRTEs = true;
247 if (IS_OUTER_JOIN(rte->jointype))
249 root->hasOuterJoins = true;
250 /* Can quit scanning once we find an outer join */
257 * Expand any rangetable entries that are inheritance sets into "append
258 * relations". This can add entries to the rangetable, but they must be
259 * plain base relations not joins, so it's OK (and marginally more
260 * efficient) to do it after checking for join RTEs. We must do it after
261 * pulling up subqueries, else we'd fail to handle inherited tables in
264 expand_inherited_tables(root);
267 * Set hasHavingQual to remember if HAVING clause is present. Needed
268 * because preprocess_expression will reduce a constant-true condition to
269 * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
271 root->hasHavingQual = (parse->havingQual != NULL);
273 /* Clear this flag; might get set in distribute_qual_to_rels */
274 root->hasPseudoConstantQuals = false;
277 * Do expression preprocessing on targetlist and quals.
279 parse->targetList = (List *)
280 preprocess_expression(root, (Node *) parse->targetList,
283 preprocess_qual_conditions(root, (Node *) parse->jointree);
285 parse->havingQual = preprocess_expression(root, parse->havingQual,
288 parse->limitOffset = preprocess_expression(root, parse->limitOffset,
290 parse->limitCount = preprocess_expression(root, parse->limitCount,
293 root->in_info_list = (List *)
294 preprocess_expression(root, (Node *) root->in_info_list,
296 root->append_rel_list = (List *)
297 preprocess_expression(root, (Node *) root->append_rel_list,
300 /* Also need to preprocess expressions for function RTEs */
301 foreach(l, parse->rtable)
303 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
305 if (rte->rtekind == RTE_FUNCTION)
306 rte->funcexpr = preprocess_expression(root, rte->funcexpr,
311 * In some cases we may want to transfer a HAVING clause into WHERE. We
312 * cannot do so if the HAVING clause contains aggregates (obviously) or
313 * volatile functions (since a HAVING clause is supposed to be executed
314 * only once per group). Also, it may be that the clause is so expensive
315 * to execute that we're better off doing it only once per group, despite
316 * the loss of selectivity. This is hard to estimate short of doing the
317 * entire planning process twice, so we use a heuristic: clauses
318 * containing subplans are left in HAVING. Otherwise, we move or copy the
319 * HAVING clause into WHERE, in hopes of eliminating tuples before
320 * aggregation instead of after.
322 * If the query has explicit grouping then we can simply move such a
323 * clause into WHERE; any group that fails the clause will not be in the
324 * output because none of its tuples will reach the grouping or
325 * aggregation stage. Otherwise we must have a degenerate (variable-free)
326 * HAVING clause, which we put in WHERE so that query_planner() can use it
327 * in a gating Result node, but also keep in HAVING to ensure that we
328 * don't emit a bogus aggregated row. (This could be done better, but it
329 * seems not worth optimizing.)
331 * Note that both havingQual and parse->jointree->quals are in
332 * implicitly-ANDed-list form at this point, even though they are declared
336 foreach(l, (List *) parse->havingQual)
338 Node *havingclause = (Node *) lfirst(l);
340 if (contain_agg_clause(havingclause) ||
341 contain_volatile_functions(havingclause) ||
342 contain_subplans(havingclause))
344 /* keep it in HAVING */
345 newHaving = lappend(newHaving, havingclause);
347 else if (parse->groupClause)
349 /* move it to WHERE */
350 parse->jointree->quals = (Node *)
351 lappend((List *) parse->jointree->quals, havingclause);
355 /* put a copy in WHERE, keep it in HAVING */
356 parse->jointree->quals = (Node *)
357 lappend((List *) parse->jointree->quals,
358 copyObject(havingclause));
359 newHaving = lappend(newHaving, havingclause);
362 parse->havingQual = (Node *) newHaving;
365 * If we have any outer joins, try to reduce them to plain inner joins.
366 * This step is most easily done after we've done expression
369 if (root->hasOuterJoins)
370 reduce_outer_joins(root);
373 * Do the main planning. If we have an inherited target relation, that
374 * needs special processing, else go straight to grouping_planner.
376 if (parse->resultRelation &&
377 rt_fetch(parse->resultRelation, parse->rtable)->inh)
378 plan = inheritance_planner(root);
380 plan = grouping_planner(root, tuple_fraction);
383 * If any subplans were generated, or if we're inside a subplan, build
384 * initPlan list and extParam/allParam sets for plan nodes, and attach the
385 * initPlans to the top plan node.
387 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
388 SS_finalize_plan(plan, parse->rtable);
390 /* Return sort ordering info if caller wants it */
391 if (subquery_pathkeys)
392 *subquery_pathkeys = root->query_pathkeys;
394 /* Return to outer subquery context */
396 PlannerInitPlan = saved_initplan;
397 /* we do NOT restore PlannerPlanId; that's not an oversight! */
403 * preprocess_expression
404 * Do subquery_planner's preprocessing work for an expression,
405 * which can be a targetlist, a WHERE clause (including JOIN/ON
406 * conditions), or a HAVING clause.
409 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
412 * Fall out quickly if expression is empty. This occurs often enough to
413 * be worth checking. Note that null->null is the correct conversion for
414 * implicit-AND result format, too.
420 * If the query has any join RTEs, replace join alias variables with
421 * base-relation variables. We must do this before sublink processing,
422 * else sublinks expanded out from join aliases wouldn't get processed.
424 if (root->hasJoinRTEs)
425 expr = flatten_join_alias_vars(root, expr);
428 * Simplify constant expressions.
430 * Note: this also flattens nested AND and OR expressions into N-argument
431 * form. All processing of a qual expression after this point must be
432 * careful to maintain AND/OR flatness --- that is, do not generate a tree
433 * with AND directly under AND, nor OR directly under OR.
435 * Because this is a relatively expensive process, we skip it when the
436 * query is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()". The
437 * expression will only be evaluated once anyway, so no point in
438 * pre-simplifying; we can't execute it any faster than the executor can,
439 * and we will waste cycles copying the tree. Notice however that we
440 * still must do it for quals (to get AND/OR flatness); and if we are in a
441 * subquery we should not assume it will be done only once.
443 if (root->parse->jointree->fromlist != NIL ||
444 kind == EXPRKIND_QUAL ||
445 PlannerQueryLevel > 1)
446 expr = eval_const_expressions(expr);
449 * If it's a qual or havingQual, canonicalize it.
451 if (kind == EXPRKIND_QUAL)
453 expr = (Node *) canonicalize_qual((Expr *) expr);
455 #ifdef OPTIMIZER_DEBUG
456 printf("After canonicalize_qual()\n");
461 /* Expand SubLinks to SubPlans */
462 if (root->parse->hasSubLinks)
463 expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL));
466 * XXX do not insert anything here unless you have grokked the comments in
467 * SS_replace_correlation_vars ...
470 /* Replace uplevel vars with Param nodes */
471 if (PlannerQueryLevel > 1)
472 expr = SS_replace_correlation_vars(expr);
475 * If it's a qual or havingQual, convert it to implicit-AND format. (We
476 * don't want to do this before eval_const_expressions, since the latter
477 * would be unable to simplify a top-level AND correctly. Also,
478 * SS_process_sublinks expects explicit-AND format.)
480 if (kind == EXPRKIND_QUAL)
481 expr = (Node *) make_ands_implicit((Expr *) expr);
487 * preprocess_qual_conditions
488 * Recursively scan the query's jointree and do subquery_planner's
489 * preprocessing work on each qual condition found therein.
492 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
496 if (IsA(jtnode, RangeTblRef))
498 /* nothing to do here */
500 else if (IsA(jtnode, FromExpr))
502 FromExpr *f = (FromExpr *) jtnode;
505 foreach(l, f->fromlist)
506 preprocess_qual_conditions(root, lfirst(l));
508 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
510 else if (IsA(jtnode, JoinExpr))
512 JoinExpr *j = (JoinExpr *) jtnode;
514 preprocess_qual_conditions(root, j->larg);
515 preprocess_qual_conditions(root, j->rarg);
517 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
520 elog(ERROR, "unrecognized node type: %d",
521 (int) nodeTag(jtnode));
525 * inheritance_planner
526 * Generate a plan in the case where the result relation is an
529 * We have to handle this case differently from cases where a source relation
530 * is an inheritance set. Source inheritance is expanded at the bottom of the
531 * plan tree (see allpaths.c), but target inheritance has to be expanded at
532 * the top. The reason is that for UPDATE, each target relation needs a
533 * different targetlist matching its own column set. Also, for both UPDATE
534 * and DELETE, the executor needs the Append plan node at the top, else it
535 * can't keep track of which table is the current target table. Fortunately,
536 * the UPDATE/DELETE target can never be the nullable side of an outer join,
537 * so it's OK to generate the plan this way.
539 * Returns a query plan.
542 inheritance_planner(PlannerInfo *root)
544 Query *parse = root->parse;
545 int parentRTindex = parse->resultRelation;
546 List *subplans = NIL;
551 subroot.parse = NULL; /* catch it if no matches in loop */
553 parse->resultRelations = NIL;
555 foreach(l, root->append_rel_list)
557 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
560 /* append_rel_list contains all append rels; ignore others */
561 if (appinfo->parent_relid != parentRTindex)
564 /* Build target-relations list for the executor */
565 parse->resultRelations = lappend_int(parse->resultRelations,
566 appinfo->child_relid);
569 * Generate modified query with this rel as target. We have to be
570 * prepared to translate varnos in in_info_list as well as in the
573 memcpy(&subroot, root, sizeof(PlannerInfo));
574 subroot.parse = (Query *)
575 adjust_appendrel_attrs((Node *) parse,
577 subroot.in_info_list = (List *)
578 adjust_appendrel_attrs((Node *) root->in_info_list,
580 /* There shouldn't be any OJ info to translate, as yet */
581 Assert(subroot.oj_info_list == NIL);
584 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
586 subplans = lappend(subplans, subplan);
588 /* Save preprocessed tlist from first rel for use in Append */
590 tlist = subplan->targetlist;
594 * Planning might have modified the rangetable, due to changes of the
595 * Query structures inside subquery RTEs. We have to ensure that this
596 * gets propagated back to the master copy. But can't do this until we
597 * are done planning, because all the calls to grouping_planner need
598 * virgin sub-Queries to work from. (We are effectively assuming that
599 * sub-Queries will get planned identically each time, or at least that
600 * the impacts on their rangetables will be the same each time.)
602 * XXX should clean this up someday
604 parse->rtable = subroot.parse->rtable;
606 /* Mark result as unordered (probably unnecessary) */
607 root->query_pathkeys = NIL;
609 return (Plan *) make_append(subplans, true, tlist);
612 /*--------------------
614 * Perform planning steps related to grouping, aggregation, etc.
615 * This primarily means adding top-level processing to the basic
616 * query plan produced by query_planner.
618 * tuple_fraction is the fraction of tuples we expect will be retrieved
620 * tuple_fraction is interpreted as follows:
621 * 0: expect all tuples to be retrieved (normal case)
622 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
623 * from the plan to be retrieved
624 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
625 * expected to be retrieved (ie, a LIMIT specification)
627 * Returns a query plan. Also, root->query_pathkeys is returned as the
628 * actual output ordering of the plan (in pathkey format).
629 *--------------------
632 grouping_planner(PlannerInfo *root, double tuple_fraction)
634 Query *parse = root->parse;
635 List *tlist = parse->targetList;
639 List *current_pathkeys;
641 double dNumGroups = 0;
643 /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
644 if (parse->limitCount || parse->limitOffset)
645 tuple_fraction = preprocess_limit(root, tuple_fraction,
646 &offset_est, &count_est);
648 if (parse->setOperations)
650 List *set_sortclauses;
653 * If there's a top-level ORDER BY, assume we have to fetch all the
654 * tuples. This might seem too simplistic given all the hackery below
655 * to possibly avoid the sort ... but a nonzero tuple_fraction is only
656 * of use to plan_set_operations() when the setop is UNION ALL, and
657 * the result of UNION ALL is always unsorted.
659 if (parse->sortClause)
660 tuple_fraction = 0.0;
663 * Construct the plan for set operations. The result will not need
664 * any work except perhaps a top-level sort and/or LIMIT.
666 result_plan = plan_set_operations(root, tuple_fraction,
670 * Calculate pathkeys representing the sort order (if any) of the set
671 * operation's result. We have to do this before overwriting the sort
674 current_pathkeys = make_pathkeys_for_sortclauses(set_sortclauses,
675 result_plan->targetlist);
676 current_pathkeys = canonicalize_pathkeys(root, current_pathkeys);
679 * We should not need to call preprocess_targetlist, since we must be
680 * in a SELECT query node. Instead, use the targetlist returned by
681 * plan_set_operations (since this tells whether it returned any
682 * resjunk columns!), and transfer any sort key information from the
685 Assert(parse->commandType == CMD_SELECT);
687 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
690 * Can't handle FOR UPDATE/SHARE here (parser should have checked
691 * already, but let's make sure).
695 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
696 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
699 * Calculate pathkeys that represent result ordering requirements
701 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
703 sort_pathkeys = canonicalize_pathkeys(root, sort_pathkeys);
707 /* No set operations, do regular planning */
709 List *group_pathkeys;
710 AttrNumber *groupColIdx = NULL;
711 bool need_tlist_eval = true;
717 AggClauseCounts agg_counts;
718 int numGroupCols = list_length(parse->groupClause);
719 bool use_hashed_grouping = false;
721 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
723 /* Preprocess targetlist */
724 tlist = preprocess_targetlist(root, tlist);
727 * Generate appropriate target list for subplan; may be different from
728 * tlist if grouping or aggregation is needed.
730 sub_tlist = make_subplanTargetList(root, tlist,
731 &groupColIdx, &need_tlist_eval);
734 * Calculate pathkeys that represent grouping/ordering requirements.
735 * Stash them in PlannerInfo so that query_planner can canonicalize
738 root->group_pathkeys =
739 make_pathkeys_for_sortclauses(parse->groupClause, tlist);
740 root->sort_pathkeys =
741 make_pathkeys_for_sortclauses(parse->sortClause, tlist);
744 * Will need actual number of aggregates for estimating costs.
746 * Note: we do not attempt to detect duplicate aggregates here; a
747 * somewhat-overestimated count is okay for our present purposes.
749 * Note: think not that we can turn off hasAggs if we find no aggs. It
750 * is possible for constant-expression simplification to remove all
751 * explicit references to aggs, but we still have to follow the
752 * aggregate semantics (eg, producing only one output row).
756 count_agg_clauses((Node *) tlist, &agg_counts);
757 count_agg_clauses(parse->havingQual, &agg_counts);
761 * Figure out whether we need a sorted result from query_planner.
763 * If we have a GROUP BY clause, then we want a result sorted properly
764 * for grouping. Otherwise, if there is an ORDER BY clause, we want
765 * to sort by the ORDER BY clause. (Note: if we have both, and ORDER
766 * BY is a superset of GROUP BY, it would be tempting to request sort
767 * by ORDER BY --- but that might just leave us failing to exploit an
768 * available sort order at all. Needs more thought...)
770 if (parse->groupClause)
771 root->query_pathkeys = root->group_pathkeys;
772 else if (parse->sortClause)
773 root->query_pathkeys = root->sort_pathkeys;
775 root->query_pathkeys = NIL;
778 * Generate the best unsorted and presorted paths for this Query (but
779 * note there may not be any presorted path). query_planner will also
780 * estimate the number of groups in the query, and canonicalize all
783 query_planner(root, sub_tlist, tuple_fraction,
784 &cheapest_path, &sorted_path, &dNumGroups);
786 group_pathkeys = root->group_pathkeys;
787 sort_pathkeys = root->sort_pathkeys;
790 * If grouping, decide whether we want to use hashed grouping.
792 if (parse->groupClause)
794 use_hashed_grouping =
795 choose_hashed_grouping(root, tuple_fraction,
796 cheapest_path, sorted_path,
797 dNumGroups, &agg_counts);
799 /* Also convert # groups to long int --- but 'ware overflow! */
800 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
804 * Select the best path. If we are doing hashed grouping, we will
805 * always read all the input tuples, so use the cheapest-total path.
806 * Otherwise, trust query_planner's decision about which to use.
808 if (use_hashed_grouping || !sorted_path)
809 best_path = cheapest_path;
811 best_path = sorted_path;
814 * Check to see if it's possible to optimize MIN/MAX aggregates. If
815 * so, we will forget all the work we did so far to choose a "regular"
816 * path ... but we had to do it anyway to be able to tell which way is
819 result_plan = optimize_minmax_aggregates(root,
822 if (result_plan != NULL)
825 * optimize_minmax_aggregates generated the full plan, with the
826 * right tlist, and it has no sort order.
828 current_pathkeys = NIL;
833 * Normal case --- create a plan according to query_planner's
836 result_plan = create_plan(root, best_path);
837 current_pathkeys = best_path->pathkeys;
840 * create_plan() returns a plan with just a "flat" tlist of
841 * required Vars. Usually we need to insert the sub_tlist as the
842 * tlist of the top plan node. However, we can skip that if we
843 * determined that whatever query_planner chose to return will be
849 * If the top-level plan node is one that cannot do expression
850 * evaluation, we must insert a Result node to project the
853 if (!is_projection_capable_plan(result_plan))
855 result_plan = (Plan *) make_result(sub_tlist, NULL,
861 * Otherwise, just replace the subplan's flat tlist with
864 result_plan->targetlist = sub_tlist;
868 * Also, account for the cost of evaluation of the sub_tlist.
870 * Up to now, we have only been dealing with "flat" tlists,
871 * containing just Vars. So their evaluation cost is zero
872 * according to the model used by cost_qual_eval() (or if you
873 * prefer, the cost is factored into cpu_tuple_cost). Thus we
874 * can avoid accounting for tlist cost throughout
875 * query_planner() and subroutines. But now we've inserted a
876 * tlist that might contain actual operators, sub-selects, etc
877 * --- so we'd better account for its cost.
879 * Below this point, any tlist eval cost for added-on nodes
880 * should be accounted for as we create those nodes.
881 * Presently, of the node types we can add on, only Agg and
882 * Group project new tlists (the rest just copy their input
883 * tuples) --- so make_agg() and make_group() are responsible
884 * for computing the added cost.
886 cost_qual_eval(&tlist_cost, sub_tlist);
887 result_plan->startup_cost += tlist_cost.startup;
888 result_plan->total_cost += tlist_cost.startup +
889 tlist_cost.per_tuple * result_plan->plan_rows;
894 * Since we're using query_planner's tlist and not the one
895 * make_subplanTargetList calculated, we have to refigure any
896 * grouping-column indexes make_subplanTargetList computed.
898 locate_grouping_columns(root, tlist, result_plan->targetlist,
903 * Insert AGG or GROUP node if needed, plus an explicit sort step
906 * HAVING clause, if any, becomes qual of the Agg or Group node.
908 if (use_hashed_grouping)
910 /* Hashed aggregate plan --- no sort needed */
911 result_plan = (Plan *) make_agg(root,
913 (List *) parse->havingQual,
920 /* Hashed aggregation produces randomly-ordered results */
921 current_pathkeys = NIL;
923 else if (parse->hasAggs)
925 /* Plain aggregate plan --- sort if needed */
926 AggStrategy aggstrategy;
928 if (parse->groupClause)
930 if (!pathkeys_contained_in(group_pathkeys,
933 result_plan = (Plan *)
934 make_sort_from_groupcols(root,
938 current_pathkeys = group_pathkeys;
940 aggstrategy = AGG_SORTED;
943 * The AGG node will not change the sort ordering of its
944 * groups, so current_pathkeys describes the result too.
949 aggstrategy = AGG_PLAIN;
950 /* Result will be only one row anyway; no sort order */
951 current_pathkeys = NIL;
954 result_plan = (Plan *) make_agg(root,
956 (List *) parse->havingQual,
964 else if (parse->groupClause)
967 * GROUP BY without aggregation, so insert a group node (plus
968 * the appropriate sort node, if necessary).
970 * Add an explicit sort if we couldn't make the path come out
971 * the way the GROUP node needs it.
973 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
975 result_plan = (Plan *)
976 make_sort_from_groupcols(root,
980 current_pathkeys = group_pathkeys;
983 result_plan = (Plan *) make_group(root,
985 (List *) parse->havingQual,
990 /* The Group node won't change sort ordering */
992 else if (root->hasHavingQual)
995 * No aggregates, and no GROUP BY, but we have a HAVING qual.
996 * This is a degenerate case in which we are supposed to emit
997 * either 0 or 1 row depending on whether HAVING succeeds.
998 * Furthermore, there cannot be any variables in either HAVING
999 * or the targetlist, so we actually do not need the FROM
1000 * table at all! We can just throw away the plan-so-far and
1001 * generate a Result node. This is a sufficiently unusual
1002 * corner case that it's not worth contorting the structure of
1003 * this routine to avoid having to generate the plan in the
1006 result_plan = (Plan *) make_result(tlist,
1010 } /* end of non-minmax-aggregate case */
1011 } /* end of if (setOperations) */
1014 * If we were not able to make the plan come out in the right order, add
1015 * an explicit sort step.
1017 if (parse->sortClause)
1019 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1021 result_plan = (Plan *)
1022 make_sort_from_sortclauses(root,
1025 current_pathkeys = sort_pathkeys;
1030 * If there is a DISTINCT clause, add the UNIQUE node.
1032 if (parse->distinctClause)
1034 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1037 * If there was grouping or aggregation, leave plan_rows as-is (ie,
1038 * assume the result was already mostly unique). If not, use the
1039 * number of distinct-groups calculated by query_planner.
1041 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1042 result_plan->plan_rows = dNumGroups;
1046 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1048 if (parse->limitCount || parse->limitOffset)
1050 result_plan = (Plan *) make_limit(result_plan,
1058 * Return the actual output ordering in query_pathkeys for possible use by
1059 * an outer query level.
1061 root->query_pathkeys = current_pathkeys;
1067 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1069 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1070 * results back in *count_est and *offset_est. These variables are set to
1071 * 0 if the corresponding clause is not present, and -1 if it's present
1072 * but we couldn't estimate the value for it. (The "0" convention is OK
1073 * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1074 * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
1075 * usual practice of never estimating less than one row.) These values will
1076 * be passed to make_limit, which see if you change this code.
1078 * The return value is the suitably adjusted tuple_fraction to use for
1079 * planning the query. This adjustment is not overridable, since it reflects
1080 * plan actions that grouping_planner() will certainly take, not assumptions
1084 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1085 int *offset_est, int *count_est)
1087 Query *parse = root->parse;
1089 double limit_fraction;
1091 /* Should not be called unless LIMIT or OFFSET */
1092 Assert(parse->limitCount || parse->limitOffset);
1095 * Try to obtain the clause values. We use estimate_expression_value
1096 * primarily because it can sometimes do something useful with Params.
1098 if (parse->limitCount)
1100 est = estimate_expression_value(parse->limitCount);
1101 if (est && IsA(est, Const))
1103 if (((Const *) est)->constisnull)
1105 /* NULL indicates LIMIT ALL, ie, no limit */
1106 *count_est = 0; /* treat as not present */
1110 *count_est = DatumGetInt32(((Const *) est)->constvalue);
1111 if (*count_est <= 0)
1112 *count_est = 1; /* force to at least 1 */
1116 *count_est = -1; /* can't estimate */
1119 *count_est = 0; /* not present */
1121 if (parse->limitOffset)
1123 est = estimate_expression_value(parse->limitOffset);
1124 if (est && IsA(est, Const))
1126 if (((Const *) est)->constisnull)
1128 /* Treat NULL as no offset; the executor will too */
1129 *offset_est = 0; /* treat as not present */
1133 *offset_est = DatumGetInt32(((Const *) est)->constvalue);
1134 if (*offset_est < 0)
1135 *offset_est = 0; /* less than 0 is same as 0 */
1139 *offset_est = -1; /* can't estimate */
1142 *offset_est = 0; /* not present */
1144 if (*count_est != 0)
1147 * A LIMIT clause limits the absolute number of tuples returned.
1148 * However, if it's not a constant LIMIT then we have to guess; for
1149 * lack of a better idea, assume 10% of the plan's result is wanted.
1151 if (*count_est < 0 || *offset_est < 0)
1153 /* LIMIT or OFFSET is an expression ... punt ... */
1154 limit_fraction = 0.10;
1158 /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
1159 limit_fraction = (double) *count_est + (double) *offset_est;
1163 * If we have absolute limits from both caller and LIMIT, use the
1164 * smaller value; likewise if they are both fractional. If one is
1165 * fractional and the other absolute, we can't easily determine which
1166 * is smaller, but we use the heuristic that the absolute will usually
1169 if (tuple_fraction >= 1.0)
1171 if (limit_fraction >= 1.0)
1174 tuple_fraction = Min(tuple_fraction, limit_fraction);
1178 /* caller absolute, limit fractional; use caller's value */
1181 else if (tuple_fraction > 0.0)
1183 if (limit_fraction >= 1.0)
1185 /* caller fractional, limit absolute; use limit */
1186 tuple_fraction = limit_fraction;
1190 /* both fractional */
1191 tuple_fraction = Min(tuple_fraction, limit_fraction);
1196 /* no info from caller, just use limit */
1197 tuple_fraction = limit_fraction;
1200 else if (*offset_est != 0 && tuple_fraction > 0.0)
1203 * We have an OFFSET but no LIMIT. This acts entirely differently
1204 * from the LIMIT case: here, we need to increase rather than decrease
1205 * the caller's tuple_fraction, because the OFFSET acts to cause more
1206 * tuples to be fetched instead of fewer. This only matters if we got
1207 * a tuple_fraction > 0, however.
1209 * As above, use 10% if OFFSET is present but unestimatable.
1211 if (*offset_est < 0)
1212 limit_fraction = 0.10;
1214 limit_fraction = (double) *offset_est;
1217 * If we have absolute counts from both caller and OFFSET, add them
1218 * together; likewise if they are both fractional. If one is
1219 * fractional and the other absolute, we want to take the larger, and
1220 * we heuristically assume that's the fractional one.
1222 if (tuple_fraction >= 1.0)
1224 if (limit_fraction >= 1.0)
1226 /* both absolute, so add them together */
1227 tuple_fraction += limit_fraction;
1231 /* caller absolute, limit fractional; use limit */
1232 tuple_fraction = limit_fraction;
1237 if (limit_fraction >= 1.0)
1239 /* caller fractional, limit absolute; use caller's value */
1243 /* both fractional, so add them together */
1244 tuple_fraction += limit_fraction;
1245 if (tuple_fraction >= 1.0)
1246 tuple_fraction = 0.0; /* assume fetch all */
1251 return tuple_fraction;
1255 * choose_hashed_grouping - should we use hashed grouping?
1258 choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
1259 Path *cheapest_path, Path *sorted_path,
1260 double dNumGroups, AggClauseCounts *agg_counts)
1262 int numGroupCols = list_length(root->parse->groupClause);
1263 double cheapest_path_rows;
1264 int cheapest_path_width;
1266 List *current_pathkeys;
1271 * Check can't-do-it conditions, including whether the grouping operators
1274 * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1275 * (Doing so would imply storing *all* the input values in the hash table,
1276 * which seems like a certain loser.)
1278 if (!enable_hashagg)
1280 if (agg_counts->numDistinctAggs != 0)
1282 if (!hash_safe_grouping(root))
1286 * Don't do it if it doesn't look like the hashtable will fit into
1289 * Beware here of the possibility that cheapest_path->parent is NULL. This
1290 * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
1292 if (cheapest_path->parent)
1294 cheapest_path_rows = cheapest_path->parent->rows;
1295 cheapest_path_width = cheapest_path->parent->width;
1299 cheapest_path_rows = 1; /* assume non-set result */
1300 cheapest_path_width = 100; /* arbitrary */
1303 /* Estimate per-hash-entry space at tuple width... */
1304 hashentrysize = MAXALIGN(cheapest_path_width) + MAXALIGN(sizeof(MinimalTupleData));
1305 /* plus space for pass-by-ref transition values... */
1306 hashentrysize += agg_counts->transitionSpace;
1307 /* plus the per-hash-entry overhead */
1308 hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1310 if (hashentrysize * dNumGroups > work_mem * 1024L)
1314 * See if the estimated cost is no more than doing it the other way. While
1315 * avoiding the need for sorted input is usually a win, the fact that the
1316 * output won't be sorted may be a loss; so we need to do an actual cost
1319 * We need to consider cheapest_path + hashagg [+ final sort] versus
1320 * either cheapest_path [+ sort] + group or agg [+ final sort] or
1321 * presorted_path + group or agg [+ final sort] where brackets indicate a
1322 * step that may not be needed. We assume query_planner() will have
1323 * returned a presorted path only if it's a winner compared to
1324 * cheapest_path for this purpose.
1326 * These path variables are dummies that just hold cost fields; we don't
1327 * make actual Paths for these steps.
1329 cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1330 numGroupCols, dNumGroups,
1331 cheapest_path->startup_cost, cheapest_path->total_cost,
1332 cheapest_path_rows);
1333 /* Result of hashed agg is always unsorted */
1334 if (root->sort_pathkeys)
1335 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
1336 dNumGroups, cheapest_path_width);
1340 sorted_p.startup_cost = sorted_path->startup_cost;
1341 sorted_p.total_cost = sorted_path->total_cost;
1342 current_pathkeys = sorted_path->pathkeys;
1346 sorted_p.startup_cost = cheapest_path->startup_cost;
1347 sorted_p.total_cost = cheapest_path->total_cost;
1348 current_pathkeys = cheapest_path->pathkeys;
1350 if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1352 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
1353 cheapest_path_rows, cheapest_path_width);
1354 current_pathkeys = root->group_pathkeys;
1357 if (root->parse->hasAggs)
1358 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1359 numGroupCols, dNumGroups,
1360 sorted_p.startup_cost, sorted_p.total_cost,
1361 cheapest_path_rows);
1363 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1364 sorted_p.startup_cost, sorted_p.total_cost,
1365 cheapest_path_rows);
1366 /* The Agg or Group node will preserve ordering */
1367 if (root->sort_pathkeys &&
1368 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1369 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
1370 dNumGroups, cheapest_path_width);
1373 * Now make the decision using the top-level tuple fraction. First we
1374 * have to convert an absolute count (LIMIT) into fractional form.
1376 if (tuple_fraction >= 1.0)
1377 tuple_fraction /= dNumGroups;
1379 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1380 tuple_fraction) < 0)
1382 /* Hashed is cheaper, so use it */
1389 * hash_safe_grouping - are grouping operators hashable?
1391 * We assume hashed aggregation will work if the datatype's equality operator
1392 * is marked hashjoinable.
1395 hash_safe_grouping(PlannerInfo *root)
1399 foreach(gl, root->parse->groupClause)
1401 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1402 TargetEntry *tle = get_sortgroupclause_tle(grpcl,
1403 root->parse->targetList);
1407 optup = equality_oper(exprType((Node *) tle->expr), true);
1410 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1411 ReleaseSysCache(optup);
1419 * make_subplanTargetList
1420 * Generate appropriate target list when grouping is required.
1422 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1423 * above the result of query_planner, we typically want to pass a different
1424 * target list to query_planner than the outer plan nodes should have.
1425 * This routine generates the correct target list for the subplan.
1427 * The initial target list passed from the parser already contains entries
1428 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1429 * for variables used only in HAVING clauses; so we need to add those
1430 * variables to the subplan target list. Also, we flatten all expressions
1431 * except GROUP BY items into their component variables; the other expressions
1432 * will be computed by the inserted nodes rather than by the subplan.
1433 * For example, given a query like
1434 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1435 * we want to pass this targetlist to the subplan:
1437 * where the a+b target will be used by the Sort/Group steps, and the
1438 * other targets will be used for computing the final results. (In the
1439 * above example we could theoretically suppress the a and b targets and
1440 * pass down only c,d,a+b, but it's not really worth the trouble to
1441 * eliminate simple var references from the subplan. We will avoid doing
1442 * the extra computation to recompute a+b at the outer level; see
1443 * replace_vars_with_subplan_refs() in setrefs.c.)
1445 * If we are grouping or aggregating, *and* there are no non-Var grouping
1446 * expressions, then the returned tlist is effectively dummy; we do not
1447 * need to force it to be evaluated, because all the Vars it contains
1448 * should be present in the output of query_planner anyway.
1450 * 'tlist' is the query's target list.
1451 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1452 * expressions (if there are any) in the subplan's target list.
1453 * 'need_tlist_eval' is set true if we really need to evaluate the
1456 * The result is the targetlist to be passed to the subplan.
1460 make_subplanTargetList(PlannerInfo *root,
1462 AttrNumber **groupColIdx,
1463 bool *need_tlist_eval)
1465 Query *parse = root->parse;
1470 *groupColIdx = NULL;
1473 * If we're not grouping or aggregating, there's nothing to do here;
1474 * query_planner should receive the unmodified target list.
1476 if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1478 *need_tlist_eval = true;
1483 * Otherwise, start with a "flattened" tlist (having just the vars
1484 * mentioned in the targetlist and HAVING qual --- but not upper- level
1485 * Vars; they will be replaced by Params later on).
1487 sub_tlist = flatten_tlist(tlist);
1488 extravars = pull_var_clause(parse->havingQual, false);
1489 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1490 list_free(extravars);
1491 *need_tlist_eval = false; /* only eval if not flat tlist */
1494 * If grouping, create sub_tlist entries for all GROUP BY expressions
1495 * (GROUP BY items that are simple Vars should be in the list already),
1496 * and make an array showing where the group columns are in the sub_tlist.
1498 numCols = list_length(parse->groupClause);
1502 AttrNumber *grpColIdx;
1505 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1506 *groupColIdx = grpColIdx;
1508 foreach(gl, parse->groupClause)
1510 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1511 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1512 TargetEntry *te = NULL;
1515 /* Find or make a matching sub_tlist entry */
1516 foreach(sl, sub_tlist)
1518 te = (TargetEntry *) lfirst(sl);
1519 if (equal(groupexpr, te->expr))
1524 te = makeTargetEntry((Expr *) groupexpr,
1525 list_length(sub_tlist) + 1,
1528 sub_tlist = lappend(sub_tlist, te);
1529 *need_tlist_eval = true; /* it's not flat anymore */
1532 /* and save its resno */
1533 grpColIdx[keyno++] = te->resno;
1541 * locate_grouping_columns
1542 * Locate grouping columns in the tlist chosen by query_planner.
1544 * This is only needed if we don't use the sub_tlist chosen by
1545 * make_subplanTargetList. We have to forget the column indexes found
1546 * by that routine and re-locate the grouping vars in the real sub_tlist.
1549 locate_grouping_columns(PlannerInfo *root,
1552 AttrNumber *groupColIdx)
1558 * No work unless grouping.
1560 if (!root->parse->groupClause)
1562 Assert(groupColIdx == NULL);
1565 Assert(groupColIdx != NULL);
1567 foreach(gl, root->parse->groupClause)
1569 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1570 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1571 TargetEntry *te = NULL;
1574 foreach(sl, sub_tlist)
1576 te = (TargetEntry *) lfirst(sl);
1577 if (equal(groupexpr, te->expr))
1581 elog(ERROR, "failed to locate grouping columns");
1583 groupColIdx[keyno++] = te->resno;
1588 * postprocess_setop_tlist
1589 * Fix up targetlist returned by plan_set_operations().
1591 * We need to transpose sort key info from the orig_tlist into new_tlist.
1592 * NOTE: this would not be good enough if we supported resjunk sort keys
1593 * for results of set operations --- then, we'd need to project a whole
1594 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1595 * find any resjunk columns in orig_tlist.
1598 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1601 ListCell *orig_tlist_item = list_head(orig_tlist);
1603 foreach(l, new_tlist)
1605 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1606 TargetEntry *orig_tle;
1608 /* ignore resjunk columns in setop result */
1609 if (new_tle->resjunk)
1612 Assert(orig_tlist_item != NULL);
1613 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1614 orig_tlist_item = lnext(orig_tlist_item);
1615 if (orig_tle->resjunk) /* should not happen */
1616 elog(ERROR, "resjunk output columns are not implemented");
1617 Assert(new_tle->resno == orig_tle->resno);
1618 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1620 if (orig_tlist_item != NULL)
1621 elog(ERROR, "resjunk output columns are not implemented");