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.184 2005/04/11 23:06:55 tgl 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(Query *parse, Node *expr, int kind);
58 static void preprocess_qual_conditions(Query *parse, Node *jtnode);
59 static Plan *inheritance_planner(Query *parse, List *inheritlist);
60 static Plan *grouping_planner(Query *parse, double tuple_fraction);
61 static bool choose_hashed_grouping(Query *parse, double tuple_fraction,
62 Path *cheapest_path, Path *sorted_path,
63 List *sort_pathkeys, List *group_pathkeys,
64 double dNumGroups, AggClauseCounts *agg_counts);
65 static bool hash_safe_grouping(Query *parse);
66 static List *make_subplanTargetList(Query *parse, List *tlist,
67 AttrNumber **groupColIdx, bool *need_tlist_eval);
68 static void locate_grouping_columns(Query *parse,
71 AttrNumber *groupColIdx);
72 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
75 /*****************************************************************************
77 * Query optimizer entry point
79 *****************************************************************************/
81 planner(Query *parse, bool isCursor, int cursorOptions,
82 ParamListInfo boundParams)
84 double tuple_fraction;
86 Index save_PlannerQueryLevel;
87 List *save_PlannerParamList;
88 ParamListInfo save_PlannerBoundParamList;
91 * The planner can be called recursively (an example is when
92 * eval_const_expressions tries to pre-evaluate an SQL function). So,
93 * these global state variables must be saved and restored.
95 * Query level and the param list cannot be moved into the Query
96 * structure since their whole purpose is communication across
97 * multiple sub-Queries. Also, boundParams is explicitly info from
98 * outside the Query, and so is likewise better handled as a global
101 * Note we do NOT save and restore PlannerPlanId: it exists to assign
102 * unique IDs to SubPlan nodes, and we want those IDs to be unique for
103 * the life of a backend. Also, PlannerInitPlan is saved/restored in
104 * subquery_planner, not here.
106 save_PlannerQueryLevel = PlannerQueryLevel;
107 save_PlannerParamList = PlannerParamList;
108 save_PlannerBoundParamList = PlannerBoundParamList;
110 /* Initialize state for handling outer-level references and params */
111 PlannerQueryLevel = 0; /* will be 1 in top-level subquery_planner */
112 PlannerParamList = NIL;
113 PlannerBoundParamList = boundParams;
115 /* Determine what fraction of the plan is likely to be scanned */
119 * We have no real idea how many tuples the user will ultimately
120 * FETCH from a cursor, but it seems a good bet that he doesn't
121 * want 'em all. Optimize for 10% retrieval (you gotta better
122 * number? Should this be a SETtable parameter?)
124 tuple_fraction = 0.10;
128 /* Default assumption is we need all the tuples */
129 tuple_fraction = 0.0;
132 /* primary planning entry point (may recurse for subqueries) */
133 result_plan = subquery_planner(parse, tuple_fraction);
135 Assert(PlannerQueryLevel == 0);
138 * If creating a plan for a scrollable cursor, make sure it can run
139 * backwards on demand. Add a Material node at the top at need.
141 if (isCursor && (cursorOptions & CURSOR_OPT_SCROLL))
143 if (!ExecSupportsBackwardScan(result_plan))
144 result_plan = materialize_finished_plan(result_plan);
147 /* executor wants to know total number of Params used overall */
148 result_plan->nParamExec = list_length(PlannerParamList);
150 /* final cleanup of the plan */
151 set_plan_references(result_plan, parse->rtable);
153 /* restore state for outer planner, if any */
154 PlannerQueryLevel = save_PlannerQueryLevel;
155 PlannerParamList = save_PlannerParamList;
156 PlannerBoundParamList = save_PlannerBoundParamList;
162 /*--------------------
164 * Invokes the planner on a subquery. We recurse to here for each
165 * sub-SELECT found in the query tree.
167 * parse is the querytree produced by the parser & rewriter.
168 * tuple_fraction is the fraction of tuples we expect will be retrieved.
169 * tuple_fraction is interpreted as explained for grouping_planner, below.
171 * Basically, this routine does the stuff that should only be done once
172 * per Query object. It then calls grouping_planner. At one time,
173 * grouping_planner could be invoked recursively on the same Query object;
174 * that's not currently true, but we keep the separation between the two
175 * routines anyway, in case we need it again someday.
177 * subquery_planner will be called recursively to handle sub-Query nodes
178 * found within the query's expressions and rangetable.
180 * Returns a query plan.
181 *--------------------
184 subquery_planner(Query *parse, double tuple_fraction)
186 List *saved_initplan = PlannerInitPlan;
187 int saved_planid = PlannerPlanId;
194 /* Set up for a new level of subquery */
196 PlannerInitPlan = NIL;
199 * Look for IN clauses at the top level of WHERE, and transform them
200 * into joins. Note that this step only handles IN clauses originally
201 * at top level of WHERE; if we pull up any subqueries in the next
202 * step, their INs are processed just before pulling them up.
204 parse->in_info_list = NIL;
205 if (parse->hasSubLinks)
206 parse->jointree->quals = pull_up_IN_clauses(parse,
207 parse->jointree->quals);
210 * Check to see if any subqueries in the rangetable can be merged into
213 parse->jointree = (FromExpr *)
214 pull_up_subqueries(parse, (Node *) parse->jointree, false);
217 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we
218 * can avoid the expense of doing flatten_join_alias_vars(). Also
219 * check for outer joins --- if none, we can skip
220 * reduce_outer_joins(). This must be done after we have done
221 * pull_up_subqueries, of course.
223 parse->hasJoinRTEs = false;
224 hasOuterJoins = false;
225 foreach(l, parse->rtable)
227 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
229 if (rte->rtekind == RTE_JOIN)
231 parse->hasJoinRTEs = true;
232 if (IS_OUTER_JOIN(rte->jointype))
234 hasOuterJoins = true;
235 /* Can quit scanning once we find an outer join */
242 * Set hasHavingQual to remember if HAVING clause is present. Needed
243 * because preprocess_expression will reduce a constant-true condition
244 * to an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
246 parse->hasHavingQual = (parse->havingQual != NULL);
249 * Do expression preprocessing on targetlist and quals.
251 parse->targetList = (List *)
252 preprocess_expression(parse, (Node *) parse->targetList,
255 preprocess_qual_conditions(parse, (Node *) parse->jointree);
257 parse->havingQual = preprocess_expression(parse, parse->havingQual,
260 parse->limitOffset = preprocess_expression(parse, parse->limitOffset,
262 parse->limitCount = preprocess_expression(parse, parse->limitCount,
265 parse->in_info_list = (List *)
266 preprocess_expression(parse, (Node *) parse->in_info_list,
269 /* Also need to preprocess expressions for function RTEs */
270 foreach(l, parse->rtable)
272 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
274 if (rte->rtekind == RTE_FUNCTION)
275 rte->funcexpr = preprocess_expression(parse, rte->funcexpr,
280 * In some cases we may want to transfer a HAVING clause into WHERE.
281 * We cannot do so if the HAVING clause contains aggregates (obviously)
282 * or volatile functions (since a HAVING clause is supposed to be executed
283 * only once per group). Also, it may be that the clause is so expensive
284 * to execute that we're better off doing it only once per group, despite
285 * the loss of selectivity. This is hard to estimate short of doing the
286 * entire planning process twice, so we use a heuristic: clauses
287 * containing subplans are left in HAVING. Otherwise, we move or copy
288 * the HAVING clause into WHERE, in hopes of eliminating tuples before
289 * aggregation instead of after.
291 * If the query has explicit grouping then we can simply move such a
292 * clause into WHERE; any group that fails the clause will not be
293 * in the output because none of its tuples will reach the grouping
294 * or aggregation stage. Otherwise we must have a degenerate
295 * (variable-free) HAVING clause, which we put in WHERE so that
296 * query_planner() can use it in a gating Result node, but also keep
297 * in HAVING to ensure that we don't emit a bogus aggregated row.
298 * (This could be done better, but it seems not worth optimizing.)
300 * Note that both havingQual and parse->jointree->quals are in
301 * implicitly-ANDed-list form at this point, even though they are
302 * declared as Node *.
305 foreach(l, (List *) parse->havingQual)
307 Node *havingclause = (Node *) lfirst(l);
309 if (contain_agg_clause(havingclause) ||
310 contain_volatile_functions(havingclause) ||
311 contain_subplans(havingclause))
313 /* keep it in HAVING */
314 newHaving = lappend(newHaving, havingclause);
316 else if (parse->groupClause)
318 /* move it to WHERE */
319 parse->jointree->quals = (Node *)
320 lappend((List *) parse->jointree->quals, havingclause);
324 /* put a copy in WHERE, keep it in HAVING */
325 parse->jointree->quals = (Node *)
326 lappend((List *) parse->jointree->quals,
327 copyObject(havingclause));
328 newHaving = lappend(newHaving, havingclause);
331 parse->havingQual = (Node *) newHaving;
334 * If we have any outer joins, try to reduce them to plain inner
335 * joins. This step is most easily done after we've done expression
339 reduce_outer_joins(parse);
342 * See if we can simplify the jointree; opportunities for this may
343 * come from having pulled up subqueries, or from flattening explicit
344 * JOIN syntax. We must do this after flattening JOIN alias
345 * variables, since eliminating explicit JOIN nodes from the jointree
346 * will cause get_relids_for_join() to fail. But it should happen
347 * after reduce_outer_joins, anyway.
349 parse->jointree = (FromExpr *)
350 simplify_jointree(parse, (Node *) parse->jointree);
353 * Do the main planning. If we have an inherited target relation,
354 * that needs special processing, else go straight to
357 if (parse->resultRelation &&
358 (lst = expand_inherited_rtentry(parse, parse->resultRelation)) != NIL)
359 plan = inheritance_planner(parse, lst);
361 plan = grouping_planner(parse, tuple_fraction);
364 * If any subplans were generated, or if we're inside a subplan, build
365 * initPlan list and extParam/allParam sets for plan nodes, and attach
366 * the initPlans to the top plan node.
368 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
369 SS_finalize_plan(plan, parse->rtable);
371 /* Return to outer subquery context */
373 PlannerInitPlan = saved_initplan;
374 /* we do NOT restore PlannerPlanId; that's not an oversight! */
380 * preprocess_expression
381 * Do subquery_planner's preprocessing work for an expression,
382 * which can be a targetlist, a WHERE clause (including JOIN/ON
383 * conditions), or a HAVING clause.
386 preprocess_expression(Query *parse, Node *expr, int kind)
389 * If the query has any join RTEs, replace join alias variables with
390 * base-relation variables. We must do this before sublink processing,
391 * else sublinks expanded out from join aliases wouldn't get
394 if (parse->hasJoinRTEs)
395 expr = flatten_join_alias_vars(parse, expr);
398 * Simplify constant expressions.
400 * Note: this also flattens nested AND and OR expressions into N-argument
401 * form. All processing of a qual expression after this point must be
402 * careful to maintain AND/OR flatness --- that is, do not generate a tree
403 * with AND directly under AND, nor OR directly under OR.
405 expr = eval_const_expressions(expr);
408 * If it's a qual or havingQual, canonicalize it.
410 if (kind == EXPRKIND_QUAL)
412 expr = (Node *) canonicalize_qual((Expr *) expr);
414 #ifdef OPTIMIZER_DEBUG
415 printf("After canonicalize_qual()\n");
420 /* Expand SubLinks to SubPlans */
421 if (parse->hasSubLinks)
422 expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL));
425 * XXX do not insert anything here unless you have grokked the
426 * comments in SS_replace_correlation_vars ...
429 /* Replace uplevel vars with Param nodes */
430 if (PlannerQueryLevel > 1)
431 expr = SS_replace_correlation_vars(expr);
434 * If it's a qual or havingQual, convert it to implicit-AND format.
435 * (We don't want to do this before eval_const_expressions, since the
436 * latter would be unable to simplify a top-level AND correctly. Also,
437 * SS_process_sublinks expects explicit-AND format.)
439 if (kind == EXPRKIND_QUAL)
440 expr = (Node *) make_ands_implicit((Expr *) expr);
446 * preprocess_qual_conditions
447 * Recursively scan the query's jointree and do subquery_planner's
448 * preprocessing work on each qual condition found therein.
451 preprocess_qual_conditions(Query *parse, Node *jtnode)
455 if (IsA(jtnode, RangeTblRef))
457 /* nothing to do here */
459 else if (IsA(jtnode, FromExpr))
461 FromExpr *f = (FromExpr *) jtnode;
464 foreach(l, f->fromlist)
465 preprocess_qual_conditions(parse, lfirst(l));
467 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_QUAL);
469 else if (IsA(jtnode, JoinExpr))
471 JoinExpr *j = (JoinExpr *) jtnode;
473 preprocess_qual_conditions(parse, j->larg);
474 preprocess_qual_conditions(parse, j->rarg);
476 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_QUAL);
479 elog(ERROR, "unrecognized node type: %d",
480 (int) nodeTag(jtnode));
483 /*--------------------
484 * inheritance_planner
485 * Generate a plan in the case where the result relation is an
488 * We have to handle this case differently from cases where a source
489 * relation is an inheritance set. Source inheritance is expanded at
490 * the bottom of the plan tree (see allpaths.c), but target inheritance
491 * has to be expanded at the top. The reason is that for UPDATE, each
492 * target relation needs a different targetlist matching its own column
493 * set. (This is not so critical for DELETE, but for simplicity we treat
494 * inherited DELETE the same way.) Fortunately, the UPDATE/DELETE target
495 * can never be the nullable side of an outer join, so it's OK to generate
498 * parse is the querytree produced by the parser & rewriter.
499 * inheritlist is an integer list of RT indexes for the result relation set.
501 * Returns a query plan.
502 *--------------------
505 inheritance_planner(Query *parse, List *inheritlist)
507 int parentRTindex = parse->resultRelation;
508 Oid parentOID = getrelid(parentRTindex, parse->rtable);
509 int mainrtlength = list_length(parse->rtable);
510 List *subplans = NIL;
514 foreach(l, inheritlist)
516 int childRTindex = lfirst_int(l);
517 Oid childOID = getrelid(childRTindex, parse->rtable);
521 /* Generate modified query with this rel as target */
522 subquery = (Query *) adjust_inherited_attrs((Node *) parse,
523 parentRTindex, parentOID,
524 childRTindex, childOID);
526 subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */ );
527 subplans = lappend(subplans, subplan);
530 * XXX my goodness this next bit is ugly. Really need to think about
531 * ways to rein in planner's habit of scribbling on its input.
533 * Planning of the subquery might have modified the rangetable,
534 * either by addition of RTEs due to expansion of inherited source
535 * tables, or by changes of the Query structures inside subquery
536 * RTEs. We have to ensure that this gets propagated back to the
537 * master copy. However, if we aren't done planning yet, we also
538 * need to ensure that subsequent calls to grouping_planner have
539 * virgin sub-Queries to work from. So, if we are at the last
540 * list entry, just copy the subquery rangetable back to the master
541 * copy; if we are not, then extend the master copy by adding
542 * whatever the subquery added. (We assume these added entries
543 * will go untouched by the future grouping_planner calls. We are
544 * also effectively assuming that sub-Queries will get planned
545 * identically each time, or at least that the impacts on their
546 * rangetables will be the same each time. Did I say this is ugly?)
548 if (lnext(l) == NULL)
549 parse->rtable = subquery->rtable;
552 int subrtlength = list_length(subquery->rtable);
554 if (subrtlength > mainrtlength)
558 subrt = list_copy_tail(subquery->rtable, mainrtlength);
559 parse->rtable = list_concat(parse->rtable, subrt);
560 mainrtlength = subrtlength;
564 /* Save preprocessed tlist from first rel for use in Append */
566 tlist = subplan->targetlist;
569 /* Save the target-relations list for the executor, too */
570 parse->resultRelations = inheritlist;
572 /* Mark result as unordered (probably unnecessary) */
573 parse->query_pathkeys = NIL;
575 return (Plan *) make_append(subplans, true, tlist);
578 /*--------------------
580 * Perform planning steps related to grouping, aggregation, etc.
581 * This primarily means adding top-level processing to the basic
582 * query plan produced by query_planner.
584 * parse is the querytree produced by the parser & rewriter.
585 * tuple_fraction is the fraction of tuples we expect will be retrieved
587 * tuple_fraction is interpreted as follows:
588 * 0: expect all tuples to be retrieved (normal case)
589 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
590 * from the plan to be retrieved
591 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
592 * expected to be retrieved (ie, a LIMIT specification)
594 * Returns a query plan. Also, parse->query_pathkeys is returned as the
595 * actual output ordering of the plan (in pathkey format).
596 *--------------------
599 grouping_planner(Query *parse, double tuple_fraction)
601 List *tlist = parse->targetList;
603 List *current_pathkeys;
606 if (parse->setOperations)
608 List *set_sortclauses;
611 * Construct the plan for set operations. The result will not
612 * need any work except perhaps a top-level sort and/or LIMIT.
614 result_plan = plan_set_operations(parse,
618 * Calculate pathkeys representing the sort order (if any) of the
619 * set operation's result. We have to do this before overwriting
620 * the sort key information...
622 current_pathkeys = make_pathkeys_for_sortclauses(set_sortclauses,
623 result_plan->targetlist);
624 current_pathkeys = canonicalize_pathkeys(parse, current_pathkeys);
627 * We should not need to call preprocess_targetlist, since we must
628 * be in a SELECT query node. Instead, use the targetlist
629 * returned by plan_set_operations (since this tells whether it
630 * returned any resjunk columns!), and transfer any sort key
631 * information from the original tlist.
633 Assert(parse->commandType == CMD_SELECT);
635 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
638 * Can't handle FOR UPDATE here (parser should have checked
639 * already, but let's make sure).
643 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
644 errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
647 * Calculate pathkeys that represent result ordering requirements
649 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
651 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
655 /* No set operations, do regular planning */
657 List *group_pathkeys;
658 AttrNumber *groupColIdx = NULL;
659 bool need_tlist_eval = true;
661 double sub_tuple_fraction;
665 double dNumGroups = 0;
667 AggClauseCounts agg_counts;
668 int numGroupCols = list_length(parse->groupClause);
669 bool use_hashed_grouping = false;
671 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
673 /* Preprocess targetlist */
674 tlist = preprocess_targetlist(parse, tlist);
677 * Generate appropriate target list for subplan; may be different
678 * from tlist if grouping or aggregation is needed.
680 sub_tlist = make_subplanTargetList(parse, tlist,
681 &groupColIdx, &need_tlist_eval);
684 * Calculate pathkeys that represent grouping/ordering
687 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
689 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
693 * Will need actual number of aggregates for estimating costs.
695 * Note: we do not attempt to detect duplicate aggregates here; a
696 * somewhat-overestimated count is okay for our present purposes.
698 * Note: think not that we can turn off hasAggs if we find no aggs.
699 * It is possible for constant-expression simplification to remove
700 * all explicit references to aggs, but we still have to follow
701 * the aggregate semantics (eg, producing only one output row).
705 count_agg_clauses((Node *) tlist, &agg_counts);
706 count_agg_clauses(parse->havingQual, &agg_counts);
710 * Figure out whether we need a sorted result from query_planner.
712 * If we have a GROUP BY clause, then we want a result sorted
713 * properly for grouping. Otherwise, if there is an ORDER BY
714 * clause, we want to sort by the ORDER BY clause. (Note: if we
715 * have both, and ORDER BY is a superset of GROUP BY, it would be
716 * tempting to request sort by ORDER BY --- but that might just
717 * leave us failing to exploit an available sort order at all.
718 * Needs more thought...)
720 if (parse->groupClause)
721 parse->query_pathkeys = group_pathkeys;
722 else if (parse->sortClause)
723 parse->query_pathkeys = sort_pathkeys;
725 parse->query_pathkeys = NIL;
728 * Adjust tuple_fraction if we see that we are going to apply
729 * limiting/grouping/aggregation/etc. This is not overridable by
730 * the caller, since it reflects plan actions that this routine
731 * will certainly take, not assumptions about context.
733 if (parse->limitCount != NULL)
736 * A LIMIT clause limits the absolute number of tuples
737 * returned. However, if it's not a constant LIMIT then we
738 * have to punt; for lack of a better idea, assume 10% of the
739 * plan's result is wanted.
741 double limit_fraction = 0.0;
743 if (IsA(parse->limitCount, Const))
745 Const *limitc = (Const *) parse->limitCount;
746 int32 count = DatumGetInt32(limitc->constvalue);
749 * A NULL-constant LIMIT represents "LIMIT ALL", which we
750 * treat the same as no limit (ie, expect to retrieve all
753 if (!limitc->constisnull && count > 0)
755 limit_fraction = (double) count;
756 /* We must also consider the OFFSET, if present */
757 if (parse->limitOffset != NULL)
759 if (IsA(parse->limitOffset, Const))
763 limitc = (Const *) parse->limitOffset;
764 offset = DatumGetInt32(limitc->constvalue);
765 if (!limitc->constisnull && offset > 0)
766 limit_fraction += (double) offset;
770 /* OFFSET is an expression ... punt ... */
771 limit_fraction = 0.10;
778 /* LIMIT is an expression ... punt ... */
779 limit_fraction = 0.10;
782 if (limit_fraction > 0.0)
785 * If we have absolute limits from both caller and LIMIT,
786 * use the smaller value; if one is fractional and the
787 * other absolute, treat the fraction as a fraction of the
788 * absolute value; else we can multiply the two fractions
791 if (tuple_fraction >= 1.0)
793 if (limit_fraction >= 1.0)
796 tuple_fraction = Min(tuple_fraction, limit_fraction);
800 /* caller absolute, limit fractional */
801 tuple_fraction *= limit_fraction;
802 if (tuple_fraction < 1.0)
803 tuple_fraction = 1.0;
806 else if (tuple_fraction > 0.0)
808 if (limit_fraction >= 1.0)
810 /* caller fractional, limit absolute */
811 tuple_fraction *= limit_fraction;
812 if (tuple_fraction < 1.0)
813 tuple_fraction = 1.0;
817 /* both fractional */
818 tuple_fraction *= limit_fraction;
823 /* no info from caller, just use limit */
824 tuple_fraction = limit_fraction;
830 * With grouping or aggregation, the tuple fraction to pass to
831 * query_planner() may be different from what it is at top level.
833 sub_tuple_fraction = tuple_fraction;
835 if (parse->groupClause)
838 * In GROUP BY mode, we have the little problem that we don't
839 * really know how many input tuples will be needed to make a
840 * group, so we can't translate an output LIMIT count into an
841 * input count. For lack of a better idea, assume 25% of the
842 * input data will be processed if there is any output limit.
843 * However, if the caller gave us a fraction rather than an
844 * absolute count, we can keep using that fraction (which
845 * amounts to assuming that all the groups are about the same
848 if (sub_tuple_fraction >= 1.0)
849 sub_tuple_fraction = 0.25;
852 * If both GROUP BY and ORDER BY are specified, we will need
853 * two levels of sort --- and, therefore, certainly need to
854 * read all the input tuples --- unless ORDER BY is a subset
855 * of GROUP BY. (We have not yet canonicalized the pathkeys,
856 * so must use the slower noncanonical comparison method.)
858 if (parse->groupClause && parse->sortClause &&
859 !noncanonical_pathkeys_contained_in(sort_pathkeys,
861 sub_tuple_fraction = 0.0;
863 else if (parse->hasAggs)
866 * Ungrouped aggregate will certainly want all the input
869 sub_tuple_fraction = 0.0;
871 else if (parse->distinctClause)
874 * SELECT DISTINCT, like GROUP, will absorb an unpredictable
875 * number of input tuples per output tuple. Handle the same
878 if (sub_tuple_fraction >= 1.0)
879 sub_tuple_fraction = 0.25;
883 * Generate the best unsorted and presorted paths for this Query
884 * (but note there may not be any presorted path).
886 query_planner(parse, sub_tlist, sub_tuple_fraction,
887 &cheapest_path, &sorted_path);
890 * We couldn't canonicalize group_pathkeys and sort_pathkeys
891 * before running query_planner(), so do it now.
893 group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
894 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
897 * If grouping, estimate the number of groups. (We can't do this
898 * until after running query_planner(), either.) Then decide
899 * whether we want to use hashed grouping.
901 if (parse->groupClause)
904 double cheapest_path_rows;
907 * Beware of the possibility that cheapest_path->parent is NULL.
908 * This could happen if user does something silly like
909 * SELECT 'foo' GROUP BY 1;
911 if (cheapest_path->parent)
912 cheapest_path_rows = cheapest_path->parent->rows;
914 cheapest_path_rows = 1; /* assume non-set result */
916 groupExprs = get_sortgrouplist_exprs(parse->groupClause,
918 dNumGroups = estimate_num_groups(parse,
921 /* Also want it as a long int --- but 'ware overflow! */
922 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
924 use_hashed_grouping =
925 choose_hashed_grouping(parse, tuple_fraction,
926 cheapest_path, sorted_path,
927 sort_pathkeys, group_pathkeys,
928 dNumGroups, &agg_counts);
932 * Select the best path. If we are doing hashed grouping, we will
933 * always read all the input tuples, so use the cheapest-total
934 * path. Otherwise, trust query_planner's decision about which to use.
936 if (use_hashed_grouping || !sorted_path)
937 best_path = cheapest_path;
939 best_path = sorted_path;
942 * Check to see if it's possible to optimize MIN/MAX aggregates.
943 * If so, we will forget all the work we did so far to choose a
944 * "regular" path ... but we had to do it anyway to be able to
945 * tell which way is cheaper.
947 result_plan = optimize_minmax_aggregates(parse,
950 if (result_plan != NULL)
953 * optimize_minmax_aggregates generated the full plan, with
954 * the right tlist, and it has no sort order.
956 current_pathkeys = NIL;
961 * Normal case --- create a plan according to query_planner's
964 result_plan = create_plan(parse, best_path);
965 current_pathkeys = best_path->pathkeys;
968 * create_plan() returns a plan with just a "flat" tlist of
969 * required Vars. Usually we need to insert the sub_tlist as the
970 * tlist of the top plan node. However, we can skip that if we
971 * determined that whatever query_planner chose to return will be
977 * If the top-level plan node is one that cannot do expression
978 * evaluation, we must insert a Result node to project the
981 if (!is_projection_capable_plan(result_plan))
983 result_plan = (Plan *) make_result(sub_tlist, NULL,
989 * Otherwise, just replace the subplan's flat tlist with
992 result_plan->targetlist = sub_tlist;
996 * Also, account for the cost of evaluation of the sub_tlist.
998 * Up to now, we have only been dealing with "flat" tlists,
999 * containing just Vars. So their evaluation cost is zero
1000 * according to the model used by cost_qual_eval() (or if you
1001 * prefer, the cost is factored into cpu_tuple_cost). Thus we
1002 * can avoid accounting for tlist cost throughout
1003 * query_planner() and subroutines. But now we've inserted a
1004 * tlist that might contain actual operators, sub-selects, etc
1005 * --- so we'd better account for its cost.
1007 * Below this point, any tlist eval cost for added-on nodes
1008 * should be accounted for as we create those nodes.
1009 * Presently, of the node types we can add on, only Agg and
1010 * Group project new tlists (the rest just copy their input
1011 * tuples) --- so make_agg() and make_group() are responsible
1012 * for computing the added cost.
1014 cost_qual_eval(&tlist_cost, sub_tlist);
1015 result_plan->startup_cost += tlist_cost.startup;
1016 result_plan->total_cost += tlist_cost.startup +
1017 tlist_cost.per_tuple * result_plan->plan_rows;
1022 * Since we're using query_planner's tlist and not the one
1023 * make_subplanTargetList calculated, we have to refigure any
1024 * grouping-column indexes make_subplanTargetList computed.
1026 locate_grouping_columns(parse, tlist, result_plan->targetlist,
1031 * Insert AGG or GROUP node if needed, plus an explicit sort step
1034 * HAVING clause, if any, becomes qual of the Agg or Group node.
1036 if (use_hashed_grouping)
1038 /* Hashed aggregate plan --- no sort needed */
1039 result_plan = (Plan *) make_agg(parse,
1041 (List *) parse->havingQual,
1048 /* Hashed aggregation produces randomly-ordered results */
1049 current_pathkeys = NIL;
1051 else if (parse->hasAggs)
1053 /* Plain aggregate plan --- sort if needed */
1054 AggStrategy aggstrategy;
1056 if (parse->groupClause)
1058 if (!pathkeys_contained_in(group_pathkeys,
1061 result_plan = (Plan *)
1062 make_sort_from_groupcols(parse,
1066 current_pathkeys = group_pathkeys;
1068 aggstrategy = AGG_SORTED;
1071 * The AGG node will not change the sort ordering of its
1072 * groups, so current_pathkeys describes the result too.
1077 aggstrategy = AGG_PLAIN;
1078 /* Result will be only one row anyway; no sort order */
1079 current_pathkeys = NIL;
1082 result_plan = (Plan *) make_agg(parse,
1084 (List *) parse->havingQual,
1092 else if (parse->groupClause)
1095 * GROUP BY without aggregation, so insert a group node (plus
1096 * the appropriate sort node, if necessary).
1098 * Add an explicit sort if we couldn't make the path come
1099 * out the way the GROUP node needs it.
1101 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1103 result_plan = (Plan *)
1104 make_sort_from_groupcols(parse,
1108 current_pathkeys = group_pathkeys;
1111 result_plan = (Plan *) make_group(parse,
1113 (List *) parse->havingQual,
1118 /* The Group node won't change sort ordering */
1120 else if (parse->hasHavingQual)
1123 * No aggregates, and no GROUP BY, but we have a HAVING qual.
1124 * This is a degenerate case in which we are supposed to emit
1125 * either 0 or 1 row depending on whether HAVING succeeds.
1126 * Furthermore, there cannot be any variables in either HAVING
1127 * or the targetlist, so we actually do not need the FROM table
1128 * at all! We can just throw away the plan-so-far and generate
1129 * a Result node. This is a sufficiently unusual corner case
1130 * that it's not worth contorting the structure of this routine
1131 * to avoid having to generate the plan in the first place.
1133 result_plan = (Plan *) make_result(tlist,
1137 } /* end of non-minmax-aggregate case */
1138 } /* end of if (setOperations) */
1141 * If we were not able to make the plan come out in the right order,
1142 * add an explicit sort step.
1144 if (parse->sortClause)
1146 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1148 result_plan = (Plan *)
1149 make_sort_from_sortclauses(parse,
1152 current_pathkeys = sort_pathkeys;
1157 * If there is a DISTINCT clause, add the UNIQUE node.
1159 if (parse->distinctClause)
1161 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1164 * If there was grouping or aggregation, leave plan_rows as-is
1165 * (ie, assume the result was already mostly unique). If not,
1166 * it's reasonable to assume the UNIQUE filter has effects
1167 * comparable to GROUP BY.
1169 if (!parse->groupClause && !parse->hasHavingQual && !parse->hasAggs)
1171 List *distinctExprs;
1173 distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
1175 result_plan->plan_rows = estimate_num_groups(parse,
1177 result_plan->plan_rows);
1182 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1184 if (parse->limitOffset || parse->limitCount)
1186 result_plan = (Plan *) make_limit(result_plan,
1192 * Return the actual output ordering in query_pathkeys for possible
1193 * use by an outer query level.
1195 parse->query_pathkeys = current_pathkeys;
1201 * choose_hashed_grouping - should we use hashed grouping?
1204 choose_hashed_grouping(Query *parse, double tuple_fraction,
1205 Path *cheapest_path, Path *sorted_path,
1206 List *sort_pathkeys, List *group_pathkeys,
1207 double dNumGroups, AggClauseCounts *agg_counts)
1209 int numGroupCols = list_length(parse->groupClause);
1210 double cheapest_path_rows;
1211 int cheapest_path_width;
1213 List *current_pathkeys;
1218 * Check can't-do-it conditions, including whether the grouping operators
1221 * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1222 * (Doing so would imply storing *all* the input values in the hash table,
1223 * which seems like a certain loser.)
1225 if (!enable_hashagg)
1227 if (agg_counts->numDistinctAggs != 0)
1229 if (!hash_safe_grouping(parse))
1233 * Don't do it if it doesn't look like the hashtable will fit into
1236 * Beware here of the possibility that cheapest_path->parent is NULL.
1237 * This could happen if user does something silly like
1238 * SELECT 'foo' GROUP BY 1;
1240 if (cheapest_path->parent)
1242 cheapest_path_rows = cheapest_path->parent->rows;
1243 cheapest_path_width = cheapest_path->parent->width;
1247 cheapest_path_rows = 1; /* assume non-set result */
1248 cheapest_path_width = 100; /* arbitrary */
1251 /* Estimate per-hash-entry space at tuple width... */
1252 hashentrysize = cheapest_path_width;
1253 /* plus space for pass-by-ref transition values... */
1254 hashentrysize += agg_counts->transitionSpace;
1255 /* plus the per-hash-entry overhead */
1256 hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1258 if (hashentrysize * dNumGroups > work_mem * 1024L)
1262 * See if the estimated cost is no more than doing it the other way.
1263 * While avoiding the need for sorted input is usually a win, the fact
1264 * that the output won't be sorted may be a loss; so we need to do an
1265 * actual cost comparison.
1267 * We need to consider
1268 * cheapest_path + hashagg [+ final sort]
1270 * cheapest_path [+ sort] + group or agg [+ final sort]
1272 * presorted_path + group or agg [+ final sort]
1273 * where brackets indicate a step that may not be needed. We assume
1274 * query_planner() will have returned a presorted path only if it's a
1275 * winner compared to cheapest_path for this purpose.
1277 * These path variables are dummies that just hold cost fields; we don't
1278 * make actual Paths for these steps.
1280 cost_agg(&hashed_p, parse, AGG_HASHED, agg_counts->numAggs,
1281 numGroupCols, dNumGroups,
1282 cheapest_path->startup_cost, cheapest_path->total_cost,
1283 cheapest_path_rows);
1284 /* Result of hashed agg is always unsorted */
1286 cost_sort(&hashed_p, parse, sort_pathkeys, hashed_p.total_cost,
1287 dNumGroups, cheapest_path_width);
1291 sorted_p.startup_cost = sorted_path->startup_cost;
1292 sorted_p.total_cost = sorted_path->total_cost;
1293 current_pathkeys = sorted_path->pathkeys;
1297 sorted_p.startup_cost = cheapest_path->startup_cost;
1298 sorted_p.total_cost = cheapest_path->total_cost;
1299 current_pathkeys = cheapest_path->pathkeys;
1301 if (!pathkeys_contained_in(group_pathkeys,
1304 cost_sort(&sorted_p, parse, group_pathkeys, sorted_p.total_cost,
1305 cheapest_path_rows, cheapest_path_width);
1306 current_pathkeys = group_pathkeys;
1310 cost_agg(&sorted_p, parse, AGG_SORTED, agg_counts->numAggs,
1311 numGroupCols, dNumGroups,
1312 sorted_p.startup_cost, sorted_p.total_cost,
1313 cheapest_path_rows);
1315 cost_group(&sorted_p, parse, numGroupCols, dNumGroups,
1316 sorted_p.startup_cost, sorted_p.total_cost,
1317 cheapest_path_rows);
1318 /* The Agg or Group node will preserve ordering */
1319 if (sort_pathkeys &&
1320 !pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1321 cost_sort(&sorted_p, parse, sort_pathkeys, sorted_p.total_cost,
1322 dNumGroups, cheapest_path_width);
1325 * Now make the decision using the top-level tuple fraction. First we
1326 * have to convert an absolute count (LIMIT) into fractional form.
1328 if (tuple_fraction >= 1.0)
1329 tuple_fraction /= dNumGroups;
1331 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1332 tuple_fraction) < 0)
1334 /* Hashed is cheaper, so use it */
1341 * hash_safe_grouping - are grouping operators hashable?
1343 * We assume hashed aggregation will work if the datatype's equality operator
1344 * is marked hashjoinable.
1347 hash_safe_grouping(Query *parse)
1351 foreach(gl, parse->groupClause)
1353 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1354 TargetEntry *tle = get_sortgroupclause_tle(grpcl, parse->targetList);
1358 optup = equality_oper(exprType((Node *) tle->expr), true);
1361 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1362 ReleaseSysCache(optup);
1370 * make_subplanTargetList
1371 * Generate appropriate target list when grouping is required.
1373 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1374 * above the result of query_planner, we typically want to pass a different
1375 * target list to query_planner than the outer plan nodes should have.
1376 * This routine generates the correct target list for the subplan.
1378 * The initial target list passed from the parser already contains entries
1379 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1380 * for variables used only in HAVING clauses; so we need to add those
1381 * variables to the subplan target list. Also, we flatten all expressions
1382 * except GROUP BY items into their component variables; the other expressions
1383 * will be computed by the inserted nodes rather than by the subplan.
1384 * For example, given a query like
1385 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1386 * we want to pass this targetlist to the subplan:
1388 * where the a+b target will be used by the Sort/Group steps, and the
1389 * other targets will be used for computing the final results. (In the
1390 * above example we could theoretically suppress the a and b targets and
1391 * pass down only c,d,a+b, but it's not really worth the trouble to
1392 * eliminate simple var references from the subplan. We will avoid doing
1393 * the extra computation to recompute a+b at the outer level; see
1394 * replace_vars_with_subplan_refs() in setrefs.c.)
1396 * If we are grouping or aggregating, *and* there are no non-Var grouping
1397 * expressions, then the returned tlist is effectively dummy; we do not
1398 * need to force it to be evaluated, because all the Vars it contains
1399 * should be present in the output of query_planner anyway.
1401 * 'parse' is the query being processed.
1402 * 'tlist' is the query's target list.
1403 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1404 * expressions (if there are any) in the subplan's target list.
1405 * 'need_tlist_eval' is set true if we really need to evaluate the
1408 * The result is the targetlist to be passed to the subplan.
1412 make_subplanTargetList(Query *parse,
1414 AttrNumber **groupColIdx,
1415 bool *need_tlist_eval)
1421 *groupColIdx = NULL;
1424 * If we're not grouping or aggregating, there's nothing to do here;
1425 * query_planner should receive the unmodified target list.
1427 if (!parse->hasAggs && !parse->groupClause && !parse->hasHavingQual)
1429 *need_tlist_eval = true;
1434 * Otherwise, start with a "flattened" tlist (having just the vars
1435 * mentioned in the targetlist and HAVING qual --- but not upper-
1436 * level Vars; they will be replaced by Params later on).
1438 sub_tlist = flatten_tlist(tlist);
1439 extravars = pull_var_clause(parse->havingQual, false);
1440 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1441 list_free(extravars);
1442 *need_tlist_eval = false; /* only eval if not flat tlist */
1445 * If grouping, create sub_tlist entries for all GROUP BY expressions
1446 * (GROUP BY items that are simple Vars should be in the list
1447 * already), and make an array showing where the group columns are in
1450 numCols = list_length(parse->groupClause);
1454 AttrNumber *grpColIdx;
1457 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1458 *groupColIdx = grpColIdx;
1460 foreach(gl, parse->groupClause)
1462 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1463 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1464 TargetEntry *te = NULL;
1467 /* Find or make a matching sub_tlist entry */
1468 foreach(sl, sub_tlist)
1470 te = (TargetEntry *) lfirst(sl);
1471 if (equal(groupexpr, te->expr))
1476 te = makeTargetEntry((Expr *) groupexpr,
1477 list_length(sub_tlist) + 1,
1480 sub_tlist = lappend(sub_tlist, te);
1481 *need_tlist_eval = true; /* it's not flat anymore */
1484 /* and save its resno */
1485 grpColIdx[keyno++] = te->resno;
1493 * locate_grouping_columns
1494 * Locate grouping columns in the tlist chosen by query_planner.
1496 * This is only needed if we don't use the sub_tlist chosen by
1497 * make_subplanTargetList. We have to forget the column indexes found
1498 * by that routine and re-locate the grouping vars in the real sub_tlist.
1501 locate_grouping_columns(Query *parse,
1504 AttrNumber *groupColIdx)
1510 * No work unless grouping.
1512 if (!parse->groupClause)
1514 Assert(groupColIdx == NULL);
1517 Assert(groupColIdx != NULL);
1519 foreach(gl, parse->groupClause)
1521 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1522 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1523 TargetEntry *te = NULL;
1526 foreach(sl, sub_tlist)
1528 te = (TargetEntry *) lfirst(sl);
1529 if (equal(groupexpr, te->expr))
1533 elog(ERROR, "failed to locate grouping columns");
1535 groupColIdx[keyno++] = te->resno;
1540 * postprocess_setop_tlist
1541 * Fix up targetlist returned by plan_set_operations().
1543 * We need to transpose sort key info from the orig_tlist into new_tlist.
1544 * NOTE: this would not be good enough if we supported resjunk sort keys
1545 * for results of set operations --- then, we'd need to project a whole
1546 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1547 * find any resjunk columns in orig_tlist.
1550 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1553 ListCell *orig_tlist_item = list_head(orig_tlist);
1555 foreach(l, new_tlist)
1557 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1558 TargetEntry *orig_tle;
1560 /* ignore resjunk columns in setop result */
1561 if (new_tle->resjunk)
1564 Assert(orig_tlist_item != NULL);
1565 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1566 orig_tlist_item = lnext(orig_tlist_item);
1567 if (orig_tle->resjunk) /* should not happen */
1568 elog(ERROR, "resjunk output columns are not implemented");
1569 Assert(new_tle->resno == orig_tle->resno);
1570 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1572 if (orig_tlist_item != NULL)
1573 elog(ERROR, "resjunk output columns are not implemented");