1 /*-------------------------------------------------------------------------
4 * The query optimizer external interface.
6 * Portions Copyright (c) 1996-2005, 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.194 2005/10/15 02:49:20 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 #ifdef OPTIMIZER_DEBUG
27 #include "nodes/print.h"
29 #include "optimizer/clauses.h"
30 #include "optimizer/cost.h"
31 #include "optimizer/pathnode.h"
32 #include "optimizer/paths.h"
33 #include "optimizer/planmain.h"
34 #include "optimizer/planner.h"
35 #include "optimizer/prep.h"
36 #include "optimizer/subselect.h"
37 #include "optimizer/tlist.h"
38 #include "optimizer/var.h"
39 #include "parser/parsetree.h"
40 #include "parser/parse_expr.h"
41 #include "parser/parse_oper.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
57 static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
58 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
59 static Plan *inheritance_planner(PlannerInfo *root, List *inheritlist);
60 static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
61 static double preprocess_limit(PlannerInfo *root,
62 double tuple_fraction,
63 int *offset_est, int *count_est);
64 static bool choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
65 Path *cheapest_path, Path *sorted_path,
66 double dNumGroups, AggClauseCounts *agg_counts);
67 static bool hash_safe_grouping(PlannerInfo *root);
68 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
69 AttrNumber **groupColIdx, bool *need_tlist_eval);
70 static void locate_grouping_columns(PlannerInfo *root,
73 AttrNumber *groupColIdx);
74 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
77 /*****************************************************************************
79 * Query optimizer entry point
81 *****************************************************************************/
83 planner(Query *parse, bool isCursor, int cursorOptions,
84 ParamListInfo boundParams)
86 double tuple_fraction;
88 Index save_PlannerQueryLevel;
89 List *save_PlannerParamList;
90 ParamListInfo save_PlannerBoundParamList;
93 * The planner can be called recursively (an example is when
94 * eval_const_expressions tries to pre-evaluate an SQL function). So,
95 * these global state variables must be saved and restored.
97 * Query level and the param list cannot be moved into the per-query
98 * PlannerInfo structure since their whole purpose is communication across
99 * multiple sub-queries. Also, boundParams is explicitly info from outside
100 * the query, and so is likewise better handled as a global variable.
102 * Note we do NOT save and restore PlannerPlanId: it exists to assign unique
103 * IDs to SubPlan nodes, and we want those IDs to be unique for the life
104 * of a backend. Also, PlannerInitPlan is saved/restored in
105 * subquery_planner, not here.
107 save_PlannerQueryLevel = PlannerQueryLevel;
108 save_PlannerParamList = PlannerParamList;
109 save_PlannerBoundParamList = PlannerBoundParamList;
111 /* Initialize state for handling outer-level references and params */
112 PlannerQueryLevel = 0; /* will be 1 in top-level subquery_planner */
113 PlannerParamList = NIL;
114 PlannerBoundParamList = boundParams;
116 /* Determine what fraction of the plan is likely to be scanned */
120 * We have no real idea how many tuples the user will ultimately FETCH
121 * from a cursor, but it seems a good bet that he doesn't want 'em
122 * all. Optimize for 10% retrieval (you gotta better number? Should
123 * this be a SETtable parameter?)
125 tuple_fraction = 0.10;
129 /* Default assumption is we need all the tuples */
130 tuple_fraction = 0.0;
133 /* primary planning entry point (may recurse for subqueries) */
134 result_plan = subquery_planner(parse, tuple_fraction, NULL);
136 /* check we popped out the right number of levels */
137 Assert(PlannerQueryLevel == 0);
140 * If creating a plan for a scrollable cursor, make sure it can run
141 * backwards on demand. Add a Material node at the top at need.
143 if (isCursor && (cursorOptions & CURSOR_OPT_SCROLL))
145 if (!ExecSupportsBackwardScan(result_plan))
146 result_plan = materialize_finished_plan(result_plan);
149 /* final cleanup of the plan */
150 result_plan = set_plan_references(result_plan, parse->rtable);
152 /* executor wants to know total number of Params used overall */
153 result_plan->nParamExec = list_length(PlannerParamList);
155 /* restore state for outer planner, if any */
156 PlannerQueryLevel = save_PlannerQueryLevel;
157 PlannerParamList = save_PlannerParamList;
158 PlannerBoundParamList = save_PlannerBoundParamList;
164 /*--------------------
166 * Invokes the planner on a subquery. We recurse to here for each
167 * sub-SELECT found in the query tree.
169 * parse is the querytree produced by the parser & rewriter.
170 * tuple_fraction is the fraction of tuples we expect will be retrieved.
171 * tuple_fraction is interpreted as explained for grouping_planner, below.
173 * If subquery_pathkeys isn't NULL, it receives a list of pathkeys indicating
174 * the output sort ordering of the completed plan.
176 * Basically, this routine does the stuff that should only be done once
177 * per Query object. It then calls grouping_planner. At one time,
178 * grouping_planner could be invoked recursively on the same Query object;
179 * that's not currently true, but we keep the separation between the two
180 * routines anyway, in case we need it again someday.
182 * subquery_planner will be called recursively to handle sub-Query nodes
183 * found within the query's expressions and rangetable.
185 * Returns a query plan.
186 *--------------------
189 subquery_planner(Query *parse, double tuple_fraction,
190 List **subquery_pathkeys)
192 List *saved_initplan = PlannerInitPlan;
193 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);
209 * Look for IN clauses at the top level of WHERE, and transform them into
210 * joins. Note that this step only handles IN clauses originally at top
211 * level of WHERE; if we pull up any subqueries in the next step, their
212 * INs are processed just before pulling them up.
214 root->in_info_list = NIL;
215 if (parse->hasSubLinks)
216 parse->jointree->quals = pull_up_IN_clauses(root,
217 parse->jointree->quals);
220 * Check to see if any subqueries in the rangetable can be merged into
223 parse->jointree = (FromExpr *)
224 pull_up_subqueries(root, (Node *) parse->jointree, false);
227 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
228 * avoid the expense of doing flatten_join_alias_vars(). Also check for
229 * outer joins --- if none, we can skip reduce_outer_joins() and some
230 * other processing. This must be done after we have done
231 * pull_up_subqueries, of course.
233 * Note: if reduce_outer_joins manages to eliminate all outer joins,
234 * root->hasOuterJoins is not reset currently. This is OK since its
235 * purpose is merely to suppress unnecessary processing in simple cases.
237 root->hasJoinRTEs = false;
238 root->hasOuterJoins = false;
239 foreach(l, parse->rtable)
241 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
243 if (rte->rtekind == RTE_JOIN)
245 root->hasJoinRTEs = true;
246 if (IS_OUTER_JOIN(rte->jointype))
248 root->hasOuterJoins = true;
249 /* Can quit scanning once we find an outer join */
256 * Set hasHavingQual to remember if HAVING clause is present. Needed
257 * because preprocess_expression will reduce a constant-true condition to
258 * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
260 root->hasHavingQual = (parse->havingQual != NULL);
263 * Do expression preprocessing on targetlist and quals.
265 parse->targetList = (List *)
266 preprocess_expression(root, (Node *) parse->targetList,
269 preprocess_qual_conditions(root, (Node *) parse->jointree);
271 parse->havingQual = preprocess_expression(root, parse->havingQual,
274 parse->limitOffset = preprocess_expression(root, parse->limitOffset,
276 parse->limitCount = preprocess_expression(root, parse->limitCount,
279 root->in_info_list = (List *)
280 preprocess_expression(root, (Node *) root->in_info_list,
283 /* Also need to preprocess expressions for function RTEs */
284 foreach(l, parse->rtable)
286 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
288 if (rte->rtekind == RTE_FUNCTION)
289 rte->funcexpr = preprocess_expression(root, rte->funcexpr,
294 * In some cases we may want to transfer a HAVING clause into WHERE. We
295 * cannot do so if the HAVING clause contains aggregates (obviously) or
296 * volatile functions (since a HAVING clause is supposed to be executed
297 * only once per group). Also, it may be that the clause is so expensive
298 * to execute that we're better off doing it only once per group, despite
299 * the loss of selectivity. This is hard to estimate short of doing the
300 * entire planning process twice, so we use a heuristic: clauses
301 * containing subplans are left in HAVING. Otherwise, we move or copy the
302 * HAVING clause into WHERE, in hopes of eliminating tuples before
303 * aggregation instead of after.
305 * If the query has explicit grouping then we can simply move such a clause
306 * into WHERE; any group that fails the clause will not be in the output
307 * because none of its tuples will reach the grouping or aggregation
308 * stage. Otherwise we must have a degenerate (variable-free) HAVING
309 * clause, which we put in WHERE so that query_planner() can use it in a
310 * gating Result node, but also keep in HAVING to ensure that we don't
311 * emit a bogus aggregated row. (This could be done better, but it seems
312 * not worth optimizing.)
314 * Note that both havingQual and parse->jointree->quals are in
315 * implicitly-ANDed-list form at this point, even though they are declared
319 foreach(l, (List *) parse->havingQual)
321 Node *havingclause = (Node *) lfirst(l);
323 if (contain_agg_clause(havingclause) ||
324 contain_volatile_functions(havingclause) ||
325 contain_subplans(havingclause))
327 /* keep it in HAVING */
328 newHaving = lappend(newHaving, havingclause);
330 else if (parse->groupClause)
332 /* move it to WHERE */
333 parse->jointree->quals = (Node *)
334 lappend((List *) parse->jointree->quals, havingclause);
338 /* put a copy in WHERE, keep it in HAVING */
339 parse->jointree->quals = (Node *)
340 lappend((List *) parse->jointree->quals,
341 copyObject(havingclause));
342 newHaving = lappend(newHaving, havingclause);
345 parse->havingQual = (Node *) newHaving;
348 * If we have any outer joins, try to reduce them to plain inner joins.
349 * This step is most easily done after we've done expression
352 if (root->hasOuterJoins)
353 reduce_outer_joins(root);
356 * See if we can simplify the jointree; opportunities for this may come
357 * from having pulled up subqueries, or from flattening explicit JOIN
358 * syntax. We must do this after flattening JOIN alias variables, since
359 * eliminating explicit JOIN nodes from the jointree will cause
360 * get_relids_for_join() to fail. But it should happen after
361 * reduce_outer_joins, anyway.
363 parse->jointree = (FromExpr *)
364 simplify_jointree(root, (Node *) parse->jointree);
367 * Do the main planning. If we have an inherited target relation, that
368 * needs special processing, else go straight to grouping_planner.
370 if (parse->resultRelation &&
371 (lst = expand_inherited_rtentry(root, parse->resultRelation)) != NIL)
372 plan = inheritance_planner(root, lst);
374 plan = grouping_planner(root, tuple_fraction);
377 * If any subplans were generated, or if we're inside a subplan, build
378 * initPlan list and extParam/allParam sets for plan nodes, and attach the
379 * initPlans to the top plan node.
381 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
382 SS_finalize_plan(plan, parse->rtable);
384 /* Return sort ordering info if caller wants it */
385 if (subquery_pathkeys)
386 *subquery_pathkeys = root->query_pathkeys;
388 /* Return to outer subquery context */
390 PlannerInitPlan = saved_initplan;
391 /* we do NOT restore PlannerPlanId; that's not an oversight! */
397 * preprocess_expression
398 * Do subquery_planner's preprocessing work for an expression,
399 * which can be a targetlist, a WHERE clause (including JOIN/ON
400 * conditions), or a HAVING clause.
403 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
406 * Fall out quickly if expression is empty. This occurs often enough to
407 * be worth checking. Note that null->null is the correct conversion for
408 * implicit-AND result format, too.
414 * If the query has any join RTEs, replace join alias variables with
415 * base-relation variables. We must do this before sublink processing,
416 * else sublinks expanded out from join aliases wouldn't get processed.
418 if (root->hasJoinRTEs)
419 expr = flatten_join_alias_vars(root, expr);
422 * Simplify constant expressions.
424 * Note: this also flattens nested AND and OR expressions into N-argument
425 * form. All processing of a qual expression after this point must be
426 * careful to maintain AND/OR flatness --- that is, do not generate a tree
427 * with AND directly under AND, nor OR directly under OR.
429 * Because this is a relatively expensive process, we skip it when the query
430 * is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()". The
431 * expression will only be evaluated once anyway, so no point in
432 * pre-simplifying; we can't execute it any faster than the executor can,
433 * and we will waste cycles copying the tree. Notice however that we
434 * still must do it for quals (to get AND/OR flatness); and if we are in a
435 * subquery we should not assume it will be done only once.
437 if (root->parse->jointree->fromlist != NIL ||
438 kind == EXPRKIND_QUAL ||
439 PlannerQueryLevel > 1)
440 expr = eval_const_expressions(expr);
443 * If it's a qual or havingQual, canonicalize it.
445 if (kind == EXPRKIND_QUAL)
447 expr = (Node *) canonicalize_qual((Expr *) expr);
449 #ifdef OPTIMIZER_DEBUG
450 printf("After canonicalize_qual()\n");
455 /* Expand SubLinks to SubPlans */
456 if (root->parse->hasSubLinks)
457 expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL));
460 * XXX do not insert anything here unless you have grokked the comments in
461 * SS_replace_correlation_vars ...
464 /* Replace uplevel vars with Param nodes */
465 if (PlannerQueryLevel > 1)
466 expr = SS_replace_correlation_vars(expr);
469 * If it's a qual or havingQual, convert it to implicit-AND format. (We
470 * don't want to do this before eval_const_expressions, since the latter
471 * would be unable to simplify a top-level AND correctly. Also,
472 * SS_process_sublinks expects explicit-AND format.)
474 if (kind == EXPRKIND_QUAL)
475 expr = (Node *) make_ands_implicit((Expr *) expr);
481 * preprocess_qual_conditions
482 * Recursively scan the query's jointree and do subquery_planner's
483 * preprocessing work on each qual condition found therein.
486 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
490 if (IsA(jtnode, RangeTblRef))
492 /* nothing to do here */
494 else if (IsA(jtnode, FromExpr))
496 FromExpr *f = (FromExpr *) jtnode;
499 foreach(l, f->fromlist)
500 preprocess_qual_conditions(root, lfirst(l));
502 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
504 else if (IsA(jtnode, JoinExpr))
506 JoinExpr *j = (JoinExpr *) jtnode;
508 preprocess_qual_conditions(root, j->larg);
509 preprocess_qual_conditions(root, j->rarg);
511 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
514 elog(ERROR, "unrecognized node type: %d",
515 (int) nodeTag(jtnode));
518 /*--------------------
519 * inheritance_planner
520 * Generate a plan in the case where the result relation is an
523 * We have to handle this case differently from cases where a source
524 * relation is an inheritance set. Source inheritance is expanded at
525 * the bottom of the plan tree (see allpaths.c), but target inheritance
526 * has to be expanded at the top. The reason is that for UPDATE, each
527 * target relation needs a different targetlist matching its own column
528 * set. (This is not so critical for DELETE, but for simplicity we treat
529 * inherited DELETE the same way.) Fortunately, the UPDATE/DELETE target
530 * can never be the nullable side of an outer join, so it's OK to generate
533 * inheritlist is an integer list of RT indexes for the result relation set.
535 * Returns a query plan.
536 *--------------------
539 inheritance_planner(PlannerInfo *root, List *inheritlist)
541 Query *parse = root->parse;
542 int parentRTindex = parse->resultRelation;
543 Oid parentOID = getrelid(parentRTindex, parse->rtable);
544 int mainrtlength = list_length(parse->rtable);
545 List *subplans = NIL;
549 foreach(l, inheritlist)
551 int childRTindex = lfirst_int(l);
552 Oid childOID = getrelid(childRTindex, parse->rtable);
557 * Generate modified query with this rel as target. We have to be
558 * prepared to translate varnos in in_info_list as well as in the
561 memcpy(&subroot, root, sizeof(PlannerInfo));
562 subroot.parse = (Query *)
563 adjust_inherited_attrs((Node *) parse,
564 parentRTindex, parentOID,
565 childRTindex, childOID);
566 subroot.in_info_list = (List *)
567 adjust_inherited_attrs((Node *) root->in_info_list,
568 parentRTindex, parentOID,
569 childRTindex, childOID);
572 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
574 subplans = lappend(subplans, subplan);
577 * XXX my goodness this next bit is ugly. Really need to think about
578 * ways to rein in planner's habit of scribbling on its input.
580 * Planning of the subquery might have modified the rangetable, either by
581 * addition of RTEs due to expansion of inherited source tables, or by
582 * changes of the Query structures inside subquery RTEs. We have to
583 * ensure that this gets propagated back to the master copy. However,
584 * if we aren't done planning yet, we also need to ensure that
585 * subsequent calls to grouping_planner have virgin sub-Queries to
586 * work from. So, if we are at the last list entry, just copy the
587 * subquery rangetable back to the master copy; if we are not, then
588 * extend the master copy by adding whatever the subquery added. (We
589 * assume these added entries will go untouched by the future
590 * grouping_planner calls. We are also effectively assuming that
591 * sub-Queries will get planned identically each time, or at least
592 * that the impacts on their rangetables will be the same each time.
593 * Did I say this is ugly?)
595 if (lnext(l) == NULL)
596 parse->rtable = subroot.parse->rtable;
599 int subrtlength = list_length(subroot.parse->rtable);
601 if (subrtlength > mainrtlength)
605 subrt = list_copy_tail(subroot.parse->rtable, mainrtlength);
606 parse->rtable = list_concat(parse->rtable, subrt);
607 mainrtlength = subrtlength;
611 /* Save preprocessed tlist from first rel for use in Append */
613 tlist = subplan->targetlist;
616 /* Save the target-relations list for the executor, too */
617 parse->resultRelations = inheritlist;
619 /* Mark result as unordered (probably unnecessary) */
620 root->query_pathkeys = NIL;
622 return (Plan *) make_append(subplans, true, tlist);
625 /*--------------------
627 * Perform planning steps related to grouping, aggregation, etc.
628 * This primarily means adding top-level processing to the basic
629 * query plan produced by query_planner.
631 * tuple_fraction is the fraction of tuples we expect will be retrieved
633 * tuple_fraction is interpreted as follows:
634 * 0: expect all tuples to be retrieved (normal case)
635 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
636 * from the plan to be retrieved
637 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
638 * expected to be retrieved (ie, a LIMIT specification)
640 * Returns a query plan. Also, root->query_pathkeys is returned as the
641 * actual output ordering of the plan (in pathkey format).
642 *--------------------
645 grouping_planner(PlannerInfo *root, double tuple_fraction)
647 Query *parse = root->parse;
648 List *tlist = parse->targetList;
652 List *current_pathkeys;
654 double dNumGroups = 0;
656 /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
657 if (parse->limitCount || parse->limitOffset)
658 tuple_fraction = preprocess_limit(root, tuple_fraction,
659 &offset_est, &count_est);
661 if (parse->setOperations)
663 List *set_sortclauses;
666 * If there's a top-level ORDER BY, assume we have to fetch all the
667 * tuples. This might seem too simplistic given all the hackery below
668 * to possibly avoid the sort ... but a nonzero tuple_fraction is only
669 * of use to plan_set_operations() when the setop is UNION ALL, and
670 * the result of UNION ALL is always unsorted.
672 if (parse->sortClause)
673 tuple_fraction = 0.0;
676 * Construct the plan for set operations. The result will not need
677 * any work except perhaps a top-level sort and/or LIMIT.
679 result_plan = plan_set_operations(root, tuple_fraction,
683 * Calculate pathkeys representing the sort order (if any) of the set
684 * operation's result. We have to do this before overwriting the sort
687 current_pathkeys = make_pathkeys_for_sortclauses(set_sortclauses,
688 result_plan->targetlist);
689 current_pathkeys = canonicalize_pathkeys(root, current_pathkeys);
692 * We should not need to call preprocess_targetlist, since we must be
693 * in a SELECT query node. Instead, use the targetlist returned by
694 * plan_set_operations (since this tells whether it returned any
695 * resjunk columns!), and transfer any sort key information from the
698 Assert(parse->commandType == CMD_SELECT);
700 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
703 * Can't handle FOR UPDATE/SHARE here (parser should have checked
704 * already, but let's make sure).
708 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
709 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
712 * Calculate pathkeys that represent result ordering requirements
714 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
716 sort_pathkeys = canonicalize_pathkeys(root, sort_pathkeys);
720 /* No set operations, do regular planning */
722 List *group_pathkeys;
723 AttrNumber *groupColIdx = NULL;
724 bool need_tlist_eval = true;
730 AggClauseCounts agg_counts;
731 int numGroupCols = list_length(parse->groupClause);
732 bool use_hashed_grouping = false;
734 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
736 /* Preprocess targetlist */
737 tlist = preprocess_targetlist(root, tlist);
740 * Generate appropriate target list for subplan; may be different from
741 * tlist if grouping or aggregation is needed.
743 sub_tlist = make_subplanTargetList(root, tlist,
744 &groupColIdx, &need_tlist_eval);
747 * Calculate pathkeys that represent grouping/ordering requirements.
748 * Stash them in PlannerInfo so that query_planner can canonicalize
751 root->group_pathkeys =
752 make_pathkeys_for_sortclauses(parse->groupClause, tlist);
753 root->sort_pathkeys =
754 make_pathkeys_for_sortclauses(parse->sortClause, tlist);
757 * Will need actual number of aggregates for estimating costs.
759 * Note: we do not attempt to detect duplicate aggregates here; a
760 * somewhat-overestimated count is okay for our present purposes.
762 * Note: think not that we can turn off hasAggs if we find no aggs. It is
763 * possible for constant-expression simplification to remove all
764 * explicit references to aggs, but we still have to follow the
765 * aggregate semantics (eg, producing only one output row).
769 count_agg_clauses((Node *) tlist, &agg_counts);
770 count_agg_clauses(parse->havingQual, &agg_counts);
774 * Figure out whether we need a sorted result from query_planner.
776 * If we have a GROUP BY clause, then we want a result sorted properly
777 * for grouping. Otherwise, if there is an ORDER BY clause, we want
778 * to sort by the ORDER BY clause. (Note: if we have both, and ORDER
779 * BY is a superset of GROUP BY, it would be tempting to request sort
780 * by ORDER BY --- but that might just leave us failing to exploit an
781 * available sort order at all. Needs more thought...)
783 if (parse->groupClause)
784 root->query_pathkeys = root->group_pathkeys;
785 else if (parse->sortClause)
786 root->query_pathkeys = root->sort_pathkeys;
788 root->query_pathkeys = NIL;
791 * Generate the best unsorted and presorted paths for this Query (but
792 * note there may not be any presorted path). query_planner will also
793 * estimate the number of groups in the query, and canonicalize all
796 query_planner(root, sub_tlist, tuple_fraction,
797 &cheapest_path, &sorted_path, &dNumGroups);
799 group_pathkeys = root->group_pathkeys;
800 sort_pathkeys = root->sort_pathkeys;
803 * If grouping, decide whether we want to use hashed grouping.
805 if (parse->groupClause)
807 use_hashed_grouping =
808 choose_hashed_grouping(root, tuple_fraction,
809 cheapest_path, sorted_path,
810 dNumGroups, &agg_counts);
812 /* Also convert # groups to long int --- but 'ware overflow! */
813 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
817 * Select the best path. If we are doing hashed grouping, we will
818 * always read all the input tuples, so use the cheapest-total path.
819 * Otherwise, trust query_planner's decision about which to use.
821 if (use_hashed_grouping || !sorted_path)
822 best_path = cheapest_path;
824 best_path = sorted_path;
827 * Check to see if it's possible to optimize MIN/MAX aggregates. If
828 * so, we will forget all the work we did so far to choose a "regular"
829 * path ... but we had to do it anyway to be able to tell which way is
832 result_plan = optimize_minmax_aggregates(root,
835 if (result_plan != NULL)
838 * optimize_minmax_aggregates generated the full plan, with the
839 * right tlist, and it has no sort order.
841 current_pathkeys = NIL;
846 * Normal case --- create a plan according to query_planner's
849 result_plan = create_plan(root, best_path);
850 current_pathkeys = best_path->pathkeys;
853 * create_plan() returns a plan with just a "flat" tlist of
854 * required Vars. Usually we need to insert the sub_tlist as the
855 * tlist of the top plan node. However, we can skip that if we
856 * determined that whatever query_planner chose to return will be
862 * If the top-level plan node is one that cannot do expression
863 * evaluation, we must insert a Result node to project the
866 if (!is_projection_capable_plan(result_plan))
868 result_plan = (Plan *) make_result(sub_tlist, NULL,
874 * Otherwise, just replace the subplan's flat tlist with
877 result_plan->targetlist = sub_tlist;
881 * Also, account for the cost of evaluation of the sub_tlist.
883 * Up to now, we have only been dealing with "flat" tlists,
884 * containing just Vars. So their evaluation cost is zero
885 * according to the model used by cost_qual_eval() (or if you
886 * prefer, the cost is factored into cpu_tuple_cost). Thus we
887 * can avoid accounting for tlist cost throughout
888 * query_planner() and subroutines. But now we've inserted a
889 * tlist that might contain actual operators, sub-selects, etc
890 * --- so we'd better account for its cost.
892 * Below this point, any tlist eval cost for added-on nodes
893 * should be accounted for as we create those nodes.
894 * Presently, of the node types we can add on, only Agg and
895 * Group project new tlists (the rest just copy their input
896 * tuples) --- so make_agg() and make_group() are responsible
897 * for computing the added cost.
899 cost_qual_eval(&tlist_cost, sub_tlist);
900 result_plan->startup_cost += tlist_cost.startup;
901 result_plan->total_cost += tlist_cost.startup +
902 tlist_cost.per_tuple * result_plan->plan_rows;
907 * Since we're using query_planner's tlist and not the one
908 * make_subplanTargetList calculated, we have to refigure any
909 * grouping-column indexes make_subplanTargetList computed.
911 locate_grouping_columns(root, tlist, result_plan->targetlist,
916 * Insert AGG or GROUP node if needed, plus an explicit sort step
919 * HAVING clause, if any, becomes qual of the Agg or Group node.
921 if (use_hashed_grouping)
923 /* Hashed aggregate plan --- no sort needed */
924 result_plan = (Plan *) make_agg(root,
926 (List *) parse->havingQual,
933 /* Hashed aggregation produces randomly-ordered results */
934 current_pathkeys = NIL;
936 else if (parse->hasAggs)
938 /* Plain aggregate plan --- sort if needed */
939 AggStrategy aggstrategy;
941 if (parse->groupClause)
943 if (!pathkeys_contained_in(group_pathkeys,
946 result_plan = (Plan *)
947 make_sort_from_groupcols(root,
951 current_pathkeys = group_pathkeys;
953 aggstrategy = AGG_SORTED;
956 * The AGG node will not change the sort ordering of its
957 * groups, so current_pathkeys describes the result too.
962 aggstrategy = AGG_PLAIN;
963 /* Result will be only one row anyway; no sort order */
964 current_pathkeys = NIL;
967 result_plan = (Plan *) make_agg(root,
969 (List *) parse->havingQual,
977 else if (parse->groupClause)
980 * GROUP BY without aggregation, so insert a group node (plus
981 * the appropriate sort node, if necessary).
983 * Add an explicit sort if we couldn't make the path come out the
984 * way the GROUP node needs it.
986 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
988 result_plan = (Plan *)
989 make_sort_from_groupcols(root,
993 current_pathkeys = group_pathkeys;
996 result_plan = (Plan *) make_group(root,
998 (List *) parse->havingQual,
1003 /* The Group node won't change sort ordering */
1005 else if (root->hasHavingQual)
1008 * No aggregates, and no GROUP BY, but we have a HAVING qual.
1009 * This is a degenerate case in which we are supposed to emit
1010 * either 0 or 1 row depending on whether HAVING succeeds.
1011 * Furthermore, there cannot be any variables in either HAVING
1012 * or the targetlist, so we actually do not need the FROM
1013 * table at all! We can just throw away the plan-so-far and
1014 * generate a Result node. This is a sufficiently unusual
1015 * corner case that it's not worth contorting the structure of
1016 * this routine to avoid having to generate the plan in the
1019 result_plan = (Plan *) make_result(tlist,
1023 } /* end of non-minmax-aggregate case */
1024 } /* end of if (setOperations) */
1027 * If we were not able to make the plan come out in the right order, add
1028 * an explicit sort step.
1030 if (parse->sortClause)
1032 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1034 result_plan = (Plan *)
1035 make_sort_from_sortclauses(root,
1038 current_pathkeys = sort_pathkeys;
1043 * If there is a DISTINCT clause, add the UNIQUE node.
1045 if (parse->distinctClause)
1047 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1050 * If there was grouping or aggregation, leave plan_rows as-is (ie,
1051 * assume the result was already mostly unique). If not, use the
1052 * number of distinct-groups calculated by query_planner.
1054 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1055 result_plan->plan_rows = dNumGroups;
1059 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1061 if (parse->limitCount || parse->limitOffset)
1063 result_plan = (Plan *) make_limit(result_plan,
1071 * Return the actual output ordering in query_pathkeys for possible use by
1072 * an outer query level.
1074 root->query_pathkeys = current_pathkeys;
1080 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1082 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1083 * results back in *count_est and *offset_est. These variables are set to
1084 * 0 if the corresponding clause is not present, and -1 if it's present
1085 * but we couldn't estimate the value for it. (The "0" convention is OK
1086 * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1087 * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
1088 * usual practice of never estimating less than one row.) These values will
1089 * be passed to make_limit, which see if you change this code.
1091 * The return value is the suitably adjusted tuple_fraction to use for
1092 * planning the query. This adjustment is not overridable, since it reflects
1093 * plan actions that grouping_planner() will certainly take, not assumptions
1097 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1098 int *offset_est, int *count_est)
1100 Query *parse = root->parse;
1102 double limit_fraction;
1104 /* Should not be called unless LIMIT or OFFSET */
1105 Assert(parse->limitCount || parse->limitOffset);
1108 * Try to obtain the clause values. We use estimate_expression_value
1109 * primarily because it can sometimes do something useful with Params.
1111 if (parse->limitCount)
1113 est = estimate_expression_value(parse->limitCount);
1114 if (est && IsA(est, Const))
1116 if (((Const *) est)->constisnull)
1118 /* NULL indicates LIMIT ALL, ie, no limit */
1119 *count_est = 0; /* treat as not present */
1123 *count_est = DatumGetInt32(((Const *) est)->constvalue);
1124 if (*count_est <= 0)
1125 *count_est = 1; /* force to at least 1 */
1129 *count_est = -1; /* can't estimate */
1132 *count_est = 0; /* not present */
1134 if (parse->limitOffset)
1136 est = estimate_expression_value(parse->limitOffset);
1137 if (est && IsA(est, Const))
1139 if (((Const *) est)->constisnull)
1141 /* Treat NULL as no offset; the executor will too */
1142 *offset_est = 0; /* treat as not present */
1146 *offset_est = DatumGetInt32(((Const *) est)->constvalue);
1147 if (*offset_est < 0)
1148 *offset_est = 0; /* less than 0 is same as 0 */
1152 *offset_est = -1; /* can't estimate */
1155 *offset_est = 0; /* not present */
1157 if (*count_est != 0)
1160 * A LIMIT clause limits the absolute number of tuples returned.
1161 * However, if it's not a constant LIMIT then we have to guess; for
1162 * lack of a better idea, assume 10% of the plan's result is wanted.
1164 if (*count_est < 0 || *offset_est < 0)
1166 /* LIMIT or OFFSET is an expression ... punt ... */
1167 limit_fraction = 0.10;
1171 /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
1172 limit_fraction = (double) *count_est + (double) *offset_est;
1176 * If we have absolute limits from both caller and LIMIT, use the
1177 * smaller value; likewise if they are both fractional. If one is
1178 * fractional and the other absolute, we can't easily determine which
1179 * is smaller, but we use the heuristic that the absolute will usually
1182 if (tuple_fraction >= 1.0)
1184 if (limit_fraction >= 1.0)
1187 tuple_fraction = Min(tuple_fraction, limit_fraction);
1191 /* caller absolute, limit fractional; use caller's value */
1194 else if (tuple_fraction > 0.0)
1196 if (limit_fraction >= 1.0)
1198 /* caller fractional, limit absolute; use limit */
1199 tuple_fraction = limit_fraction;
1203 /* both fractional */
1204 tuple_fraction = Min(tuple_fraction, limit_fraction);
1209 /* no info from caller, just use limit */
1210 tuple_fraction = limit_fraction;
1213 else if (*offset_est != 0 && tuple_fraction > 0.0)
1216 * We have an OFFSET but no LIMIT. This acts entirely differently
1217 * from the LIMIT case: here, we need to increase rather than decrease
1218 * the caller's tuple_fraction, because the OFFSET acts to cause more
1219 * tuples to be fetched instead of fewer. This only matters if we got
1220 * a tuple_fraction > 0, however.
1222 * As above, use 10% if OFFSET is present but unestimatable.
1224 if (*offset_est < 0)
1225 limit_fraction = 0.10;
1227 limit_fraction = (double) *offset_est;
1230 * If we have absolute counts from both caller and OFFSET, add them
1231 * together; likewise if they are both fractional. If one is
1232 * fractional and the other absolute, we want to take the larger, and
1233 * we heuristically assume that's the fractional one.
1235 if (tuple_fraction >= 1.0)
1237 if (limit_fraction >= 1.0)
1239 /* both absolute, so add them together */
1240 tuple_fraction += limit_fraction;
1244 /* caller absolute, limit fractional; use limit */
1245 tuple_fraction = limit_fraction;
1250 if (limit_fraction >= 1.0)
1252 /* caller fractional, limit absolute; use caller's value */
1256 /* both fractional, so add them together */
1257 tuple_fraction += limit_fraction;
1258 if (tuple_fraction >= 1.0)
1259 tuple_fraction = 0.0; /* assume fetch all */
1264 return tuple_fraction;
1268 * choose_hashed_grouping - should we use hashed grouping?
1271 choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
1272 Path *cheapest_path, Path *sorted_path,
1273 double dNumGroups, AggClauseCounts *agg_counts)
1275 int numGroupCols = list_length(root->parse->groupClause);
1276 double cheapest_path_rows;
1277 int cheapest_path_width;
1279 List *current_pathkeys;
1284 * Check can't-do-it conditions, including whether the grouping operators
1287 * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1288 * (Doing so would imply storing *all* the input values in the hash table,
1289 * which seems like a certain loser.)
1291 if (!enable_hashagg)
1293 if (agg_counts->numDistinctAggs != 0)
1295 if (!hash_safe_grouping(root))
1299 * Don't do it if it doesn't look like the hashtable will fit into
1302 * Beware here of the possibility that cheapest_path->parent is NULL. This
1303 * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
1305 if (cheapest_path->parent)
1307 cheapest_path_rows = cheapest_path->parent->rows;
1308 cheapest_path_width = cheapest_path->parent->width;
1312 cheapest_path_rows = 1; /* assume non-set result */
1313 cheapest_path_width = 100; /* arbitrary */
1316 /* Estimate per-hash-entry space at tuple width... */
1317 hashentrysize = cheapest_path_width;
1318 /* plus space for pass-by-ref transition values... */
1319 hashentrysize += agg_counts->transitionSpace;
1320 /* plus the per-hash-entry overhead */
1321 hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1323 if (hashentrysize * dNumGroups > work_mem * 1024L)
1327 * See if the estimated cost is no more than doing it the other way. While
1328 * avoiding the need for sorted input is usually a win, the fact that the
1329 * output won't be sorted may be a loss; so we need to do an actual cost
1332 * We need to consider cheapest_path + hashagg [+ final sort] versus either
1333 * cheapest_path [+ sort] + group or agg [+ final sort] or presorted_path
1334 * + group or agg [+ final sort] where brackets indicate a step that may
1335 * not be needed. We assume query_planner() will have returned a presorted
1336 * path only if it's a winner compared to cheapest_path for this purpose.
1338 * These path variables are dummies that just hold cost fields; we don't make
1339 * actual Paths for these steps.
1341 cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1342 numGroupCols, dNumGroups,
1343 cheapest_path->startup_cost, cheapest_path->total_cost,
1344 cheapest_path_rows);
1345 /* Result of hashed agg is always unsorted */
1346 if (root->sort_pathkeys)
1347 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
1348 dNumGroups, cheapest_path_width);
1352 sorted_p.startup_cost = sorted_path->startup_cost;
1353 sorted_p.total_cost = sorted_path->total_cost;
1354 current_pathkeys = sorted_path->pathkeys;
1358 sorted_p.startup_cost = cheapest_path->startup_cost;
1359 sorted_p.total_cost = cheapest_path->total_cost;
1360 current_pathkeys = cheapest_path->pathkeys;
1362 if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1364 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
1365 cheapest_path_rows, cheapest_path_width);
1366 current_pathkeys = root->group_pathkeys;
1369 if (root->parse->hasAggs)
1370 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1371 numGroupCols, dNumGroups,
1372 sorted_p.startup_cost, sorted_p.total_cost,
1373 cheapest_path_rows);
1375 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1376 sorted_p.startup_cost, sorted_p.total_cost,
1377 cheapest_path_rows);
1378 /* The Agg or Group node will preserve ordering */
1379 if (root->sort_pathkeys &&
1380 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1381 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
1382 dNumGroups, cheapest_path_width);
1385 * Now make the decision using the top-level tuple fraction. First we
1386 * have to convert an absolute count (LIMIT) into fractional form.
1388 if (tuple_fraction >= 1.0)
1389 tuple_fraction /= dNumGroups;
1391 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1392 tuple_fraction) < 0)
1394 /* Hashed is cheaper, so use it */
1401 * hash_safe_grouping - are grouping operators hashable?
1403 * We assume hashed aggregation will work if the datatype's equality operator
1404 * is marked hashjoinable.
1407 hash_safe_grouping(PlannerInfo *root)
1411 foreach(gl, root->parse->groupClause)
1413 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1414 TargetEntry *tle = get_sortgroupclause_tle(grpcl,
1415 root->parse->targetList);
1419 optup = equality_oper(exprType((Node *) tle->expr), true);
1422 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1423 ReleaseSysCache(optup);
1431 * make_subplanTargetList
1432 * Generate appropriate target list when grouping is required.
1434 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1435 * above the result of query_planner, we typically want to pass a different
1436 * target list to query_planner than the outer plan nodes should have.
1437 * This routine generates the correct target list for the subplan.
1439 * The initial target list passed from the parser already contains entries
1440 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1441 * for variables used only in HAVING clauses; so we need to add those
1442 * variables to the subplan target list. Also, we flatten all expressions
1443 * except GROUP BY items into their component variables; the other expressions
1444 * will be computed by the inserted nodes rather than by the subplan.
1445 * For example, given a query like
1446 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1447 * we want to pass this targetlist to the subplan:
1449 * where the a+b target will be used by the Sort/Group steps, and the
1450 * other targets will be used for computing the final results. (In the
1451 * above example we could theoretically suppress the a and b targets and
1452 * pass down only c,d,a+b, but it's not really worth the trouble to
1453 * eliminate simple var references from the subplan. We will avoid doing
1454 * the extra computation to recompute a+b at the outer level; see
1455 * replace_vars_with_subplan_refs() in setrefs.c.)
1457 * If we are grouping or aggregating, *and* there are no non-Var grouping
1458 * expressions, then the returned tlist is effectively dummy; we do not
1459 * need to force it to be evaluated, because all the Vars it contains
1460 * should be present in the output of query_planner anyway.
1462 * 'tlist' is the query's target list.
1463 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1464 * expressions (if there are any) in the subplan's target list.
1465 * 'need_tlist_eval' is set true if we really need to evaluate the
1468 * The result is the targetlist to be passed to the subplan.
1472 make_subplanTargetList(PlannerInfo *root,
1474 AttrNumber **groupColIdx,
1475 bool *need_tlist_eval)
1477 Query *parse = root->parse;
1482 *groupColIdx = NULL;
1485 * If we're not grouping or aggregating, there's nothing to do here;
1486 * query_planner should receive the unmodified target list.
1488 if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1490 *need_tlist_eval = true;
1495 * Otherwise, start with a "flattened" tlist (having just the vars
1496 * mentioned in the targetlist and HAVING qual --- but not upper- level
1497 * Vars; they will be replaced by Params later on).
1499 sub_tlist = flatten_tlist(tlist);
1500 extravars = pull_var_clause(parse->havingQual, false);
1501 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1502 list_free(extravars);
1503 *need_tlist_eval = false; /* only eval if not flat tlist */
1506 * If grouping, create sub_tlist entries for all GROUP BY expressions
1507 * (GROUP BY items that are simple Vars should be in the list already),
1508 * and make an array showing where the group columns are in the sub_tlist.
1510 numCols = list_length(parse->groupClause);
1514 AttrNumber *grpColIdx;
1517 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1518 *groupColIdx = grpColIdx;
1520 foreach(gl, parse->groupClause)
1522 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1523 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1524 TargetEntry *te = NULL;
1527 /* Find or make a matching sub_tlist entry */
1528 foreach(sl, sub_tlist)
1530 te = (TargetEntry *) lfirst(sl);
1531 if (equal(groupexpr, te->expr))
1536 te = makeTargetEntry((Expr *) groupexpr,
1537 list_length(sub_tlist) + 1,
1540 sub_tlist = lappend(sub_tlist, te);
1541 *need_tlist_eval = true; /* it's not flat anymore */
1544 /* and save its resno */
1545 grpColIdx[keyno++] = te->resno;
1553 * locate_grouping_columns
1554 * Locate grouping columns in the tlist chosen by query_planner.
1556 * This is only needed if we don't use the sub_tlist chosen by
1557 * make_subplanTargetList. We have to forget the column indexes found
1558 * by that routine and re-locate the grouping vars in the real sub_tlist.
1561 locate_grouping_columns(PlannerInfo *root,
1564 AttrNumber *groupColIdx)
1570 * No work unless grouping.
1572 if (!root->parse->groupClause)
1574 Assert(groupColIdx == NULL);
1577 Assert(groupColIdx != NULL);
1579 foreach(gl, root->parse->groupClause)
1581 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1582 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1583 TargetEntry *te = NULL;
1586 foreach(sl, sub_tlist)
1588 te = (TargetEntry *) lfirst(sl);
1589 if (equal(groupexpr, te->expr))
1593 elog(ERROR, "failed to locate grouping columns");
1595 groupColIdx[keyno++] = te->resno;
1600 * postprocess_setop_tlist
1601 * Fix up targetlist returned by plan_set_operations().
1603 * We need to transpose sort key info from the orig_tlist into new_tlist.
1604 * NOTE: this would not be good enough if we supported resjunk sort keys
1605 * for results of set operations --- then, we'd need to project a whole
1606 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1607 * find any resjunk columns in orig_tlist.
1610 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1613 ListCell *orig_tlist_item = list_head(orig_tlist);
1615 foreach(l, new_tlist)
1617 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1618 TargetEntry *orig_tle;
1620 /* ignore resjunk columns in setop result */
1621 if (new_tle->resjunk)
1624 Assert(orig_tlist_item != NULL);
1625 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1626 orig_tlist_item = lnext(orig_tlist_item);
1627 if (orig_tle->resjunk) /* should not happen */
1628 elog(ERROR, "resjunk output columns are not implemented");
1629 Assert(new_tle->resno == orig_tle->resno);
1630 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1632 if (orig_tlist_item != NULL)
1633 elog(ERROR, "resjunk output columns are not implemented");