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.183 2005/04/10 19:50:08 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.
367 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
369 Cost initplan_cost = 0;
371 /* Prepare extParam/allParam sets for all nodes in tree */
372 SS_finalize_plan(plan, parse->rtable);
375 * SS_finalize_plan doesn't handle initPlans, so we have to
376 * manually attach them to the topmost plan node, and add their
377 * extParams to the topmost node's, too.
379 * We also add the total_cost of each initPlan to the startup cost of
380 * the top node. This is a conservative overestimate, since in
381 * fact each initPlan might be executed later than plan startup,
382 * or even not at all.
384 plan->initPlan = PlannerInitPlan;
386 foreach(l, plan->initPlan)
388 SubPlan *initplan = (SubPlan *) lfirst(l);
390 plan->extParam = bms_add_members(plan->extParam,
391 initplan->plan->extParam);
392 /* allParam must include all members of extParam */
393 plan->allParam = bms_add_members(plan->allParam,
395 initplan_cost += initplan->plan->total_cost;
398 plan->startup_cost += initplan_cost;
399 plan->total_cost += initplan_cost;
402 /* Return to outer subquery context */
404 PlannerInitPlan = saved_initplan;
405 /* we do NOT restore PlannerPlanId; that's not an oversight! */
411 * preprocess_expression
412 * Do subquery_planner's preprocessing work for an expression,
413 * which can be a targetlist, a WHERE clause (including JOIN/ON
414 * conditions), or a HAVING clause.
417 preprocess_expression(Query *parse, Node *expr, int kind)
420 * If the query has any join RTEs, replace join alias variables with
421 * base-relation variables. We must do this before sublink processing,
422 * else sublinks expanded out from join aliases wouldn't get
425 if (parse->hasJoinRTEs)
426 expr = flatten_join_alias_vars(parse, expr);
429 * Simplify constant expressions.
431 * Note: this also flattens nested AND and OR expressions into N-argument
432 * form. All processing of a qual expression after this point must be
433 * careful to maintain AND/OR flatness --- that is, do not generate a tree
434 * with AND directly under AND, nor OR directly under OR.
436 expr = eval_const_expressions(expr);
439 * If it's a qual or havingQual, canonicalize it.
441 if (kind == EXPRKIND_QUAL)
443 expr = (Node *) canonicalize_qual((Expr *) expr);
445 #ifdef OPTIMIZER_DEBUG
446 printf("After canonicalize_qual()\n");
451 /* Expand SubLinks to SubPlans */
452 if (parse->hasSubLinks)
453 expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL));
456 * XXX do not insert anything here unless you have grokked the
457 * comments in SS_replace_correlation_vars ...
460 /* Replace uplevel vars with Param nodes */
461 if (PlannerQueryLevel > 1)
462 expr = SS_replace_correlation_vars(expr);
465 * If it's a qual or havingQual, convert it to implicit-AND format.
466 * (We don't want to do this before eval_const_expressions, since the
467 * latter would be unable to simplify a top-level AND correctly. Also,
468 * SS_process_sublinks expects explicit-AND format.)
470 if (kind == EXPRKIND_QUAL)
471 expr = (Node *) make_ands_implicit((Expr *) expr);
477 * preprocess_qual_conditions
478 * Recursively scan the query's jointree and do subquery_planner's
479 * preprocessing work on each qual condition found therein.
482 preprocess_qual_conditions(Query *parse, Node *jtnode)
486 if (IsA(jtnode, RangeTblRef))
488 /* nothing to do here */
490 else if (IsA(jtnode, FromExpr))
492 FromExpr *f = (FromExpr *) jtnode;
495 foreach(l, f->fromlist)
496 preprocess_qual_conditions(parse, lfirst(l));
498 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_QUAL);
500 else if (IsA(jtnode, JoinExpr))
502 JoinExpr *j = (JoinExpr *) jtnode;
504 preprocess_qual_conditions(parse, j->larg);
505 preprocess_qual_conditions(parse, j->rarg);
507 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_QUAL);
510 elog(ERROR, "unrecognized node type: %d",
511 (int) nodeTag(jtnode));
514 /*--------------------
515 * inheritance_planner
516 * Generate a plan in the case where the result relation is an
519 * We have to handle this case differently from cases where a source
520 * relation is an inheritance set. Source inheritance is expanded at
521 * the bottom of the plan tree (see allpaths.c), but target inheritance
522 * has to be expanded at the top. The reason is that for UPDATE, each
523 * target relation needs a different targetlist matching its own column
524 * set. (This is not so critical for DELETE, but for simplicity we treat
525 * inherited DELETE the same way.) Fortunately, the UPDATE/DELETE target
526 * can never be the nullable side of an outer join, so it's OK to generate
529 * parse is the querytree produced by the parser & rewriter.
530 * inheritlist is an integer list of RT indexes for the result relation set.
532 * Returns a query plan.
533 *--------------------
536 inheritance_planner(Query *parse, List *inheritlist)
538 int parentRTindex = parse->resultRelation;
539 Oid parentOID = getrelid(parentRTindex, parse->rtable);
540 int mainrtlength = list_length(parse->rtable);
541 List *subplans = NIL;
545 foreach(l, inheritlist)
547 int childRTindex = lfirst_int(l);
548 Oid childOID = getrelid(childRTindex, parse->rtable);
552 /* Generate modified query with this rel as target */
553 subquery = (Query *) adjust_inherited_attrs((Node *) parse,
554 parentRTindex, parentOID,
555 childRTindex, childOID);
557 subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */ );
558 subplans = lappend(subplans, subplan);
561 * XXX my goodness this next bit is ugly. Really need to think about
562 * ways to rein in planner's habit of scribbling on its input.
564 * Planning of the subquery might have modified the rangetable,
565 * either by addition of RTEs due to expansion of inherited source
566 * tables, or by changes of the Query structures inside subquery
567 * RTEs. We have to ensure that this gets propagated back to the
568 * master copy. However, if we aren't done planning yet, we also
569 * need to ensure that subsequent calls to grouping_planner have
570 * virgin sub-Queries to work from. So, if we are at the last
571 * list entry, just copy the subquery rangetable back to the master
572 * copy; if we are not, then extend the master copy by adding
573 * whatever the subquery added. (We assume these added entries
574 * will go untouched by the future grouping_planner calls. We are
575 * also effectively assuming that sub-Queries will get planned
576 * identically each time, or at least that the impacts on their
577 * rangetables will be the same each time. Did I say this is ugly?)
579 if (lnext(l) == NULL)
580 parse->rtable = subquery->rtable;
583 int subrtlength = list_length(subquery->rtable);
585 if (subrtlength > mainrtlength)
589 subrt = list_copy_tail(subquery->rtable, mainrtlength);
590 parse->rtable = list_concat(parse->rtable, subrt);
591 mainrtlength = subrtlength;
595 /* Save preprocessed tlist from first rel for use in Append */
597 tlist = subplan->targetlist;
600 /* Save the target-relations list for the executor, too */
601 parse->resultRelations = inheritlist;
603 /* Mark result as unordered (probably unnecessary) */
604 parse->query_pathkeys = NIL;
606 return (Plan *) make_append(subplans, true, tlist);
609 /*--------------------
611 * Perform planning steps related to grouping, aggregation, etc.
612 * This primarily means adding top-level processing to the basic
613 * query plan produced by query_planner.
615 * parse is the querytree produced by the parser & rewriter.
616 * tuple_fraction is the fraction of tuples we expect will be retrieved
618 * tuple_fraction is interpreted as follows:
619 * 0: expect all tuples to be retrieved (normal case)
620 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
621 * from the plan to be retrieved
622 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
623 * expected to be retrieved (ie, a LIMIT specification)
625 * Returns a query plan. Also, parse->query_pathkeys is returned as the
626 * actual output ordering of the plan (in pathkey format).
627 *--------------------
630 grouping_planner(Query *parse, double tuple_fraction)
632 List *tlist = parse->targetList;
634 List *current_pathkeys;
637 if (parse->setOperations)
639 List *set_sortclauses;
642 * Construct the plan for set operations. The result will not
643 * need any work except perhaps a top-level sort and/or LIMIT.
645 result_plan = plan_set_operations(parse,
649 * Calculate pathkeys representing the sort order (if any) of the
650 * set operation's result. We have to do this before overwriting
651 * the sort key information...
653 current_pathkeys = make_pathkeys_for_sortclauses(set_sortclauses,
654 result_plan->targetlist);
655 current_pathkeys = canonicalize_pathkeys(parse, current_pathkeys);
658 * We should not need to call preprocess_targetlist, since we must
659 * be in a SELECT query node. Instead, use the targetlist
660 * returned by plan_set_operations (since this tells whether it
661 * returned any resjunk columns!), and transfer any sort key
662 * information from the original tlist.
664 Assert(parse->commandType == CMD_SELECT);
666 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
669 * Can't handle FOR UPDATE here (parser should have checked
670 * already, but let's make sure).
674 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
675 errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
678 * Calculate pathkeys that represent result ordering requirements
680 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
682 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
686 /* No set operations, do regular planning */
688 List *group_pathkeys;
689 AttrNumber *groupColIdx = NULL;
690 bool need_tlist_eval = true;
692 double sub_tuple_fraction;
695 double dNumGroups = 0;
697 AggClauseCounts agg_counts;
698 int numGroupCols = list_length(parse->groupClause);
699 bool use_hashed_grouping = false;
701 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
703 /* Preprocess targetlist */
704 tlist = preprocess_targetlist(parse, tlist);
707 * Generate appropriate target list for subplan; may be different
708 * from tlist if grouping or aggregation is needed.
710 sub_tlist = make_subplanTargetList(parse, tlist,
711 &groupColIdx, &need_tlist_eval);
714 * Calculate pathkeys that represent grouping/ordering
717 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
719 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
723 * Will need actual number of aggregates for estimating costs.
725 * Note: we do not attempt to detect duplicate aggregates here; a
726 * somewhat-overestimated count is okay for our present purposes.
728 * Note: think not that we can turn off hasAggs if we find no aggs.
729 * It is possible for constant-expression simplification to remove
730 * all explicit references to aggs, but we still have to follow
731 * the aggregate semantics (eg, producing only one output row).
735 count_agg_clauses((Node *) tlist, &agg_counts);
736 count_agg_clauses(parse->havingQual, &agg_counts);
740 * Figure out whether we need a sorted result from query_planner.
742 * If we have a GROUP BY clause, then we want a result sorted
743 * properly for grouping. Otherwise, if there is an ORDER BY
744 * clause, we want to sort by the ORDER BY clause. (Note: if we
745 * have both, and ORDER BY is a superset of GROUP BY, it would be
746 * tempting to request sort by ORDER BY --- but that might just
747 * leave us failing to exploit an available sort order at all.
748 * Needs more thought...)
750 if (parse->groupClause)
751 parse->query_pathkeys = group_pathkeys;
752 else if (parse->sortClause)
753 parse->query_pathkeys = sort_pathkeys;
755 parse->query_pathkeys = NIL;
758 * Adjust tuple_fraction if we see that we are going to apply
759 * limiting/grouping/aggregation/etc. This is not overridable by
760 * the caller, since it reflects plan actions that this routine
761 * will certainly take, not assumptions about context.
763 if (parse->limitCount != NULL)
766 * A LIMIT clause limits the absolute number of tuples
767 * returned. However, if it's not a constant LIMIT then we
768 * have to punt; for lack of a better idea, assume 10% of the
769 * plan's result is wanted.
771 double limit_fraction = 0.0;
773 if (IsA(parse->limitCount, Const))
775 Const *limitc = (Const *) parse->limitCount;
776 int32 count = DatumGetInt32(limitc->constvalue);
779 * A NULL-constant LIMIT represents "LIMIT ALL", which we
780 * treat the same as no limit (ie, expect to retrieve all
783 if (!limitc->constisnull && count > 0)
785 limit_fraction = (double) count;
786 /* We must also consider the OFFSET, if present */
787 if (parse->limitOffset != NULL)
789 if (IsA(parse->limitOffset, Const))
793 limitc = (Const *) parse->limitOffset;
794 offset = DatumGetInt32(limitc->constvalue);
795 if (!limitc->constisnull && offset > 0)
796 limit_fraction += (double) offset;
800 /* OFFSET is an expression ... punt ... */
801 limit_fraction = 0.10;
808 /* LIMIT is an expression ... punt ... */
809 limit_fraction = 0.10;
812 if (limit_fraction > 0.0)
815 * If we have absolute limits from both caller and LIMIT,
816 * use the smaller value; if one is fractional and the
817 * other absolute, treat the fraction as a fraction of the
818 * absolute value; else we can multiply the two fractions
821 if (tuple_fraction >= 1.0)
823 if (limit_fraction >= 1.0)
826 tuple_fraction = Min(tuple_fraction, limit_fraction);
830 /* caller absolute, limit fractional */
831 tuple_fraction *= limit_fraction;
832 if (tuple_fraction < 1.0)
833 tuple_fraction = 1.0;
836 else if (tuple_fraction > 0.0)
838 if (limit_fraction >= 1.0)
840 /* caller fractional, limit absolute */
841 tuple_fraction *= limit_fraction;
842 if (tuple_fraction < 1.0)
843 tuple_fraction = 1.0;
847 /* both fractional */
848 tuple_fraction *= limit_fraction;
853 /* no info from caller, just use limit */
854 tuple_fraction = limit_fraction;
860 * With grouping or aggregation, the tuple fraction to pass to
861 * query_planner() may be different from what it is at top level.
863 sub_tuple_fraction = tuple_fraction;
865 if (parse->groupClause)
868 * In GROUP BY mode, we have the little problem that we don't
869 * really know how many input tuples will be needed to make a
870 * group, so we can't translate an output LIMIT count into an
871 * input count. For lack of a better idea, assume 25% of the
872 * input data will be processed if there is any output limit.
873 * However, if the caller gave us a fraction rather than an
874 * absolute count, we can keep using that fraction (which
875 * amounts to assuming that all the groups are about the same
878 if (sub_tuple_fraction >= 1.0)
879 sub_tuple_fraction = 0.25;
882 * If both GROUP BY and ORDER BY are specified, we will need
883 * two levels of sort --- and, therefore, certainly need to
884 * read all the input tuples --- unless ORDER BY is a subset
885 * of GROUP BY. (We have not yet canonicalized the pathkeys,
886 * so must use the slower noncanonical comparison method.)
888 if (parse->groupClause && parse->sortClause &&
889 !noncanonical_pathkeys_contained_in(sort_pathkeys,
891 sub_tuple_fraction = 0.0;
893 else if (parse->hasAggs)
896 * Ungrouped aggregate will certainly want all the input
899 sub_tuple_fraction = 0.0;
901 else if (parse->distinctClause)
904 * SELECT DISTINCT, like GROUP, will absorb an unpredictable
905 * number of input tuples per output tuple. Handle the same
908 if (sub_tuple_fraction >= 1.0)
909 sub_tuple_fraction = 0.25;
913 * Generate the best unsorted and presorted paths for this Query
914 * (but note there may not be any presorted path).
916 query_planner(parse, sub_tlist, sub_tuple_fraction,
917 &cheapest_path, &sorted_path);
920 * We couldn't canonicalize group_pathkeys and sort_pathkeys
921 * before running query_planner(), so do it now.
923 group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
924 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
927 * If grouping, estimate the number of groups. (We can't do this
928 * until after running query_planner(), either.) Then decide
929 * whether we want to use hashed grouping.
931 if (parse->groupClause)
934 double cheapest_path_rows;
937 * Beware of the possibility that cheapest_path->parent is NULL.
938 * This could happen if user does something silly like
939 * SELECT 'foo' GROUP BY 1;
941 if (cheapest_path->parent)
942 cheapest_path_rows = cheapest_path->parent->rows;
944 cheapest_path_rows = 1; /* assume non-set result */
946 groupExprs = get_sortgrouplist_exprs(parse->groupClause,
948 dNumGroups = estimate_num_groups(parse,
951 /* Also want it as a long int --- but 'ware overflow! */
952 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
954 use_hashed_grouping =
955 choose_hashed_grouping(parse, tuple_fraction,
956 cheapest_path, sorted_path,
957 sort_pathkeys, group_pathkeys,
958 dNumGroups, &agg_counts);
962 * Select the best path and create a plan to execute it.
964 * If we are doing hashed grouping, we will always read all the input
965 * tuples, so use the cheapest-total path. Otherwise, trust
966 * query_planner's decision about which to use.
968 if (sorted_path && !use_hashed_grouping)
970 result_plan = create_plan(parse, sorted_path);
971 current_pathkeys = sorted_path->pathkeys;
975 result_plan = create_plan(parse, cheapest_path);
976 current_pathkeys = cheapest_path->pathkeys;
980 * create_plan() returns a plan with just a "flat" tlist of
981 * required Vars. Usually we need to insert the sub_tlist as the
982 * tlist of the top plan node. However, we can skip that if we
983 * determined that whatever query_planner chose to return will be
989 * If the top-level plan node is one that cannot do expression
990 * evaluation, we must insert a Result node to project the
993 if (!is_projection_capable_plan(result_plan))
995 result_plan = (Plan *) make_result(sub_tlist, NULL,
1001 * Otherwise, just replace the subplan's flat tlist with
1002 * the desired tlist.
1004 result_plan->targetlist = sub_tlist;
1008 * Also, account for the cost of evaluation of the sub_tlist.
1010 * Up to now, we have only been dealing with "flat" tlists,
1011 * containing just Vars. So their evaluation cost is zero
1012 * according to the model used by cost_qual_eval() (or if you
1013 * prefer, the cost is factored into cpu_tuple_cost). Thus we
1014 * can avoid accounting for tlist cost throughout
1015 * query_planner() and subroutines. But now we've inserted a
1016 * tlist that might contain actual operators, sub-selects, etc
1017 * --- so we'd better account for its cost.
1019 * Below this point, any tlist eval cost for added-on nodes
1020 * should be accounted for as we create those nodes.
1021 * Presently, of the node types we can add on, only Agg and
1022 * Group project new tlists (the rest just copy their input
1023 * tuples) --- so make_agg() and make_group() are responsible
1024 * for computing the added cost.
1026 cost_qual_eval(&tlist_cost, sub_tlist);
1027 result_plan->startup_cost += tlist_cost.startup;
1028 result_plan->total_cost += tlist_cost.startup +
1029 tlist_cost.per_tuple * result_plan->plan_rows;
1034 * Since we're using query_planner's tlist and not the one
1035 * make_subplanTargetList calculated, we have to refigure any
1036 * grouping-column indexes make_subplanTargetList computed.
1038 locate_grouping_columns(parse, tlist, result_plan->targetlist,
1043 * Insert AGG or GROUP node if needed, plus an explicit sort step
1046 * HAVING clause, if any, becomes qual of the Agg or Group node.
1048 if (use_hashed_grouping)
1050 /* Hashed aggregate plan --- no sort needed */
1051 result_plan = (Plan *) make_agg(parse,
1053 (List *) parse->havingQual,
1060 /* Hashed aggregation produces randomly-ordered results */
1061 current_pathkeys = NIL;
1063 else if (parse->hasAggs)
1065 /* Plain aggregate plan --- sort if needed */
1066 AggStrategy aggstrategy;
1068 if (parse->groupClause)
1070 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1072 result_plan = (Plan *)
1073 make_sort_from_groupcols(parse,
1077 current_pathkeys = group_pathkeys;
1079 aggstrategy = AGG_SORTED;
1082 * The AGG node will not change the sort ordering of its
1083 * groups, so current_pathkeys describes the result too.
1088 aggstrategy = AGG_PLAIN;
1089 /* Result will be only one row anyway; no sort order */
1090 current_pathkeys = NIL;
1093 result_plan = (Plan *) make_agg(parse,
1095 (List *) parse->havingQual,
1103 else if (parse->groupClause)
1106 * GROUP BY without aggregation, so insert a group node (plus the
1107 * appropriate sort node, if necessary).
1109 * Add an explicit sort if we couldn't make the path come
1110 * out the way the GROUP node needs it.
1112 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1114 result_plan = (Plan *)
1115 make_sort_from_groupcols(parse,
1119 current_pathkeys = group_pathkeys;
1122 result_plan = (Plan *) make_group(parse,
1124 (List *) parse->havingQual,
1129 /* The Group node won't change sort ordering */
1131 else if (parse->hasHavingQual)
1134 * No aggregates, and no GROUP BY, but we have a HAVING qual.
1135 * This is a degenerate case in which we are supposed to emit
1136 * either 0 or 1 row depending on whether HAVING succeeds.
1137 * Furthermore, there cannot be any variables in either HAVING
1138 * or the targetlist, so we actually do not need the FROM table
1139 * at all! We can just throw away the plan-so-far and generate
1140 * a Result node. This is a sufficiently unusual corner case
1141 * that it's not worth contorting the structure of this routine
1142 * to avoid having to generate the plan in the first place.
1144 result_plan = (Plan *) make_result(tlist,
1148 } /* end of if (setOperations) */
1151 * If we were not able to make the plan come out in the right order,
1152 * add an explicit sort step.
1154 if (parse->sortClause)
1156 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1158 result_plan = (Plan *)
1159 make_sort_from_sortclauses(parse,
1162 current_pathkeys = sort_pathkeys;
1167 * If there is a DISTINCT clause, add the UNIQUE node.
1169 if (parse->distinctClause)
1171 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1174 * If there was grouping or aggregation, leave plan_rows as-is
1175 * (ie, assume the result was already mostly unique). If not,
1176 * it's reasonable to assume the UNIQUE filter has effects
1177 * comparable to GROUP BY.
1179 if (!parse->groupClause && !parse->hasHavingQual && !parse->hasAggs)
1181 List *distinctExprs;
1183 distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
1185 result_plan->plan_rows = estimate_num_groups(parse,
1187 result_plan->plan_rows);
1192 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1194 if (parse->limitOffset || parse->limitCount)
1196 result_plan = (Plan *) make_limit(result_plan,
1202 * Return the actual output ordering in query_pathkeys for possible
1203 * use by an outer query level.
1205 parse->query_pathkeys = current_pathkeys;
1211 * choose_hashed_grouping - should we use hashed grouping?
1214 choose_hashed_grouping(Query *parse, double tuple_fraction,
1215 Path *cheapest_path, Path *sorted_path,
1216 List *sort_pathkeys, List *group_pathkeys,
1217 double dNumGroups, AggClauseCounts *agg_counts)
1219 int numGroupCols = list_length(parse->groupClause);
1220 double cheapest_path_rows;
1221 int cheapest_path_width;
1223 List *current_pathkeys;
1228 * Check can't-do-it conditions, including whether the grouping operators
1231 * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1232 * (Doing so would imply storing *all* the input values in the hash table,
1233 * which seems like a certain loser.)
1235 if (!enable_hashagg)
1237 if (agg_counts->numDistinctAggs != 0)
1239 if (!hash_safe_grouping(parse))
1243 * Don't do it if it doesn't look like the hashtable will fit into
1246 * Beware here of the possibility that cheapest_path->parent is NULL.
1247 * This could happen if user does something silly like
1248 * SELECT 'foo' GROUP BY 1;
1250 if (cheapest_path->parent)
1252 cheapest_path_rows = cheapest_path->parent->rows;
1253 cheapest_path_width = cheapest_path->parent->width;
1257 cheapest_path_rows = 1; /* assume non-set result */
1258 cheapest_path_width = 100; /* arbitrary */
1261 /* Estimate per-hash-entry space at tuple width... */
1262 hashentrysize = cheapest_path_width;
1263 /* plus space for pass-by-ref transition values... */
1264 hashentrysize += agg_counts->transitionSpace;
1265 /* plus the per-hash-entry overhead */
1266 hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1268 if (hashentrysize * dNumGroups > work_mem * 1024L)
1272 * See if the estimated cost is no more than doing it the other way.
1273 * While avoiding the need for sorted input is usually a win, the fact
1274 * that the output won't be sorted may be a loss; so we need to do an
1275 * actual cost comparison.
1277 * We need to consider
1278 * cheapest_path + hashagg [+ final sort]
1280 * cheapest_path [+ sort] + group or agg [+ final sort]
1282 * presorted_path + group or agg [+ final sort]
1283 * where brackets indicate a step that may not be needed. We assume
1284 * query_planner() will have returned a presorted path only if it's a
1285 * winner compared to cheapest_path for this purpose.
1287 * These path variables are dummies that just hold cost fields; we don't
1288 * make actual Paths for these steps.
1290 cost_agg(&hashed_p, parse, AGG_HASHED, agg_counts->numAggs,
1291 numGroupCols, dNumGroups,
1292 cheapest_path->startup_cost, cheapest_path->total_cost,
1293 cheapest_path_rows);
1294 /* Result of hashed agg is always unsorted */
1296 cost_sort(&hashed_p, parse, sort_pathkeys, hashed_p.total_cost,
1297 dNumGroups, cheapest_path_width);
1301 sorted_p.startup_cost = sorted_path->startup_cost;
1302 sorted_p.total_cost = sorted_path->total_cost;
1303 current_pathkeys = sorted_path->pathkeys;
1307 sorted_p.startup_cost = cheapest_path->startup_cost;
1308 sorted_p.total_cost = cheapest_path->total_cost;
1309 current_pathkeys = cheapest_path->pathkeys;
1311 if (!pathkeys_contained_in(group_pathkeys,
1314 cost_sort(&sorted_p, parse, group_pathkeys, sorted_p.total_cost,
1315 cheapest_path_rows, cheapest_path_width);
1316 current_pathkeys = group_pathkeys;
1320 cost_agg(&sorted_p, parse, AGG_SORTED, agg_counts->numAggs,
1321 numGroupCols, dNumGroups,
1322 sorted_p.startup_cost, sorted_p.total_cost,
1323 cheapest_path_rows);
1325 cost_group(&sorted_p, parse, numGroupCols, dNumGroups,
1326 sorted_p.startup_cost, sorted_p.total_cost,
1327 cheapest_path_rows);
1328 /* The Agg or Group node will preserve ordering */
1329 if (sort_pathkeys &&
1330 !pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1331 cost_sort(&sorted_p, parse, sort_pathkeys, sorted_p.total_cost,
1332 dNumGroups, cheapest_path_width);
1335 * Now make the decision using the top-level tuple fraction. First we
1336 * have to convert an absolute count (LIMIT) into fractional form.
1338 if (tuple_fraction >= 1.0)
1339 tuple_fraction /= dNumGroups;
1341 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1342 tuple_fraction) < 0)
1344 /* Hashed is cheaper, so use it */
1351 * hash_safe_grouping - are grouping operators hashable?
1353 * We assume hashed aggregation will work if the datatype's equality operator
1354 * is marked hashjoinable.
1357 hash_safe_grouping(Query *parse)
1361 foreach(gl, parse->groupClause)
1363 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1364 TargetEntry *tle = get_sortgroupclause_tle(grpcl, parse->targetList);
1368 optup = equality_oper(exprType((Node *) tle->expr), true);
1371 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1372 ReleaseSysCache(optup);
1380 * make_subplanTargetList
1381 * Generate appropriate target list when grouping is required.
1383 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1384 * above the result of query_planner, we typically want to pass a different
1385 * target list to query_planner than the outer plan nodes should have.
1386 * This routine generates the correct target list for the subplan.
1388 * The initial target list passed from the parser already contains entries
1389 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1390 * for variables used only in HAVING clauses; so we need to add those
1391 * variables to the subplan target list. Also, we flatten all expressions
1392 * except GROUP BY items into their component variables; the other expressions
1393 * will be computed by the inserted nodes rather than by the subplan.
1394 * For example, given a query like
1395 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1396 * we want to pass this targetlist to the subplan:
1398 * where the a+b target will be used by the Sort/Group steps, and the
1399 * other targets will be used for computing the final results. (In the
1400 * above example we could theoretically suppress the a and b targets and
1401 * pass down only c,d,a+b, but it's not really worth the trouble to
1402 * eliminate simple var references from the subplan. We will avoid doing
1403 * the extra computation to recompute a+b at the outer level; see
1404 * replace_vars_with_subplan_refs() in setrefs.c.)
1406 * If we are grouping or aggregating, *and* there are no non-Var grouping
1407 * expressions, then the returned tlist is effectively dummy; we do not
1408 * need to force it to be evaluated, because all the Vars it contains
1409 * should be present in the output of query_planner anyway.
1411 * 'parse' is the query being processed.
1412 * 'tlist' is the query's target list.
1413 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1414 * expressions (if there are any) in the subplan's target list.
1415 * 'need_tlist_eval' is set true if we really need to evaluate the
1418 * The result is the targetlist to be passed to the subplan.
1422 make_subplanTargetList(Query *parse,
1424 AttrNumber **groupColIdx,
1425 bool *need_tlist_eval)
1431 *groupColIdx = NULL;
1434 * If we're not grouping or aggregating, there's nothing to do here;
1435 * query_planner should receive the unmodified target list.
1437 if (!parse->hasAggs && !parse->groupClause && !parse->hasHavingQual)
1439 *need_tlist_eval = true;
1444 * Otherwise, start with a "flattened" tlist (having just the vars
1445 * mentioned in the targetlist and HAVING qual --- but not upper-
1446 * level Vars; they will be replaced by Params later on).
1448 sub_tlist = flatten_tlist(tlist);
1449 extravars = pull_var_clause(parse->havingQual, false);
1450 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1451 list_free(extravars);
1452 *need_tlist_eval = false; /* only eval if not flat tlist */
1455 * If grouping, create sub_tlist entries for all GROUP BY expressions
1456 * (GROUP BY items that are simple Vars should be in the list
1457 * already), and make an array showing where the group columns are in
1460 numCols = list_length(parse->groupClause);
1464 AttrNumber *grpColIdx;
1467 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1468 *groupColIdx = grpColIdx;
1470 foreach(gl, parse->groupClause)
1472 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1473 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1474 TargetEntry *te = NULL;
1477 /* Find or make a matching sub_tlist entry */
1478 foreach(sl, sub_tlist)
1480 te = (TargetEntry *) lfirst(sl);
1481 if (equal(groupexpr, te->expr))
1486 te = makeTargetEntry((Expr *) groupexpr,
1487 list_length(sub_tlist) + 1,
1490 sub_tlist = lappend(sub_tlist, te);
1491 *need_tlist_eval = true; /* it's not flat anymore */
1494 /* and save its resno */
1495 grpColIdx[keyno++] = te->resno;
1503 * locate_grouping_columns
1504 * Locate grouping columns in the tlist chosen by query_planner.
1506 * This is only needed if we don't use the sub_tlist chosen by
1507 * make_subplanTargetList. We have to forget the column indexes found
1508 * by that routine and re-locate the grouping vars in the real sub_tlist.
1511 locate_grouping_columns(Query *parse,
1514 AttrNumber *groupColIdx)
1520 * No work unless grouping.
1522 if (!parse->groupClause)
1524 Assert(groupColIdx == NULL);
1527 Assert(groupColIdx != NULL);
1529 foreach(gl, parse->groupClause)
1531 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1532 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1533 TargetEntry *te = NULL;
1536 foreach(sl, sub_tlist)
1538 te = (TargetEntry *) lfirst(sl);
1539 if (equal(groupexpr, te->expr))
1543 elog(ERROR, "failed to locate grouping columns");
1545 groupColIdx[keyno++] = te->resno;
1550 * postprocess_setop_tlist
1551 * Fix up targetlist returned by plan_set_operations().
1553 * We need to transpose sort key info from the orig_tlist into new_tlist.
1554 * NOTE: this would not be good enough if we supported resjunk sort keys
1555 * for results of set operations --- then, we'd need to project a whole
1556 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1557 * find any resjunk columns in orig_tlist.
1560 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1563 ListCell *orig_tlist_item = list_head(orig_tlist);
1565 foreach(l, new_tlist)
1567 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1568 TargetEntry *orig_tle;
1570 /* ignore resjunk columns in setop result */
1571 if (new_tle->resjunk)
1574 Assert(orig_tlist_item != NULL);
1575 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1576 orig_tlist_item = lnext(orig_tlist_item);
1577 if (orig_tle->resjunk) /* should not happen */
1578 elog(ERROR, "resjunk output columns are not implemented");
1579 Assert(new_tle->resno == orig_tle->resno);
1580 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1582 if (orig_tlist_item != NULL)
1583 elog(ERROR, "resjunk output columns are not implemented");