1 /*-------------------------------------------------------------------------
4 * The query optimizer external interface.
6 * Portions Copyright (c) 1996-2003, 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.171 2004/05/30 23:40:29 neilc Exp $
13 *-------------------------------------------------------------------------
20 #include "catalog/pg_operator.h"
21 #include "catalog/pg_type.h"
22 #include "executor/executor.h"
23 #include "miscadmin.h"
24 #include "nodes/makefuncs.h"
25 #ifdef OPTIMIZER_DEBUG
26 #include "nodes/print.h"
28 #include "optimizer/clauses.h"
29 #include "optimizer/cost.h"
30 #include "optimizer/pathnode.h"
31 #include "optimizer/paths.h"
32 #include "optimizer/planmain.h"
33 #include "optimizer/planner.h"
34 #include "optimizer/prep.h"
35 #include "optimizer/subselect.h"
36 #include "optimizer/tlist.h"
37 #include "optimizer/var.h"
38 #include "parser/analyze.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 /* Expression kind codes for preprocess_expression */
47 #define EXPRKIND_QUAL 0
48 #define EXPRKIND_TARGET 1
49 #define EXPRKIND_RTFUNC 2
50 #define EXPRKIND_LIMIT 3
51 #define EXPRKIND_ININFO 4
54 static Node *preprocess_expression(Query *parse, Node *expr, int kind);
55 static void preprocess_qual_conditions(Query *parse, Node *jtnode);
56 static Plan *inheritance_planner(Query *parse, List *inheritlist);
57 static Plan *grouping_planner(Query *parse, double tuple_fraction);
58 static bool hash_safe_grouping(Query *parse);
59 static List *make_subplanTargetList(Query *parse, List *tlist,
60 AttrNumber **groupColIdx, bool *need_tlist_eval);
61 static void locate_grouping_columns(Query *parse,
64 AttrNumber *groupColIdx);
65 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
68 /*****************************************************************************
70 * Query optimizer entry point
72 *****************************************************************************/
74 planner(Query *parse, bool isCursor, int cursorOptions)
76 double tuple_fraction;
78 Index save_PlannerQueryLevel;
79 List *save_PlannerParamList;
82 * The planner can be called recursively (an example is when
83 * eval_const_expressions tries to pre-evaluate an SQL function). So,
84 * these global state variables must be saved and restored.
86 * These vars cannot be moved into the Query structure since their whole
87 * purpose is communication across multiple sub-Queries.
89 * Note we do NOT save and restore PlannerPlanId: it exists to assign
90 * unique IDs to SubPlan nodes, and we want those IDs to be unique for
91 * the life of a backend. Also, PlannerInitPlan is saved/restored in
92 * subquery_planner, not here.
94 save_PlannerQueryLevel = PlannerQueryLevel;
95 save_PlannerParamList = PlannerParamList;
97 /* Initialize state for handling outer-level references and params */
98 PlannerQueryLevel = 0; /* will be 1 in top-level subquery_planner */
99 PlannerParamList = NIL;
101 /* Determine what fraction of the plan is likely to be scanned */
105 * We have no real idea how many tuples the user will ultimately
106 * FETCH from a cursor, but it seems a good bet that he doesn't
107 * want 'em all. Optimize for 10% retrieval (you gotta better
108 * number? Should this be a SETtable parameter?)
110 tuple_fraction = 0.10;
114 /* Default assumption is we need all the tuples */
115 tuple_fraction = 0.0;
118 /* primary planning entry point (may recurse for subqueries) */
119 result_plan = subquery_planner(parse, tuple_fraction);
121 Assert(PlannerQueryLevel == 0);
124 * If creating a plan for a scrollable cursor, make sure it can run
125 * backwards on demand. Add a Material node at the top at need.
127 if (isCursor && (cursorOptions & CURSOR_OPT_SCROLL))
129 if (!ExecSupportsBackwardScan(result_plan))
130 result_plan = materialize_finished_plan(result_plan);
133 /* executor wants to know total number of Params used overall */
134 result_plan->nParamExec = list_length(PlannerParamList);
136 /* final cleanup of the plan */
137 set_plan_references(result_plan, parse->rtable);
139 /* restore state for outer planner, if any */
140 PlannerQueryLevel = save_PlannerQueryLevel;
141 PlannerParamList = save_PlannerParamList;
147 /*--------------------
149 * Invokes the planner on a subquery. We recurse to here for each
150 * sub-SELECT found in the query tree.
152 * parse is the querytree produced by the parser & rewriter.
153 * tuple_fraction is the fraction of tuples we expect will be retrieved.
154 * tuple_fraction is interpreted as explained for grouping_planner, below.
156 * Basically, this routine does the stuff that should only be done once
157 * per Query object. It then calls grouping_planner. At one time,
158 * grouping_planner could be invoked recursively on the same Query object;
159 * that's not currently true, but we keep the separation between the two
160 * routines anyway, in case we need it again someday.
162 * subquery_planner will be called recursively to handle sub-Query nodes
163 * found within the query's expressions and rangetable.
165 * Returns a query plan.
166 *--------------------
169 subquery_planner(Query *parse, double tuple_fraction)
171 List *saved_initplan = PlannerInitPlan;
172 int saved_planid = PlannerPlanId;
179 /* Set up for a new level of subquery */
181 PlannerInitPlan = NIL;
184 * Look for IN clauses at the top level of WHERE, and transform them
185 * into joins. Note that this step only handles IN clauses originally
186 * at top level of WHERE; if we pull up any subqueries in the next
187 * step, their INs are processed just before pulling them up.
189 parse->in_info_list = NIL;
190 if (parse->hasSubLinks)
191 parse->jointree->quals = pull_up_IN_clauses(parse,
192 parse->jointree->quals);
195 * Check to see if any subqueries in the rangetable can be merged into
198 parse->jointree = (FromExpr *)
199 pull_up_subqueries(parse, (Node *) parse->jointree, false);
202 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we
203 * can avoid the expense of doing flatten_join_alias_vars(). Also
204 * check for outer joins --- if none, we can skip
205 * reduce_outer_joins(). This must be done after we have done
206 * pull_up_subqueries, of course.
208 parse->hasJoinRTEs = false;
209 hasOuterJoins = false;
210 foreach(l, parse->rtable)
212 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
214 if (rte->rtekind == RTE_JOIN)
216 parse->hasJoinRTEs = true;
217 if (IS_OUTER_JOIN(rte->jointype))
219 hasOuterJoins = true;
220 /* Can quit scanning once we find an outer join */
227 * Do expression preprocessing on targetlist and quals.
229 parse->targetList = (List *)
230 preprocess_expression(parse, (Node *) parse->targetList,
233 preprocess_qual_conditions(parse, (Node *) parse->jointree);
235 parse->havingQual = preprocess_expression(parse, parse->havingQual,
238 parse->limitOffset = preprocess_expression(parse, parse->limitOffset,
240 parse->limitCount = preprocess_expression(parse, parse->limitCount,
243 parse->in_info_list = (List *)
244 preprocess_expression(parse, (Node *) parse->in_info_list,
247 /* Also need to preprocess expressions for function RTEs */
248 foreach(l, parse->rtable)
250 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
252 if (rte->rtekind == RTE_FUNCTION)
253 rte->funcexpr = preprocess_expression(parse, rte->funcexpr,
258 * A HAVING clause without aggregates is equivalent to a WHERE clause
259 * (except it can only refer to grouped fields). Transfer any
260 * agg-free clauses of the HAVING qual into WHERE. This may seem like
261 * wasting cycles to cater to stupidly-written queries, but there are
262 * other reasons for doing it. Firstly, if the query contains no aggs
263 * at all, then we aren't going to generate an Agg plan node, and so
264 * there'll be no place to execute HAVING conditions; without this
265 * transfer, we'd lose the HAVING condition entirely, which is wrong.
266 * Secondly, when we push down a qual condition into a sub-query, it's
267 * easiest to push the qual into HAVING always, in case it contains
268 * aggs, and then let this code sort it out.
270 * Note that both havingQual and parse->jointree->quals are in
271 * implicitly-ANDed-list form at this point, even though they are
272 * declared as Node *.
275 foreach(l, (List *) parse->havingQual)
277 Node *havingclause = (Node *) lfirst(l);
279 if (contain_agg_clause(havingclause))
280 newHaving = lappend(newHaving, havingclause);
282 parse->jointree->quals = (Node *)
283 lappend((List *) parse->jointree->quals, havingclause);
285 parse->havingQual = (Node *) newHaving;
288 * If we have any outer joins, try to reduce them to plain inner
289 * joins. This step is most easily done after we've done expression
293 reduce_outer_joins(parse);
296 * See if we can simplify the jointree; opportunities for this may
297 * come from having pulled up subqueries, or from flattening explicit
298 * JOIN syntax. We must do this after flattening JOIN alias
299 * variables, since eliminating explicit JOIN nodes from the jointree
300 * will cause get_relids_for_join() to fail. But it should happen
301 * after reduce_outer_joins, anyway.
303 parse->jointree = (FromExpr *)
304 simplify_jointree(parse, (Node *) parse->jointree);
307 * Do the main planning. If we have an inherited target relation,
308 * that needs special processing, else go straight to
311 if (parse->resultRelation &&
312 (lst = expand_inherited_rtentry(parse, parse->resultRelation,
314 plan = inheritance_planner(parse, lst);
316 plan = grouping_planner(parse, tuple_fraction);
319 * If any subplans were generated, or if we're inside a subplan, build
320 * initPlan list and extParam/allParam sets for plan nodes.
322 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
324 Cost initplan_cost = 0;
326 /* Prepare extParam/allParam sets for all nodes in tree */
327 SS_finalize_plan(plan, parse->rtable);
330 * SS_finalize_plan doesn't handle initPlans, so we have to
331 * manually attach them to the topmost plan node, and add their
332 * extParams to the topmost node's, too.
334 * We also add the total_cost of each initPlan to the startup cost of
335 * the top node. This is a conservative overestimate, since in
336 * fact each initPlan might be executed later than plan startup,
337 * or even not at all.
339 plan->initPlan = PlannerInitPlan;
341 foreach(l, plan->initPlan)
343 SubPlan *initplan = (SubPlan *) lfirst(l);
345 plan->extParam = bms_add_members(plan->extParam,
346 initplan->plan->extParam);
347 /* allParam must include all members of extParam */
348 plan->allParam = bms_add_members(plan->allParam,
350 initplan_cost += initplan->plan->total_cost;
353 plan->startup_cost += initplan_cost;
354 plan->total_cost += initplan_cost;
357 /* Return to outer subquery context */
359 PlannerInitPlan = saved_initplan;
360 /* we do NOT restore PlannerPlanId; that's not an oversight! */
366 * preprocess_expression
367 * Do subquery_planner's preprocessing work for an expression,
368 * which can be a targetlist, a WHERE clause (including JOIN/ON
369 * conditions), or a HAVING clause.
372 preprocess_expression(Query *parse, Node *expr, int kind)
375 * If the query has any join RTEs, replace join alias variables with
376 * base-relation variables. We must do this before sublink processing,
377 * else sublinks expanded out from join aliases wouldn't get
380 if (parse->hasJoinRTEs)
381 expr = flatten_join_alias_vars(parse, expr);
384 * If it's a qual or havingQual, canonicalize it. It seems most useful
385 * to do this before applying eval_const_expressions, since the latter
386 * can optimize flattened AND/ORs better than unflattened ones.
388 * Note: all processing of a qual expression after this point must be
389 * careful to maintain AND/OR flatness --- that is, do not generate a
390 * tree with AND directly under AND, nor OR directly under OR.
392 if (kind == EXPRKIND_QUAL)
394 expr = (Node *) canonicalize_qual((Expr *) expr);
396 #ifdef OPTIMIZER_DEBUG
397 printf("After canonicalize_qual()\n");
403 * Simplify constant expressions.
405 expr = eval_const_expressions(expr);
407 /* Expand SubLinks to SubPlans */
408 if (parse->hasSubLinks)
409 expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL));
412 * XXX do not insert anything here unless you have grokked the
413 * comments in SS_replace_correlation_vars ...
416 /* Replace uplevel vars with Param nodes */
417 if (PlannerQueryLevel > 1)
418 expr = SS_replace_correlation_vars(expr);
421 * If it's a qual or havingQual, convert it to implicit-AND format.
422 * (We don't want to do this before eval_const_expressions, since the
423 * latter would be unable to simplify a top-level AND correctly. Also,
424 * SS_process_sublinks expects explicit-AND format.)
426 if (kind == EXPRKIND_QUAL)
427 expr = (Node *) make_ands_implicit((Expr *) expr);
433 * preprocess_qual_conditions
434 * Recursively scan the query's jointree and do subquery_planner's
435 * preprocessing work on each qual condition found therein.
438 preprocess_qual_conditions(Query *parse, Node *jtnode)
442 if (IsA(jtnode, RangeTblRef))
444 /* nothing to do here */
446 else if (IsA(jtnode, FromExpr))
448 FromExpr *f = (FromExpr *) jtnode;
451 foreach(l, f->fromlist)
452 preprocess_qual_conditions(parse, lfirst(l));
454 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_QUAL);
456 else if (IsA(jtnode, JoinExpr))
458 JoinExpr *j = (JoinExpr *) jtnode;
460 preprocess_qual_conditions(parse, j->larg);
461 preprocess_qual_conditions(parse, j->rarg);
463 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_QUAL);
466 elog(ERROR, "unrecognized node type: %d",
467 (int) nodeTag(jtnode));
470 /*--------------------
471 * inheritance_planner
472 * Generate a plan in the case where the result relation is an
475 * We have to handle this case differently from cases where a source
476 * relation is an inheritance set. Source inheritance is expanded at
477 * the bottom of the plan tree (see allpaths.c), but target inheritance
478 * has to be expanded at the top. The reason is that for UPDATE, each
479 * target relation needs a different targetlist matching its own column
480 * set. (This is not so critical for DELETE, but for simplicity we treat
481 * inherited DELETE the same way.) Fortunately, the UPDATE/DELETE target
482 * can never be the nullable side of an outer join, so it's OK to generate
485 * parse is the querytree produced by the parser & rewriter.
486 * inheritlist is an integer list of RT indexes for the result relation set.
488 * Returns a query plan.
489 *--------------------
492 inheritance_planner(Query *parse, List *inheritlist)
494 int parentRTindex = parse->resultRelation;
495 Oid parentOID = getrelid(parentRTindex, parse->rtable);
496 int mainrtlength = list_length(parse->rtable);
497 List *subplans = NIL;
501 foreach(l, inheritlist)
503 int childRTindex = lfirst_int(l);
504 Oid childOID = getrelid(childRTindex, parse->rtable);
509 /* Generate modified query with this rel as target */
510 subquery = (Query *) adjust_inherited_attrs((Node *) parse,
511 parentRTindex, parentOID,
512 childRTindex, childOID);
514 subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */ );
515 subplans = lappend(subplans, subplan);
518 * It's possible that additional RTEs got added to the rangetable
519 * due to expansion of inherited source tables (see allpaths.c).
520 * If so, we must copy 'em back to the main parse tree's rtable.
522 * XXX my goodness this is ugly. Really need to think about ways to
523 * rein in planner's habit of scribbling on its input.
525 subrtlength = list_length(subquery->rtable);
526 if (subrtlength > mainrtlength)
530 subrt = list_copy_tail(subquery->rtable, mainrtlength);
531 parse->rtable = list_concat(parse->rtable, subrt);
532 mainrtlength = subrtlength;
534 /* Save preprocessed tlist from first rel for use in Append */
536 tlist = subplan->targetlist;
539 /* Save the target-relations list for the executor, too */
540 parse->resultRelations = inheritlist;
542 /* Mark result as unordered (probably unnecessary) */
543 parse->query_pathkeys = NIL;
545 return (Plan *) make_append(subplans, true, tlist);
548 /*--------------------
550 * Perform planning steps related to grouping, aggregation, etc.
551 * This primarily means adding top-level processing to the basic
552 * query plan produced by query_planner.
554 * parse is the querytree produced by the parser & rewriter.
555 * tuple_fraction is the fraction of tuples we expect will be retrieved
557 * tuple_fraction is interpreted as follows:
558 * 0: expect all tuples to be retrieved (normal case)
559 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
560 * from the plan to be retrieved
561 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
562 * expected to be retrieved (ie, a LIMIT specification)
564 * Returns a query plan. Also, parse->query_pathkeys is returned as the
565 * actual output ordering of the plan (in pathkey format).
566 *--------------------
569 grouping_planner(Query *parse, double tuple_fraction)
571 List *tlist = parse->targetList;
573 List *current_pathkeys;
576 if (parse->setOperations)
578 List *set_sortclauses;
581 * Construct the plan for set operations. The result will not
582 * need any work except perhaps a top-level sort and/or LIMIT.
584 result_plan = plan_set_operations(parse,
588 * Calculate pathkeys representing the sort order (if any) of the
589 * set operation's result. We have to do this before overwriting
590 * the sort key information...
592 current_pathkeys = make_pathkeys_for_sortclauses(set_sortclauses,
593 result_plan->targetlist);
594 current_pathkeys = canonicalize_pathkeys(parse, current_pathkeys);
597 * We should not need to call preprocess_targetlist, since we must
598 * be in a SELECT query node. Instead, use the targetlist
599 * returned by plan_set_operations (since this tells whether it
600 * returned any resjunk columns!), and transfer any sort key
601 * information from the original tlist.
603 Assert(parse->commandType == CMD_SELECT);
605 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
608 * Can't handle FOR UPDATE here (parser should have checked
609 * already, but let's make sure).
613 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
614 errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
617 * Calculate pathkeys that represent result ordering requirements
619 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
621 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
625 /* No set operations, do regular planning */
627 List *group_pathkeys;
628 AttrNumber *groupColIdx = NULL;
629 bool need_tlist_eval = true;
631 double sub_tuple_fraction;
634 double dNumGroups = 0;
637 int numGroupCols = list_length(parse->groupClause);
638 bool use_hashed_grouping = false;
640 /* Preprocess targetlist in case we are inside an INSERT/UPDATE. */
641 tlist = preprocess_targetlist(tlist,
643 parse->resultRelation,
647 * Add TID targets for rels selected FOR UPDATE (should this be
648 * done in preprocess_targetlist?). The executor uses the TID to
649 * know which rows to lock, much as for UPDATE or DELETE.
656 * We've got trouble if the FOR UPDATE appears inside
657 * grouping, since grouping renders a reference to individual
658 * tuple CTIDs invalid. This is also checked at parse time,
659 * but that's insufficient because of rule substitution, query
662 CheckSelectForUpdate(parse);
665 * Currently the executor only supports FOR UPDATE at top
668 if (PlannerQueryLevel > 1)
670 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
671 errmsg("SELECT FOR UPDATE is not allowed in subqueries")));
673 foreach(l, parse->rowMarks)
675 Index rti = lfirst_int(l);
681 resname = (char *) palloc(32);
682 snprintf(resname, 32, "ctid%u", rti);
683 resdom = makeResdom(list_length(tlist) + 1,
690 SelfItemPointerAttributeNumber,
695 ctid = makeTargetEntry(resdom, (Expr *) var);
696 tlist = lappend(tlist, ctid);
701 * Generate appropriate target list for subplan; may be different
702 * from tlist if grouping or aggregation is needed.
704 sub_tlist = make_subplanTargetList(parse, tlist,
705 &groupColIdx, &need_tlist_eval);
708 * Calculate pathkeys that represent grouping/ordering
711 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
713 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
717 * Will need actual number of aggregates for estimating costs.
719 * Note: we do not attempt to detect duplicate aggregates here; a
720 * somewhat-overestimated count is okay for our present purposes.
722 * Note: think not that we can turn off hasAggs if we find no aggs.
723 * It is possible for constant-expression simplification to remove
724 * all explicit references to aggs, but we still have to follow the
725 * aggregate semantics (eg, producing only one output row).
728 numAggs = count_agg_clause((Node *) tlist) +
729 count_agg_clause(parse->havingQual);
732 * Figure out whether we need a sorted result from query_planner.
734 * If we have a GROUP BY clause, then we want a result sorted
735 * properly for grouping. Otherwise, if there is an ORDER BY
736 * clause, we want to sort by the ORDER BY clause. (Note: if we
737 * have both, and ORDER BY is a superset of GROUP BY, it would be
738 * tempting to request sort by ORDER BY --- but that might just
739 * leave us failing to exploit an available sort order at all.
740 * Needs more thought...)
742 if (parse->groupClause)
743 parse->query_pathkeys = group_pathkeys;
744 else if (parse->sortClause)
745 parse->query_pathkeys = sort_pathkeys;
747 parse->query_pathkeys = NIL;
750 * Adjust tuple_fraction if we see that we are going to apply
751 * limiting/grouping/aggregation/etc. This is not overridable by
752 * the caller, since it reflects plan actions that this routine
753 * will certainly take, not assumptions about context.
755 if (parse->limitCount != NULL)
758 * A LIMIT clause limits the absolute number of tuples
759 * returned. However, if it's not a constant LIMIT then we
760 * have to punt; for lack of a better idea, assume 10% of the
761 * plan's result is wanted.
763 double limit_fraction = 0.0;
765 if (IsA(parse->limitCount, Const))
767 Const *limitc = (Const *) parse->limitCount;
768 int32 count = DatumGetInt32(limitc->constvalue);
771 * A NULL-constant LIMIT represents "LIMIT ALL", which we
772 * treat the same as no limit (ie, expect to retrieve all
775 if (!limitc->constisnull && count > 0)
777 limit_fraction = (double) count;
778 /* We must also consider the OFFSET, if present */
779 if (parse->limitOffset != NULL)
781 if (IsA(parse->limitOffset, Const))
785 limitc = (Const *) parse->limitOffset;
786 offset = DatumGetInt32(limitc->constvalue);
787 if (!limitc->constisnull && offset > 0)
788 limit_fraction += (double) offset;
792 /* OFFSET is an expression ... punt ... */
793 limit_fraction = 0.10;
800 /* LIMIT is an expression ... punt ... */
801 limit_fraction = 0.10;
804 if (limit_fraction > 0.0)
807 * If we have absolute limits from both caller and LIMIT,
808 * use the smaller value; if one is fractional and the
809 * other absolute, treat the fraction as a fraction of the
810 * absolute value; else we can multiply the two fractions
813 if (tuple_fraction >= 1.0)
815 if (limit_fraction >= 1.0)
818 tuple_fraction = Min(tuple_fraction, limit_fraction);
822 /* caller absolute, limit fractional */
823 tuple_fraction *= limit_fraction;
824 if (tuple_fraction < 1.0)
825 tuple_fraction = 1.0;
828 else if (tuple_fraction > 0.0)
830 if (limit_fraction >= 1.0)
832 /* caller fractional, limit absolute */
833 tuple_fraction *= limit_fraction;
834 if (tuple_fraction < 1.0)
835 tuple_fraction = 1.0;
839 /* both fractional */
840 tuple_fraction *= limit_fraction;
845 /* no info from caller, just use limit */
846 tuple_fraction = limit_fraction;
852 * With grouping or aggregation, the tuple fraction to pass to
853 * query_planner() may be different from what it is at top level.
855 sub_tuple_fraction = tuple_fraction;
857 if (parse->groupClause)
860 * In GROUP BY mode, we have the little problem that we don't
861 * really know how many input tuples will be needed to make a
862 * group, so we can't translate an output LIMIT count into an
863 * input count. For lack of a better idea, assume 25% of the
864 * input data will be processed if there is any output limit.
865 * However, if the caller gave us a fraction rather than an
866 * absolute count, we can keep using that fraction (which
867 * amounts to assuming that all the groups are about the same
870 if (sub_tuple_fraction >= 1.0)
871 sub_tuple_fraction = 0.25;
874 * If both GROUP BY and ORDER BY are specified, we will need
875 * two levels of sort --- and, therefore, certainly need to
876 * read all the input tuples --- unless ORDER BY is a subset
877 * of GROUP BY. (We have not yet canonicalized the pathkeys,
878 * so must use the slower noncanonical comparison method.)
880 if (parse->groupClause && parse->sortClause &&
881 !noncanonical_pathkeys_contained_in(sort_pathkeys,
883 sub_tuple_fraction = 0.0;
885 else if (parse->hasAggs)
888 * Ungrouped aggregate will certainly want all the input
891 sub_tuple_fraction = 0.0;
893 else if (parse->distinctClause)
896 * SELECT DISTINCT, like GROUP, will absorb an unpredictable
897 * number of input tuples per output tuple. Handle the same
900 if (sub_tuple_fraction >= 1.0)
901 sub_tuple_fraction = 0.25;
905 * Generate the best unsorted and presorted paths for this Query
906 * (but note there may not be any presorted path).
908 query_planner(parse, sub_tlist, sub_tuple_fraction,
909 &cheapest_path, &sorted_path);
912 * We couldn't canonicalize group_pathkeys and sort_pathkeys
913 * before running query_planner(), so do it now.
915 group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
916 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
919 * Consider whether we might want to use hashed grouping.
921 if (parse->groupClause)
924 double cheapest_path_rows;
925 int cheapest_path_width;
928 * Beware in this section of the possibility that
929 * cheapest_path->parent is NULL. This could happen if user
930 * does something silly like SELECT 'foo' GROUP BY 1;
932 if (cheapest_path->parent)
934 cheapest_path_rows = cheapest_path->parent->rows;
935 cheapest_path_width = cheapest_path->parent->width;
939 cheapest_path_rows = 1; /* assume non-set result */
940 cheapest_path_width = 100; /* arbitrary */
944 * Always estimate the number of groups. We can't do this
945 * until after running query_planner(), either.
947 groupExprs = get_sortgrouplist_exprs(parse->groupClause,
949 dNumGroups = estimate_num_groups(parse,
952 /* Also want it as a long int --- but 'ware overflow! */
953 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
956 * Check can't-do-it conditions, including whether the
957 * grouping operators are hashjoinable.
959 * Executor doesn't support hashed aggregation with DISTINCT
960 * aggregates. (Doing so would imply storing *all* the input
961 * values in the hash table, which seems like a certain
964 if (!enable_hashagg || !hash_safe_grouping(parse))
965 use_hashed_grouping = false;
966 else if (parse->hasAggs &&
967 (contain_distinct_agg_clause((Node *) tlist) ||
968 contain_distinct_agg_clause(parse->havingQual)))
969 use_hashed_grouping = false;
973 * Use hashed grouping if (a) we think we can fit the
974 * hashtable into work_mem, *and* (b) the estimated cost is
975 * no more than doing it the other way. While avoiding
976 * the need for sorted input is usually a win, the fact
977 * that the output won't be sorted may be a loss; so we
978 * need to do an actual cost comparison.
980 * In most cases we have no good way to estimate the size of
981 * the transition value needed by an aggregate;
982 * arbitrarily assume it is 100 bytes. Also set the
983 * overhead per hashtable entry at 64 bytes.
985 int hashentrysize = cheapest_path_width + 64 + numAggs * 100;
987 if (hashentrysize * dNumGroups <= work_mem * 1024L)
990 * Okay, do the cost comparison. We need to consider
991 * cheapest_path + hashagg [+ final sort] versus
992 * either cheapest_path [+ sort] + group or agg [+
993 * final sort] or presorted_path + group or agg [+
994 * final sort] where brackets indicate a step that may
995 * not be needed. We assume query_planner() will have
996 * returned a presorted path only if it's a winner
997 * compared to cheapest_path for this purpose.
999 * These path variables are dummies that just hold cost
1000 * fields; we don't make actual Paths for these steps.
1005 cost_agg(&hashed_p, parse,
1006 AGG_HASHED, numAggs,
1007 numGroupCols, dNumGroups,
1008 cheapest_path->startup_cost,
1009 cheapest_path->total_cost,
1010 cheapest_path_rows);
1011 /* Result of hashed agg is always unsorted */
1013 cost_sort(&hashed_p, parse, sort_pathkeys,
1014 hashed_p.total_cost,
1016 cheapest_path_width);
1020 sorted_p.startup_cost = sorted_path->startup_cost;
1021 sorted_p.total_cost = sorted_path->total_cost;
1022 current_pathkeys = sorted_path->pathkeys;
1026 sorted_p.startup_cost = cheapest_path->startup_cost;
1027 sorted_p.total_cost = cheapest_path->total_cost;
1028 current_pathkeys = cheapest_path->pathkeys;
1030 if (!pathkeys_contained_in(group_pathkeys,
1033 cost_sort(&sorted_p, parse, group_pathkeys,
1034 sorted_p.total_cost,
1036 cheapest_path_width);
1037 current_pathkeys = group_pathkeys;
1040 cost_agg(&sorted_p, parse,
1041 AGG_SORTED, numAggs,
1042 numGroupCols, dNumGroups,
1043 sorted_p.startup_cost,
1044 sorted_p.total_cost,
1045 cheapest_path_rows);
1047 cost_group(&sorted_p, parse,
1048 numGroupCols, dNumGroups,
1049 sorted_p.startup_cost,
1050 sorted_p.total_cost,
1051 cheapest_path_rows);
1052 /* The Agg or Group node will preserve ordering */
1053 if (sort_pathkeys &&
1054 !pathkeys_contained_in(sort_pathkeys,
1057 cost_sort(&sorted_p, parse, sort_pathkeys,
1058 sorted_p.total_cost,
1060 cheapest_path_width);
1064 * Now make the decision using the top-level tuple
1065 * fraction. First we have to convert an absolute
1066 * count (LIMIT) into fractional form.
1068 if (tuple_fraction >= 1.0)
1069 tuple_fraction /= dNumGroups;
1071 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1072 tuple_fraction) < 0)
1074 /* Hashed is cheaper, so use it */
1075 use_hashed_grouping = true;
1082 * Select the best path and create a plan to execute it.
1084 * If we are doing hashed grouping, we will always read all the input
1085 * tuples, so use the cheapest-total path. Otherwise, trust
1086 * query_planner's decision about which to use.
1088 if (sorted_path && !use_hashed_grouping)
1090 result_plan = create_plan(parse, sorted_path);
1091 current_pathkeys = sorted_path->pathkeys;
1095 result_plan = create_plan(parse, cheapest_path);
1096 current_pathkeys = cheapest_path->pathkeys;
1100 * create_plan() returns a plan with just a "flat" tlist of
1101 * required Vars. Usually we need to insert the sub_tlist as the
1102 * tlist of the top plan node. However, we can skip that if we
1103 * determined that whatever query_planner chose to return will be
1106 if (need_tlist_eval)
1109 * If the top-level plan node is one that cannot do expression
1110 * evaluation, we must insert a Result node to project the
1113 if (!is_projection_capable_plan(result_plan))
1115 result_plan = (Plan *) make_result(sub_tlist, NULL,
1121 * Otherwise, just replace the subplan's flat tlist with
1122 * the desired tlist.
1124 result_plan->targetlist = sub_tlist;
1128 * Also, account for the cost of evaluation of the sub_tlist.
1130 * Up to now, we have only been dealing with "flat" tlists,
1131 * containing just Vars. So their evaluation cost is zero
1132 * according to the model used by cost_qual_eval() (or if you
1133 * prefer, the cost is factored into cpu_tuple_cost). Thus we
1134 * can avoid accounting for tlist cost throughout
1135 * query_planner() and subroutines. But now we've inserted a
1136 * tlist that might contain actual operators, sub-selects, etc
1137 * --- so we'd better account for its cost.
1139 * Below this point, any tlist eval cost for added-on nodes
1140 * should be accounted for as we create those nodes.
1141 * Presently, of the node types we can add on, only Agg and
1142 * Group project new tlists (the rest just copy their input
1143 * tuples) --- so make_agg() and make_group() are responsible
1144 * for computing the added cost.
1146 cost_qual_eval(&tlist_cost, sub_tlist);
1147 result_plan->startup_cost += tlist_cost.startup;
1148 result_plan->total_cost += tlist_cost.startup +
1149 tlist_cost.per_tuple * result_plan->plan_rows;
1154 * Since we're using query_planner's tlist and not the one
1155 * make_subplanTargetList calculated, we have to refigure any
1156 * grouping-column indexes make_subplanTargetList computed.
1158 locate_grouping_columns(parse, tlist, result_plan->targetlist,
1163 * Insert AGG or GROUP node if needed, plus an explicit sort step
1166 * HAVING clause, if any, becomes qual of the Agg node
1168 if (use_hashed_grouping)
1170 /* Hashed aggregate plan --- no sort needed */
1171 result_plan = (Plan *) make_agg(parse,
1173 (List *) parse->havingQual,
1180 /* Hashed aggregation produces randomly-ordered results */
1181 current_pathkeys = NIL;
1183 else if (parse->hasAggs)
1185 /* Plain aggregate plan --- sort if needed */
1186 AggStrategy aggstrategy;
1188 if (parse->groupClause)
1190 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1192 result_plan = (Plan *)
1193 make_sort_from_groupcols(parse,
1197 current_pathkeys = group_pathkeys;
1199 aggstrategy = AGG_SORTED;
1202 * The AGG node will not change the sort ordering of its
1203 * groups, so current_pathkeys describes the result too.
1208 aggstrategy = AGG_PLAIN;
1209 /* Result will be only one row anyway; no sort order */
1210 current_pathkeys = NIL;
1213 result_plan = (Plan *) make_agg(parse,
1215 (List *) parse->havingQual,
1226 * If there are no Aggs, we shouldn't have any HAVING qual
1229 Assert(parse->havingQual == NULL);
1232 * If we have a GROUP BY clause, insert a group node (plus the
1233 * appropriate sort node, if necessary).
1235 if (parse->groupClause)
1238 * Add an explicit sort if we couldn't make the path come
1239 * out the way the GROUP node needs it.
1241 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1243 result_plan = (Plan *)
1244 make_sort_from_groupcols(parse,
1248 current_pathkeys = group_pathkeys;
1251 result_plan = (Plan *) make_group(parse,
1257 /* The Group node won't change sort ordering */
1260 } /* end of if (setOperations) */
1263 * If we were not able to make the plan come out in the right order,
1264 * add an explicit sort step.
1266 if (parse->sortClause)
1268 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1270 result_plan = (Plan *)
1271 make_sort_from_sortclauses(parse,
1274 current_pathkeys = sort_pathkeys;
1279 * If there is a DISTINCT clause, add the UNIQUE node.
1281 if (parse->distinctClause)
1283 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1286 * If there was grouping or aggregation, leave plan_rows as-is
1287 * (ie, assume the result was already mostly unique). If not,
1288 * it's reasonable to assume the UNIQUE filter has effects
1289 * comparable to GROUP BY.
1291 if (!parse->groupClause && !parse->hasAggs)
1293 List *distinctExprs;
1295 distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
1297 result_plan->plan_rows = estimate_num_groups(parse,
1299 result_plan->plan_rows);
1304 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1306 if (parse->limitOffset || parse->limitCount)
1308 result_plan = (Plan *) make_limit(result_plan,
1314 * Return the actual output ordering in query_pathkeys for possible
1315 * use by an outer query level.
1317 parse->query_pathkeys = current_pathkeys;
1323 * hash_safe_grouping - are grouping operators hashable?
1325 * We assume hashed aggregation will work if the datatype's equality operator
1326 * is marked hashjoinable.
1329 hash_safe_grouping(Query *parse)
1333 foreach(gl, parse->groupClause)
1335 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1336 TargetEntry *tle = get_sortgroupclause_tle(grpcl, parse->targetList);
1340 optup = equality_oper(tle->resdom->restype, true);
1343 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1344 ReleaseSysCache(optup);
1352 * make_subplanTargetList
1353 * Generate appropriate target list when grouping is required.
1355 * When grouping_planner inserts Aggregate or Group plan nodes above
1356 * the result of query_planner, we typically want to pass a different
1357 * target list to query_planner than the outer plan nodes should have.
1358 * This routine generates the correct target list for the subplan.
1360 * The initial target list passed from the parser already contains entries
1361 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1362 * for variables used only in HAVING clauses; so we need to add those
1363 * variables to the subplan target list. Also, if we are doing either
1364 * grouping or aggregation, we flatten all expressions except GROUP BY items
1365 * into their component variables; the other expressions will be computed by
1366 * the inserted nodes rather than by the subplan. For example,
1367 * given a query like
1368 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1369 * we want to pass this targetlist to the subplan:
1371 * where the a+b target will be used by the Sort/Group steps, and the
1372 * other targets will be used for computing the final results. (In the
1373 * above example we could theoretically suppress the a and b targets and
1374 * pass down only c,d,a+b, but it's not really worth the trouble to
1375 * eliminate simple var references from the subplan. We will avoid doing
1376 * the extra computation to recompute a+b at the outer level; see
1377 * replace_vars_with_subplan_refs() in setrefs.c.)
1379 * If we are grouping or aggregating, *and* there are no non-Var grouping
1380 * expressions, then the returned tlist is effectively dummy; we do not
1381 * need to force it to be evaluated, because all the Vars it contains
1382 * should be present in the output of query_planner anyway.
1384 * 'parse' is the query being processed.
1385 * 'tlist' is the query's target list.
1386 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1387 * expressions (if there are any) in the subplan's target list.
1388 * 'need_tlist_eval' is set true if we really need to evaluate the
1391 * The result is the targetlist to be passed to the subplan.
1395 make_subplanTargetList(Query *parse,
1397 AttrNumber **groupColIdx,
1398 bool *need_tlist_eval)
1404 *groupColIdx = NULL;
1407 * If we're not grouping or aggregating, nothing to do here;
1408 * query_planner should receive the unmodified target list.
1410 if (!parse->hasAggs && !parse->groupClause)
1412 *need_tlist_eval = true;
1417 * Otherwise, start with a "flattened" tlist (having just the vars
1418 * mentioned in the targetlist and HAVING qual --- but not upper-
1419 * level Vars; they will be replaced by Params later on).
1421 sub_tlist = flatten_tlist(tlist);
1422 extravars = pull_var_clause(parse->havingQual, false);
1423 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1424 list_free(extravars);
1425 *need_tlist_eval = false; /* only eval if not flat tlist */
1428 * If grouping, create sub_tlist entries for all GROUP BY expressions
1429 * (GROUP BY items that are simple Vars should be in the list
1430 * already), and make an array showing where the group columns are in
1433 numCols = list_length(parse->groupClause);
1437 AttrNumber *grpColIdx;
1440 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1441 *groupColIdx = grpColIdx;
1443 foreach(gl, parse->groupClause)
1445 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1446 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1447 TargetEntry *te = NULL;
1450 /* Find or make a matching sub_tlist entry */
1451 foreach(sl, sub_tlist)
1453 te = (TargetEntry *) lfirst(sl);
1454 if (equal(groupexpr, te->expr))
1459 te = makeTargetEntry(makeResdom(list_length(sub_tlist) + 1,
1460 exprType(groupexpr),
1461 exprTypmod(groupexpr),
1464 (Expr *) groupexpr);
1465 sub_tlist = lappend(sub_tlist, te);
1466 *need_tlist_eval = true; /* it's not flat anymore */
1469 /* and save its resno */
1470 grpColIdx[keyno++] = te->resdom->resno;
1478 * locate_grouping_columns
1479 * Locate grouping columns in the tlist chosen by query_planner.
1481 * This is only needed if we don't use the sub_tlist chosen by
1482 * make_subplanTargetList. We have to forget the column indexes found
1483 * by that routine and re-locate the grouping vars in the real sub_tlist.
1486 locate_grouping_columns(Query *parse,
1489 AttrNumber *groupColIdx)
1495 * No work unless grouping.
1497 if (!parse->groupClause)
1499 Assert(groupColIdx == NULL);
1502 Assert(groupColIdx != NULL);
1504 foreach(gl, parse->groupClause)
1506 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1507 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1508 TargetEntry *te = NULL;
1511 foreach(sl, sub_tlist)
1513 te = (TargetEntry *) lfirst(sl);
1514 if (equal(groupexpr, te->expr))
1518 elog(ERROR, "failed to locate grouping columns");
1520 groupColIdx[keyno++] = te->resdom->resno;
1525 * postprocess_setop_tlist
1526 * Fix up targetlist returned by plan_set_operations().
1528 * We need to transpose sort key info from the orig_tlist into new_tlist.
1529 * NOTE: this would not be good enough if we supported resjunk sort keys
1530 * for results of set operations --- then, we'd need to project a whole
1531 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1532 * find any resjunk columns in orig_tlist.
1535 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1538 ListCell *orig_tlist_item = list_head(orig_tlist);
1540 foreach(l, new_tlist)
1542 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1543 TargetEntry *orig_tle;
1545 /* ignore resjunk columns in setop result */
1546 if (new_tle->resdom->resjunk)
1549 Assert(orig_tlist_item != NULL);
1550 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1551 orig_tlist_item = lnext(orig_tlist_item);
1552 if (orig_tle->resdom->resjunk) /* should not happen */
1553 elog(ERROR, "resjunk output columns are not implemented");
1554 Assert(new_tle->resdom->resno == orig_tle->resdom->resno);
1555 Assert(new_tle->resdom->restype == orig_tle->resdom->restype);
1556 new_tle->resdom->ressortgroupref = orig_tle->resdom->ressortgroupref;
1558 if (orig_tlist_item != NULL)
1559 elog(ERROR, "resjunk output columns are not implemented");