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.188 2005/06/05 22:32:56 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(PlannerInfo *root, Node *expr, int kind);
58 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
59 static Plan *inheritance_planner(PlannerInfo *root, List *inheritlist);
60 static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
61 static bool choose_hashed_grouping(PlannerInfo *root, 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(PlannerInfo *root);
66 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
67 AttrNumber **groupColIdx, bool *need_tlist_eval);
68 static void locate_grouping_columns(PlannerInfo *root,
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 per-query
96 * PlannerInfo structure since their whole purpose is communication
97 * across multiple sub-queries. Also, boundParams is explicitly info
98 * from 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, NULL);
135 /* check we popped out the right number of levels */
136 Assert(PlannerQueryLevel == 0);
139 * If creating a plan for a scrollable cursor, make sure it can run
140 * backwards on demand. Add a Material node at the top at need.
142 if (isCursor && (cursorOptions & CURSOR_OPT_SCROLL))
144 if (!ExecSupportsBackwardScan(result_plan))
145 result_plan = materialize_finished_plan(result_plan);
148 /* final cleanup of the plan */
149 result_plan = set_plan_references(result_plan, parse->rtable);
151 /* executor wants to know total number of Params used overall */
152 result_plan->nParamExec = list_length(PlannerParamList);
154 /* restore state for outer planner, if any */
155 PlannerQueryLevel = save_PlannerQueryLevel;
156 PlannerParamList = save_PlannerParamList;
157 PlannerBoundParamList = save_PlannerBoundParamList;
163 /*--------------------
165 * Invokes the planner on a subquery. We recurse to here for each
166 * sub-SELECT found in the query tree.
168 * parse is the querytree produced by the parser & rewriter.
169 * tuple_fraction is the fraction of tuples we expect will be retrieved.
170 * tuple_fraction is interpreted as explained for grouping_planner, below.
172 * If subquery_pathkeys isn't NULL, it receives a list of pathkeys indicating
173 * the output sort ordering of the completed plan.
175 * Basically, this routine does the stuff that should only be done once
176 * per Query object. It then calls grouping_planner. At one time,
177 * grouping_planner could be invoked recursively on the same Query object;
178 * that's not currently true, but we keep the separation between the two
179 * routines anyway, in case we need it again someday.
181 * subquery_planner will be called recursively to handle sub-Query nodes
182 * found within the query's expressions and rangetable.
184 * Returns a query plan.
185 *--------------------
188 subquery_planner(Query *parse, double tuple_fraction,
189 List **subquery_pathkeys)
191 List *saved_initplan = PlannerInitPlan;
192 int saved_planid = PlannerPlanId;
200 /* Set up for a new level of subquery */
202 PlannerInitPlan = NIL;
204 /* Create a PlannerInfo data structure for this subquery */
205 root = makeNode(PlannerInfo);
209 * Look for IN clauses at the top level of WHERE, and transform them
210 * into joins. Note that this step only handles IN clauses originally
211 * at top level of WHERE; if we pull up any subqueries in the next
212 * step, their INs are processed just before pulling them up.
214 root->in_info_list = NIL;
215 if (parse->hasSubLinks)
216 parse->jointree->quals = pull_up_IN_clauses(root,
217 parse->jointree->quals);
220 * Check to see if any subqueries in the rangetable can be merged into
223 parse->jointree = (FromExpr *)
224 pull_up_subqueries(root, (Node *) parse->jointree, false);
227 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we
228 * can avoid the expense of doing flatten_join_alias_vars(). Also
229 * check for outer joins --- if none, we can skip
230 * reduce_outer_joins(). This must be done after we have done
231 * pull_up_subqueries, of course.
233 root->hasJoinRTEs = false;
234 hasOuterJoins = false;
235 foreach(l, parse->rtable)
237 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
239 if (rte->rtekind == RTE_JOIN)
241 root->hasJoinRTEs = true;
242 if (IS_OUTER_JOIN(rte->jointype))
244 hasOuterJoins = true;
245 /* Can quit scanning once we find an outer join */
252 * Set hasHavingQual to remember if HAVING clause is present. Needed
253 * because preprocess_expression will reduce a constant-true condition
254 * to an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
256 root->hasHavingQual = (parse->havingQual != NULL);
259 * Do expression preprocessing on targetlist and quals.
261 parse->targetList = (List *)
262 preprocess_expression(root, (Node *) parse->targetList,
265 preprocess_qual_conditions(root, (Node *) parse->jointree);
267 parse->havingQual = preprocess_expression(root, parse->havingQual,
270 parse->limitOffset = preprocess_expression(root, parse->limitOffset,
272 parse->limitCount = preprocess_expression(root, parse->limitCount,
275 root->in_info_list = (List *)
276 preprocess_expression(root, (Node *) root->in_info_list,
279 /* Also need to preprocess expressions for function RTEs */
280 foreach(l, parse->rtable)
282 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
284 if (rte->rtekind == RTE_FUNCTION)
285 rte->funcexpr = preprocess_expression(root, rte->funcexpr,
290 * In some cases we may want to transfer a HAVING clause into WHERE.
291 * We cannot do so if the HAVING clause contains aggregates (obviously)
292 * or volatile functions (since a HAVING clause is supposed to be executed
293 * only once per group). Also, it may be that the clause is so expensive
294 * to execute that we're better off doing it only once per group, despite
295 * the loss of selectivity. This is hard to estimate short of doing the
296 * entire planning process twice, so we use a heuristic: clauses
297 * containing subplans are left in HAVING. Otherwise, we move or copy
298 * the HAVING clause into WHERE, in hopes of eliminating tuples before
299 * aggregation instead of after.
301 * If the query has explicit grouping then we can simply move such a
302 * clause into WHERE; any group that fails the clause will not be
303 * in the output because none of its tuples will reach the grouping
304 * or aggregation stage. Otherwise we must have a degenerate
305 * (variable-free) HAVING clause, which we put in WHERE so that
306 * query_planner() can use it in a gating Result node, but also keep
307 * in HAVING to ensure that we don't emit a bogus aggregated row.
308 * (This could be done better, but it seems not worth optimizing.)
310 * Note that both havingQual and parse->jointree->quals are in
311 * implicitly-ANDed-list form at this point, even though they are
312 * declared as Node *.
315 foreach(l, (List *) parse->havingQual)
317 Node *havingclause = (Node *) lfirst(l);
319 if (contain_agg_clause(havingclause) ||
320 contain_volatile_functions(havingclause) ||
321 contain_subplans(havingclause))
323 /* keep it in HAVING */
324 newHaving = lappend(newHaving, havingclause);
326 else if (parse->groupClause)
328 /* move it to WHERE */
329 parse->jointree->quals = (Node *)
330 lappend((List *) parse->jointree->quals, havingclause);
334 /* put a copy in WHERE, keep it in HAVING */
335 parse->jointree->quals = (Node *)
336 lappend((List *) parse->jointree->quals,
337 copyObject(havingclause));
338 newHaving = lappend(newHaving, havingclause);
341 parse->havingQual = (Node *) newHaving;
344 * If we have any outer joins, try to reduce them to plain inner
345 * joins. This step is most easily done after we've done expression
349 reduce_outer_joins(root);
352 * See if we can simplify the jointree; opportunities for this may
353 * come from having pulled up subqueries, or from flattening explicit
354 * JOIN syntax. We must do this after flattening JOIN alias
355 * variables, since eliminating explicit JOIN nodes from the jointree
356 * will cause get_relids_for_join() to fail. But it should happen
357 * after reduce_outer_joins, anyway.
359 parse->jointree = (FromExpr *)
360 simplify_jointree(root, (Node *) parse->jointree);
363 * Do the main planning. If we have an inherited target relation,
364 * that needs special processing, else go straight to
367 if (parse->resultRelation &&
368 (lst = expand_inherited_rtentry(root, parse->resultRelation)) != NIL)
369 plan = inheritance_planner(root, lst);
371 plan = grouping_planner(root, tuple_fraction);
374 * If any subplans were generated, or if we're inside a subplan, build
375 * initPlan list and extParam/allParam sets for plan nodes, and attach
376 * the initPlans to the top plan node.
378 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
379 SS_finalize_plan(plan, parse->rtable);
381 /* Return sort ordering info if caller wants it */
382 if (subquery_pathkeys)
383 *subquery_pathkeys = root->query_pathkeys;
385 /* Return to outer subquery context */
387 PlannerInitPlan = saved_initplan;
388 /* we do NOT restore PlannerPlanId; that's not an oversight! */
394 * preprocess_expression
395 * Do subquery_planner's preprocessing work for an expression,
396 * which can be a targetlist, a WHERE clause (including JOIN/ON
397 * conditions), or a HAVING clause.
400 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
403 * Fall out quickly if expression is empty. This occurs often enough
404 * to be worth checking. Note that null->null is the correct conversion
405 * for implicit-AND result format, too.
411 * If the query has any join RTEs, replace join alias variables with
412 * base-relation variables. We must do this before sublink processing,
413 * else sublinks expanded out from join aliases wouldn't get
416 if (root->hasJoinRTEs)
417 expr = flatten_join_alias_vars(root, expr);
420 * Simplify constant expressions.
422 * Note: this also flattens nested AND and OR expressions into N-argument
423 * form. All processing of a qual expression after this point must be
424 * careful to maintain AND/OR flatness --- that is, do not generate a tree
425 * with AND directly under AND, nor OR directly under OR.
427 * Because this is a relatively expensive process, we skip it when the
428 * query is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()".
429 * The expression will only be evaluated once anyway, so no point in
430 * pre-simplifying; we can't execute it any faster than the executor can,
431 * and we will waste cycles copying the tree. Notice however that we
432 * still must do it for quals (to get AND/OR flatness); and if we are
433 * in a subquery we should not assume it will be done only once.
435 if (root->parse->jointree->fromlist != NIL ||
436 kind == EXPRKIND_QUAL ||
437 PlannerQueryLevel > 1)
438 expr = eval_const_expressions(expr);
441 * If it's a qual or havingQual, canonicalize it.
443 if (kind == EXPRKIND_QUAL)
445 expr = (Node *) canonicalize_qual((Expr *) expr);
447 #ifdef OPTIMIZER_DEBUG
448 printf("After canonicalize_qual()\n");
453 /* Expand SubLinks to SubPlans */
454 if (root->parse->hasSubLinks)
455 expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL));
458 * XXX do not insert anything here unless you have grokked the
459 * comments in SS_replace_correlation_vars ...
462 /* Replace uplevel vars with Param nodes */
463 if (PlannerQueryLevel > 1)
464 expr = SS_replace_correlation_vars(expr);
467 * If it's a qual or havingQual, convert it to implicit-AND format.
468 * (We don't want to do this before eval_const_expressions, since the
469 * latter would be unable to simplify a top-level AND correctly. Also,
470 * SS_process_sublinks expects explicit-AND format.)
472 if (kind == EXPRKIND_QUAL)
473 expr = (Node *) make_ands_implicit((Expr *) expr);
479 * preprocess_qual_conditions
480 * Recursively scan the query's jointree and do subquery_planner's
481 * preprocessing work on each qual condition found therein.
484 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
488 if (IsA(jtnode, RangeTblRef))
490 /* nothing to do here */
492 else if (IsA(jtnode, FromExpr))
494 FromExpr *f = (FromExpr *) jtnode;
497 foreach(l, f->fromlist)
498 preprocess_qual_conditions(root, lfirst(l));
500 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
502 else if (IsA(jtnode, JoinExpr))
504 JoinExpr *j = (JoinExpr *) jtnode;
506 preprocess_qual_conditions(root, j->larg);
507 preprocess_qual_conditions(root, j->rarg);
509 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
512 elog(ERROR, "unrecognized node type: %d",
513 (int) nodeTag(jtnode));
516 /*--------------------
517 * inheritance_planner
518 * Generate a plan in the case where the result relation is an
521 * We have to handle this case differently from cases where a source
522 * relation is an inheritance set. Source inheritance is expanded at
523 * the bottom of the plan tree (see allpaths.c), but target inheritance
524 * has to be expanded at the top. The reason is that for UPDATE, each
525 * target relation needs a different targetlist matching its own column
526 * set. (This is not so critical for DELETE, but for simplicity we treat
527 * inherited DELETE the same way.) Fortunately, the UPDATE/DELETE target
528 * can never be the nullable side of an outer join, so it's OK to generate
531 * inheritlist is an integer list of RT indexes for the result relation set.
533 * Returns a query plan.
534 *--------------------
537 inheritance_planner(PlannerInfo *root, List *inheritlist)
539 Query *parse = root->parse;
540 int parentRTindex = parse->resultRelation;
541 Oid parentOID = getrelid(parentRTindex, parse->rtable);
542 int mainrtlength = list_length(parse->rtable);
543 List *subplans = NIL;
547 foreach(l, inheritlist)
549 int childRTindex = lfirst_int(l);
550 Oid childOID = getrelid(childRTindex, parse->rtable);
555 * Generate modified query with this rel as target. We have to
556 * be prepared to translate varnos in in_info_list as well as in
559 memcpy(&subroot, root, sizeof(PlannerInfo));
560 subroot.parse = (Query *)
561 adjust_inherited_attrs((Node *) parse,
562 parentRTindex, parentOID,
563 childRTindex, childOID);
564 subroot.in_info_list = (List *)
565 adjust_inherited_attrs((Node *) root->in_info_list,
566 parentRTindex, parentOID,
567 childRTindex, childOID);
570 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
572 subplans = lappend(subplans, subplan);
575 * XXX my goodness this next bit is ugly. Really need to think about
576 * ways to rein in planner's habit of scribbling on its input.
578 * Planning of the subquery might have modified the rangetable,
579 * either by addition of RTEs due to expansion of inherited source
580 * tables, or by changes of the Query structures inside subquery
581 * RTEs. We have to ensure that this gets propagated back to the
582 * master copy. However, if we aren't done planning yet, we also
583 * need to ensure that subsequent calls to grouping_planner have
584 * virgin sub-Queries to work from. So, if we are at the last
585 * list entry, just copy the subquery rangetable back to the master
586 * copy; if we are not, then extend the master copy by adding
587 * whatever the subquery added. (We assume these added entries
588 * will go untouched by the future grouping_planner calls. We are
589 * also effectively assuming that sub-Queries will get planned
590 * identically each time, or at least that the impacts on their
591 * rangetables will be the same each time. Did I say this is ugly?)
593 if (lnext(l) == NULL)
594 parse->rtable = subroot.parse->rtable;
597 int subrtlength = list_length(subroot.parse->rtable);
599 if (subrtlength > mainrtlength)
603 subrt = list_copy_tail(subroot.parse->rtable, mainrtlength);
604 parse->rtable = list_concat(parse->rtable, subrt);
605 mainrtlength = subrtlength;
609 /* Save preprocessed tlist from first rel for use in Append */
611 tlist = subplan->targetlist;
614 /* Save the target-relations list for the executor, too */
615 parse->resultRelations = inheritlist;
617 /* Mark result as unordered (probably unnecessary) */
618 root->query_pathkeys = NIL;
620 return (Plan *) make_append(subplans, true, tlist);
623 /*--------------------
625 * Perform planning steps related to grouping, aggregation, etc.
626 * This primarily means adding top-level processing to the basic
627 * query plan produced by query_planner.
629 * tuple_fraction is the fraction of tuples we expect will be retrieved
631 * tuple_fraction is interpreted as follows:
632 * 0: expect all tuples to be retrieved (normal case)
633 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
634 * from the plan to be retrieved
635 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
636 * expected to be retrieved (ie, a LIMIT specification)
638 * Returns a query plan. Also, root->query_pathkeys is returned as the
639 * actual output ordering of the plan (in pathkey format).
640 *--------------------
643 grouping_planner(PlannerInfo *root, double tuple_fraction)
645 Query *parse = root->parse;
646 List *tlist = parse->targetList;
648 List *current_pathkeys;
651 if (parse->setOperations)
653 List *set_sortclauses;
656 * Construct the plan for set operations. The result will not
657 * need any work except perhaps a top-level sort and/or LIMIT.
659 result_plan = plan_set_operations(root,
663 * Calculate pathkeys representing the sort order (if any) of the
664 * set operation's result. We have to do this before overwriting
665 * the sort key information...
667 current_pathkeys = make_pathkeys_for_sortclauses(set_sortclauses,
668 result_plan->targetlist);
669 current_pathkeys = canonicalize_pathkeys(root, current_pathkeys);
672 * We should not need to call preprocess_targetlist, since we must
673 * be in a SELECT query node. Instead, use the targetlist
674 * returned by plan_set_operations (since this tells whether it
675 * returned any resjunk columns!), and transfer any sort key
676 * information from the original tlist.
678 Assert(parse->commandType == CMD_SELECT);
680 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
683 * Can't handle FOR UPDATE/SHARE here (parser should have checked
684 * already, but let's make sure).
688 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
689 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
692 * Calculate pathkeys that represent result ordering requirements
694 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
696 sort_pathkeys = canonicalize_pathkeys(root, sort_pathkeys);
700 /* No set operations, do regular planning */
702 List *group_pathkeys;
703 AttrNumber *groupColIdx = NULL;
704 bool need_tlist_eval = true;
706 double sub_tuple_fraction;
710 double dNumGroups = 0;
712 AggClauseCounts agg_counts;
713 int numGroupCols = list_length(parse->groupClause);
714 bool use_hashed_grouping = false;
716 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
718 /* Preprocess targetlist */
719 tlist = preprocess_targetlist(root, tlist);
722 * Generate appropriate target list for subplan; may be different
723 * from tlist if grouping or aggregation is needed.
725 sub_tlist = make_subplanTargetList(root, tlist,
726 &groupColIdx, &need_tlist_eval);
729 * Calculate pathkeys that represent grouping/ordering
732 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
734 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
738 * Will need actual number of aggregates for estimating costs.
740 * Note: we do not attempt to detect duplicate aggregates here; a
741 * somewhat-overestimated count is okay for our present purposes.
743 * Note: think not that we can turn off hasAggs if we find no aggs.
744 * It is possible for constant-expression simplification to remove
745 * all explicit references to aggs, but we still have to follow
746 * the aggregate semantics (eg, producing only one output row).
750 count_agg_clauses((Node *) tlist, &agg_counts);
751 count_agg_clauses(parse->havingQual, &agg_counts);
755 * Figure out whether we need a sorted result from query_planner.
757 * If we have a GROUP BY clause, then we want a result sorted
758 * properly for grouping. Otherwise, if there is an ORDER BY
759 * clause, we want to sort by the ORDER BY clause. (Note: if we
760 * have both, and ORDER BY is a superset of GROUP BY, it would be
761 * tempting to request sort by ORDER BY --- but that might just
762 * leave us failing to exploit an available sort order at all.
763 * Needs more thought...)
765 if (parse->groupClause)
766 root->query_pathkeys = group_pathkeys;
767 else if (parse->sortClause)
768 root->query_pathkeys = sort_pathkeys;
770 root->query_pathkeys = NIL;
773 * Adjust tuple_fraction if we see that we are going to apply
774 * limiting/grouping/aggregation/etc. This is not overridable by
775 * the caller, since it reflects plan actions that this routine
776 * will certainly take, not assumptions about context.
778 if (parse->limitCount != NULL)
781 * A LIMIT clause limits the absolute number of tuples
782 * returned. However, if it's not a constant LIMIT then we
783 * have to punt; for lack of a better idea, assume 10% of the
784 * plan's result is wanted.
786 double limit_fraction = 0.0;
788 if (IsA(parse->limitCount, Const))
790 Const *limitc = (Const *) parse->limitCount;
791 int32 count = DatumGetInt32(limitc->constvalue);
794 * A NULL-constant LIMIT represents "LIMIT ALL", which we
795 * treat the same as no limit (ie, expect to retrieve all
798 if (!limitc->constisnull && count > 0)
800 limit_fraction = (double) count;
801 /* We must also consider the OFFSET, if present */
802 if (parse->limitOffset != NULL)
804 if (IsA(parse->limitOffset, Const))
808 limitc = (Const *) parse->limitOffset;
809 offset = DatumGetInt32(limitc->constvalue);
810 if (!limitc->constisnull && offset > 0)
811 limit_fraction += (double) offset;
815 /* OFFSET is an expression ... punt ... */
816 limit_fraction = 0.10;
823 /* LIMIT is an expression ... punt ... */
824 limit_fraction = 0.10;
827 if (limit_fraction > 0.0)
830 * If we have absolute limits from both caller and LIMIT,
831 * use the smaller value; if one is fractional and the
832 * other absolute, treat the fraction as a fraction of the
833 * absolute value; else we can multiply the two fractions
836 if (tuple_fraction >= 1.0)
838 if (limit_fraction >= 1.0)
841 tuple_fraction = Min(tuple_fraction, limit_fraction);
845 /* caller absolute, limit fractional */
846 tuple_fraction *= limit_fraction;
847 if (tuple_fraction < 1.0)
848 tuple_fraction = 1.0;
851 else if (tuple_fraction > 0.0)
853 if (limit_fraction >= 1.0)
855 /* caller fractional, limit absolute */
856 tuple_fraction *= limit_fraction;
857 if (tuple_fraction < 1.0)
858 tuple_fraction = 1.0;
862 /* both fractional */
863 tuple_fraction *= limit_fraction;
868 /* no info from caller, just use limit */
869 tuple_fraction = limit_fraction;
875 * With grouping or aggregation, the tuple fraction to pass to
876 * query_planner() may be different from what it is at top level.
878 sub_tuple_fraction = tuple_fraction;
880 if (parse->groupClause)
883 * In GROUP BY mode, we have the little problem that we don't
884 * really know how many input tuples will be needed to make a
885 * group, so we can't translate an output LIMIT count into an
886 * input count. For lack of a better idea, assume 25% of the
887 * input data will be processed if there is any output limit.
888 * However, if the caller gave us a fraction rather than an
889 * absolute count, we can keep using that fraction (which
890 * amounts to assuming that all the groups are about the same
893 if (sub_tuple_fraction >= 1.0)
894 sub_tuple_fraction = 0.25;
897 * If both GROUP BY and ORDER BY are specified, we will need
898 * two levels of sort --- and, therefore, certainly need to
899 * read all the input tuples --- unless ORDER BY is a subset
900 * of GROUP BY. (We have not yet canonicalized the pathkeys,
901 * so must use the slower noncanonical comparison method.)
903 if (parse->groupClause && parse->sortClause &&
904 !noncanonical_pathkeys_contained_in(sort_pathkeys,
906 sub_tuple_fraction = 0.0;
908 else if (parse->hasAggs)
911 * Ungrouped aggregate will certainly want all the input
914 sub_tuple_fraction = 0.0;
916 else if (parse->distinctClause)
919 * SELECT DISTINCT, like GROUP, will absorb an unpredictable
920 * number of input tuples per output tuple. Handle the same
923 if (sub_tuple_fraction >= 1.0)
924 sub_tuple_fraction = 0.25;
928 * Generate the best unsorted and presorted paths for this Query
929 * (but note there may not be any presorted path).
931 query_planner(root, sub_tlist, sub_tuple_fraction,
932 &cheapest_path, &sorted_path);
935 * We couldn't canonicalize group_pathkeys and sort_pathkeys
936 * before running query_planner(), so do it now.
938 group_pathkeys = canonicalize_pathkeys(root, group_pathkeys);
939 sort_pathkeys = canonicalize_pathkeys(root, sort_pathkeys);
942 * If grouping, estimate the number of groups. (We can't do this
943 * until after running query_planner(), either.) Then decide
944 * whether we want to use hashed grouping.
946 if (parse->groupClause)
949 double cheapest_path_rows;
952 * Beware of the possibility that cheapest_path->parent is NULL.
953 * This could happen if user does something silly like
954 * SELECT 'foo' GROUP BY 1;
956 if (cheapest_path->parent)
957 cheapest_path_rows = cheapest_path->parent->rows;
959 cheapest_path_rows = 1; /* assume non-set result */
961 groupExprs = get_sortgrouplist_exprs(parse->groupClause,
963 dNumGroups = estimate_num_groups(root,
966 /* Also want it as a long int --- but 'ware overflow! */
967 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
969 use_hashed_grouping =
970 choose_hashed_grouping(root, tuple_fraction,
971 cheapest_path, sorted_path,
972 sort_pathkeys, group_pathkeys,
973 dNumGroups, &agg_counts);
977 * Select the best path. If we are doing hashed grouping, we will
978 * always read all the input tuples, so use the cheapest-total
979 * path. Otherwise, trust query_planner's decision about which to use.
981 if (use_hashed_grouping || !sorted_path)
982 best_path = cheapest_path;
984 best_path = sorted_path;
987 * Check to see if it's possible to optimize MIN/MAX aggregates.
988 * If so, we will forget all the work we did so far to choose a
989 * "regular" path ... but we had to do it anyway to be able to
990 * tell which way is cheaper.
992 result_plan = optimize_minmax_aggregates(root,
995 if (result_plan != NULL)
998 * optimize_minmax_aggregates generated the full plan, with
999 * the right tlist, and it has no sort order.
1001 current_pathkeys = NIL;
1006 * Normal case --- create a plan according to query_planner's
1009 result_plan = create_plan(root, best_path);
1010 current_pathkeys = best_path->pathkeys;
1013 * create_plan() returns a plan with just a "flat" tlist of
1014 * required Vars. Usually we need to insert the sub_tlist as the
1015 * tlist of the top plan node. However, we can skip that if we
1016 * determined that whatever query_planner chose to return will be
1019 if (need_tlist_eval)
1022 * If the top-level plan node is one that cannot do expression
1023 * evaluation, we must insert a Result node to project the
1026 if (!is_projection_capable_plan(result_plan))
1028 result_plan = (Plan *) make_result(sub_tlist, NULL,
1034 * Otherwise, just replace the subplan's flat tlist with
1035 * the desired tlist.
1037 result_plan->targetlist = sub_tlist;
1041 * Also, account for the cost of evaluation of the sub_tlist.
1043 * Up to now, we have only been dealing with "flat" tlists,
1044 * containing just Vars. So their evaluation cost is zero
1045 * according to the model used by cost_qual_eval() (or if you
1046 * prefer, the cost is factored into cpu_tuple_cost). Thus we
1047 * can avoid accounting for tlist cost throughout
1048 * query_planner() and subroutines. But now we've inserted a
1049 * tlist that might contain actual operators, sub-selects, etc
1050 * --- so we'd better account for its cost.
1052 * Below this point, any tlist eval cost for added-on nodes
1053 * should be accounted for as we create those nodes.
1054 * Presently, of the node types we can add on, only Agg and
1055 * Group project new tlists (the rest just copy their input
1056 * tuples) --- so make_agg() and make_group() are responsible
1057 * for computing the added cost.
1059 cost_qual_eval(&tlist_cost, sub_tlist);
1060 result_plan->startup_cost += tlist_cost.startup;
1061 result_plan->total_cost += tlist_cost.startup +
1062 tlist_cost.per_tuple * result_plan->plan_rows;
1067 * Since we're using query_planner's tlist and not the one
1068 * make_subplanTargetList calculated, we have to refigure any
1069 * grouping-column indexes make_subplanTargetList computed.
1071 locate_grouping_columns(root, tlist, result_plan->targetlist,
1076 * Insert AGG or GROUP node if needed, plus an explicit sort step
1079 * HAVING clause, if any, becomes qual of the Agg or Group node.
1081 if (use_hashed_grouping)
1083 /* Hashed aggregate plan --- no sort needed */
1084 result_plan = (Plan *) make_agg(root,
1086 (List *) parse->havingQual,
1093 /* Hashed aggregation produces randomly-ordered results */
1094 current_pathkeys = NIL;
1096 else if (parse->hasAggs)
1098 /* Plain aggregate plan --- sort if needed */
1099 AggStrategy aggstrategy;
1101 if (parse->groupClause)
1103 if (!pathkeys_contained_in(group_pathkeys,
1106 result_plan = (Plan *)
1107 make_sort_from_groupcols(root,
1111 current_pathkeys = group_pathkeys;
1113 aggstrategy = AGG_SORTED;
1116 * The AGG node will not change the sort ordering of its
1117 * groups, so current_pathkeys describes the result too.
1122 aggstrategy = AGG_PLAIN;
1123 /* Result will be only one row anyway; no sort order */
1124 current_pathkeys = NIL;
1127 result_plan = (Plan *) make_agg(root,
1129 (List *) parse->havingQual,
1137 else if (parse->groupClause)
1140 * GROUP BY without aggregation, so insert a group node (plus
1141 * the appropriate sort node, if necessary).
1143 * Add an explicit sort if we couldn't make the path come
1144 * out the way the GROUP node needs it.
1146 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1148 result_plan = (Plan *)
1149 make_sort_from_groupcols(root,
1153 current_pathkeys = group_pathkeys;
1156 result_plan = (Plan *) make_group(root,
1158 (List *) parse->havingQual,
1163 /* The Group node won't change sort ordering */
1165 else if (root->hasHavingQual)
1168 * No aggregates, and no GROUP BY, but we have a HAVING qual.
1169 * This is a degenerate case in which we are supposed to emit
1170 * either 0 or 1 row depending on whether HAVING succeeds.
1171 * Furthermore, there cannot be any variables in either HAVING
1172 * or the targetlist, so we actually do not need the FROM table
1173 * at all! We can just throw away the plan-so-far and generate
1174 * a Result node. This is a sufficiently unusual corner case
1175 * that it's not worth contorting the structure of this routine
1176 * to avoid having to generate the plan in the first place.
1178 result_plan = (Plan *) make_result(tlist,
1182 } /* end of non-minmax-aggregate case */
1183 } /* end of if (setOperations) */
1186 * If we were not able to make the plan come out in the right order,
1187 * add an explicit sort step.
1189 if (parse->sortClause)
1191 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1193 result_plan = (Plan *)
1194 make_sort_from_sortclauses(root,
1197 current_pathkeys = sort_pathkeys;
1202 * If there is a DISTINCT clause, add the UNIQUE node.
1204 if (parse->distinctClause)
1206 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1209 * If there was grouping or aggregation, leave plan_rows as-is
1210 * (ie, assume the result was already mostly unique). If not,
1211 * it's reasonable to assume the UNIQUE filter has effects
1212 * comparable to GROUP BY.
1214 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1216 List *distinctExprs;
1218 distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
1220 result_plan->plan_rows = estimate_num_groups(root,
1222 result_plan->plan_rows);
1227 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1229 if (parse->limitOffset || parse->limitCount)
1231 result_plan = (Plan *) make_limit(result_plan,
1237 * Return the actual output ordering in query_pathkeys for possible
1238 * use by an outer query level.
1240 root->query_pathkeys = current_pathkeys;
1246 * choose_hashed_grouping - should we use hashed grouping?
1249 choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
1250 Path *cheapest_path, Path *sorted_path,
1251 List *sort_pathkeys, List *group_pathkeys,
1252 double dNumGroups, AggClauseCounts *agg_counts)
1254 int numGroupCols = list_length(root->parse->groupClause);
1255 double cheapest_path_rows;
1256 int cheapest_path_width;
1258 List *current_pathkeys;
1263 * Check can't-do-it conditions, including whether the grouping operators
1266 * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1267 * (Doing so would imply storing *all* the input values in the hash table,
1268 * which seems like a certain loser.)
1270 if (!enable_hashagg)
1272 if (agg_counts->numDistinctAggs != 0)
1274 if (!hash_safe_grouping(root))
1278 * Don't do it if it doesn't look like the hashtable will fit into
1281 * Beware here of the possibility that cheapest_path->parent is NULL.
1282 * This could happen if user does something silly like
1283 * SELECT 'foo' GROUP BY 1;
1285 if (cheapest_path->parent)
1287 cheapest_path_rows = cheapest_path->parent->rows;
1288 cheapest_path_width = cheapest_path->parent->width;
1292 cheapest_path_rows = 1; /* assume non-set result */
1293 cheapest_path_width = 100; /* arbitrary */
1296 /* Estimate per-hash-entry space at tuple width... */
1297 hashentrysize = cheapest_path_width;
1298 /* plus space for pass-by-ref transition values... */
1299 hashentrysize += agg_counts->transitionSpace;
1300 /* plus the per-hash-entry overhead */
1301 hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1303 if (hashentrysize * dNumGroups > work_mem * 1024L)
1307 * See if the estimated cost is no more than doing it the other way.
1308 * While avoiding the need for sorted input is usually a win, the fact
1309 * that the output won't be sorted may be a loss; so we need to do an
1310 * actual cost comparison.
1312 * We need to consider
1313 * cheapest_path + hashagg [+ final sort]
1315 * cheapest_path [+ sort] + group or agg [+ final sort]
1317 * presorted_path + group or agg [+ final sort]
1318 * where brackets indicate a step that may not be needed. We assume
1319 * query_planner() will have returned a presorted path only if it's a
1320 * winner compared to cheapest_path for this purpose.
1322 * These path variables are dummies that just hold cost fields; we don't
1323 * make actual Paths for these steps.
1325 cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1326 numGroupCols, dNumGroups,
1327 cheapest_path->startup_cost, cheapest_path->total_cost,
1328 cheapest_path_rows);
1329 /* Result of hashed agg is always unsorted */
1331 cost_sort(&hashed_p, root, sort_pathkeys, hashed_p.total_cost,
1332 dNumGroups, cheapest_path_width);
1336 sorted_p.startup_cost = sorted_path->startup_cost;
1337 sorted_p.total_cost = sorted_path->total_cost;
1338 current_pathkeys = sorted_path->pathkeys;
1342 sorted_p.startup_cost = cheapest_path->startup_cost;
1343 sorted_p.total_cost = cheapest_path->total_cost;
1344 current_pathkeys = cheapest_path->pathkeys;
1346 if (!pathkeys_contained_in(group_pathkeys,
1349 cost_sort(&sorted_p, root, group_pathkeys, sorted_p.total_cost,
1350 cheapest_path_rows, cheapest_path_width);
1351 current_pathkeys = group_pathkeys;
1354 if (root->parse->hasAggs)
1355 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1356 numGroupCols, dNumGroups,
1357 sorted_p.startup_cost, sorted_p.total_cost,
1358 cheapest_path_rows);
1360 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1361 sorted_p.startup_cost, sorted_p.total_cost,
1362 cheapest_path_rows);
1363 /* The Agg or Group node will preserve ordering */
1364 if (sort_pathkeys &&
1365 !pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1366 cost_sort(&sorted_p, root, sort_pathkeys, sorted_p.total_cost,
1367 dNumGroups, cheapest_path_width);
1370 * Now make the decision using the top-level tuple fraction. First we
1371 * have to convert an absolute count (LIMIT) into fractional form.
1373 if (tuple_fraction >= 1.0)
1374 tuple_fraction /= dNumGroups;
1376 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1377 tuple_fraction) < 0)
1379 /* Hashed is cheaper, so use it */
1386 * hash_safe_grouping - are grouping operators hashable?
1388 * We assume hashed aggregation will work if the datatype's equality operator
1389 * is marked hashjoinable.
1392 hash_safe_grouping(PlannerInfo *root)
1396 foreach(gl, root->parse->groupClause)
1398 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1399 TargetEntry *tle = get_sortgroupclause_tle(grpcl,
1400 root->parse->targetList);
1404 optup = equality_oper(exprType((Node *) tle->expr), true);
1407 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1408 ReleaseSysCache(optup);
1416 * make_subplanTargetList
1417 * Generate appropriate target list when grouping is required.
1419 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1420 * above the result of query_planner, we typically want to pass a different
1421 * target list to query_planner than the outer plan nodes should have.
1422 * This routine generates the correct target list for the subplan.
1424 * The initial target list passed from the parser already contains entries
1425 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1426 * for variables used only in HAVING clauses; so we need to add those
1427 * variables to the subplan target list. Also, we flatten all expressions
1428 * except GROUP BY items into their component variables; the other expressions
1429 * will be computed by the inserted nodes rather than by the subplan.
1430 * For example, given a query like
1431 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1432 * we want to pass this targetlist to the subplan:
1434 * where the a+b target will be used by the Sort/Group steps, and the
1435 * other targets will be used for computing the final results. (In the
1436 * above example we could theoretically suppress the a and b targets and
1437 * pass down only c,d,a+b, but it's not really worth the trouble to
1438 * eliminate simple var references from the subplan. We will avoid doing
1439 * the extra computation to recompute a+b at the outer level; see
1440 * replace_vars_with_subplan_refs() in setrefs.c.)
1442 * If we are grouping or aggregating, *and* there are no non-Var grouping
1443 * expressions, then the returned tlist is effectively dummy; we do not
1444 * need to force it to be evaluated, because all the Vars it contains
1445 * should be present in the output of query_planner anyway.
1447 * 'tlist' is the query's target list.
1448 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1449 * expressions (if there are any) in the subplan's target list.
1450 * 'need_tlist_eval' is set true if we really need to evaluate the
1453 * The result is the targetlist to be passed to the subplan.
1457 make_subplanTargetList(PlannerInfo *root,
1459 AttrNumber **groupColIdx,
1460 bool *need_tlist_eval)
1462 Query *parse = root->parse;
1467 *groupColIdx = NULL;
1470 * If we're not grouping or aggregating, there's nothing to do here;
1471 * query_planner should receive the unmodified target list.
1473 if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1475 *need_tlist_eval = true;
1480 * Otherwise, start with a "flattened" tlist (having just the vars
1481 * mentioned in the targetlist and HAVING qual --- but not upper-
1482 * level Vars; they will be replaced by Params later on).
1484 sub_tlist = flatten_tlist(tlist);
1485 extravars = pull_var_clause(parse->havingQual, false);
1486 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1487 list_free(extravars);
1488 *need_tlist_eval = false; /* only eval if not flat tlist */
1491 * If grouping, create sub_tlist entries for all GROUP BY expressions
1492 * (GROUP BY items that are simple Vars should be in the list
1493 * already), and make an array showing where the group columns are in
1496 numCols = list_length(parse->groupClause);
1500 AttrNumber *grpColIdx;
1503 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1504 *groupColIdx = grpColIdx;
1506 foreach(gl, parse->groupClause)
1508 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1509 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1510 TargetEntry *te = NULL;
1513 /* Find or make a matching sub_tlist entry */
1514 foreach(sl, sub_tlist)
1516 te = (TargetEntry *) lfirst(sl);
1517 if (equal(groupexpr, te->expr))
1522 te = makeTargetEntry((Expr *) groupexpr,
1523 list_length(sub_tlist) + 1,
1526 sub_tlist = lappend(sub_tlist, te);
1527 *need_tlist_eval = true; /* it's not flat anymore */
1530 /* and save its resno */
1531 grpColIdx[keyno++] = te->resno;
1539 * locate_grouping_columns
1540 * Locate grouping columns in the tlist chosen by query_planner.
1542 * This is only needed if we don't use the sub_tlist chosen by
1543 * make_subplanTargetList. We have to forget the column indexes found
1544 * by that routine and re-locate the grouping vars in the real sub_tlist.
1547 locate_grouping_columns(PlannerInfo *root,
1550 AttrNumber *groupColIdx)
1556 * No work unless grouping.
1558 if (!root->parse->groupClause)
1560 Assert(groupColIdx == NULL);
1563 Assert(groupColIdx != NULL);
1565 foreach(gl, root->parse->groupClause)
1567 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1568 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1569 TargetEntry *te = NULL;
1572 foreach(sl, sub_tlist)
1574 te = (TargetEntry *) lfirst(sl);
1575 if (equal(groupexpr, te->expr))
1579 elog(ERROR, "failed to locate grouping columns");
1581 groupColIdx[keyno++] = te->resno;
1586 * postprocess_setop_tlist
1587 * Fix up targetlist returned by plan_set_operations().
1589 * We need to transpose sort key info from the orig_tlist into new_tlist.
1590 * NOTE: this would not be good enough if we supported resjunk sort keys
1591 * for results of set operations --- then, we'd need to project a whole
1592 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1593 * find any resjunk columns in orig_tlist.
1596 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1599 ListCell *orig_tlist_item = list_head(orig_tlist);
1601 foreach(l, new_tlist)
1603 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1604 TargetEntry *orig_tle;
1606 /* ignore resjunk columns in setop result */
1607 if (new_tle->resjunk)
1610 Assert(orig_tlist_item != NULL);
1611 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1612 orig_tlist_item = lnext(orig_tlist_item);
1613 if (orig_tle->resjunk) /* should not happen */
1614 elog(ERROR, "resjunk output columns are not implemented");
1615 Assert(new_tle->resno == orig_tle->resno);
1616 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1618 if (orig_tlist_item != NULL)
1619 elog(ERROR, "resjunk output columns are not implemented");