1 /*-------------------------------------------------------------------------
4 * The query optimizer external interface.
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/planner.c,v 1.156 2003/07/03 19:07:20 tgl 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
107 * doesn't want 'em all. Optimize for 10% retrieval (you
108 * gotta better 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
125 * run 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 = 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;
178 /* Set up for a new level of subquery */
180 PlannerInitPlan = NIL;
183 * Look for IN clauses at the top level of WHERE, and transform them
184 * into joins. Note that this step only handles IN clauses originally
185 * at top level of WHERE; if we pull up any subqueries in the next step,
186 * their INs are processed just before pulling them up.
188 parse->in_info_list = NIL;
189 if (parse->hasSubLinks)
190 parse->jointree->quals = pull_up_IN_clauses(parse,
191 parse->jointree->quals);
194 * Check to see if any subqueries in the rangetable can be merged into
197 parse->jointree = (FromExpr *)
198 pull_up_subqueries(parse, (Node *) parse->jointree, false);
201 * Detect whether any rangetable entries are RTE_JOIN kind; if not,
202 * we can avoid the expense of doing flatten_join_alias_vars(). Also
203 * check for outer joins --- if none, we can skip reduce_outer_joins().
204 * This must be done after we have done pull_up_subqueries, of course.
206 parse->hasJoinRTEs = false;
207 hasOuterJoins = false;
208 foreach(lst, parse->rtable)
210 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lst);
212 if (rte->rtekind == RTE_JOIN)
214 parse->hasJoinRTEs = true;
215 if (IS_OUTER_JOIN(rte->jointype))
217 hasOuterJoins = true;
218 /* Can quit scanning once we find an outer join */
225 * Do expression preprocessing on targetlist and quals.
227 parse->targetList = (List *)
228 preprocess_expression(parse, (Node *) parse->targetList,
231 preprocess_qual_conditions(parse, (Node *) parse->jointree);
233 parse->havingQual = preprocess_expression(parse, parse->havingQual,
236 parse->limitOffset = preprocess_expression(parse, parse->limitOffset,
238 parse->limitCount = preprocess_expression(parse, parse->limitCount,
241 parse->in_info_list = (List *)
242 preprocess_expression(parse, (Node *) parse->in_info_list,
245 /* Also need to preprocess expressions for function RTEs */
246 foreach(lst, parse->rtable)
248 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lst);
250 if (rte->rtekind == RTE_FUNCTION)
251 rte->funcexpr = preprocess_expression(parse, rte->funcexpr,
256 * A HAVING clause without aggregates is equivalent to a WHERE clause
257 * (except it can only refer to grouped fields). Transfer any
258 * agg-free clauses of the HAVING qual into WHERE. This may seem like
259 * wasting cycles to cater to stupidly-written queries, but there are
260 * other reasons for doing it. Firstly, if the query contains no aggs
261 * at all, then we aren't going to generate an Agg plan node, and so
262 * there'll be no place to execute HAVING conditions; without this
263 * transfer, we'd lose the HAVING condition entirely, which is wrong.
264 * Secondly, when we push down a qual condition into a sub-query, it's
265 * easiest to push the qual into HAVING always, in case it contains
266 * aggs, and then let this code sort it out.
268 * Note that both havingQual and parse->jointree->quals are in
269 * implicitly-ANDed-list form at this point, even though they are
270 * declared as Node *.
273 foreach(lst, (List *) parse->havingQual)
275 Node *havingclause = (Node *) lfirst(lst);
277 if (contain_agg_clause(havingclause))
278 newHaving = lappend(newHaving, havingclause);
280 parse->jointree->quals = (Node *)
281 lappend((List *) parse->jointree->quals, havingclause);
283 parse->havingQual = (Node *) newHaving;
286 * If we have any outer joins, try to reduce them to plain inner joins.
287 * This step is most easily done after we've done expression preprocessing.
290 reduce_outer_joins(parse);
293 * See if we can simplify the jointree; opportunities for this may come
294 * from having pulled up subqueries, or from flattening explicit JOIN
295 * syntax. We must do this after flattening JOIN alias variables, since
296 * eliminating explicit JOIN nodes from the jointree will cause
297 * get_relids_for_join() to fail. But it should happen after
298 * reduce_outer_joins, anyway.
300 parse->jointree = (FromExpr *)
301 simplify_jointree(parse, (Node *) parse->jointree);
304 * Do the main planning. If we have an inherited target relation,
305 * that needs special processing, else go straight to
308 if (parse->resultRelation &&
309 (lst = expand_inherited_rtentry(parse, parse->resultRelation,
311 plan = inheritance_planner(parse, lst);
313 plan = grouping_planner(parse, tuple_fraction);
316 * If any subplans were generated, or if we're inside a subplan, build
317 * initPlan list and extParam/allParam sets for plan nodes.
319 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
321 Cost initplan_cost = 0;
323 /* Prepare extParam/allParam sets for all nodes in tree */
324 SS_finalize_plan(plan, parse->rtable);
327 * SS_finalize_plan doesn't handle initPlans, so we have to manually
328 * attach them to the topmost plan node, and add their extParams to
329 * the topmost node's, too.
331 * We also add the total_cost of each initPlan to the startup cost
332 * of the top node. This is a conservative overestimate, since in
333 * fact each initPlan might be executed later than plan startup, or
336 plan->initPlan = PlannerInitPlan;
338 foreach(lst, plan->initPlan)
340 SubPlan *initplan = (SubPlan *) lfirst(lst);
342 plan->extParam = bms_add_members(plan->extParam,
343 initplan->plan->extParam);
344 initplan_cost += initplan->plan->total_cost;
347 plan->startup_cost += initplan_cost;
348 plan->total_cost += initplan_cost;
351 /* Return to outer subquery context */
353 PlannerInitPlan = saved_initplan;
354 /* we do NOT restore PlannerPlanId; that's not an oversight! */
360 * preprocess_expression
361 * Do subquery_planner's preprocessing work for an expression,
362 * which can be a targetlist, a WHERE clause (including JOIN/ON
363 * conditions), or a HAVING clause.
366 preprocess_expression(Query *parse, Node *expr, int kind)
369 * If the query has any join RTEs, replace join alias variables with
370 * base-relation variables. We must do this before sublink processing,
371 * else sublinks expanded out from join aliases wouldn't get processed.
373 if (parse->hasJoinRTEs)
374 expr = flatten_join_alias_vars(parse, expr);
377 * Simplify constant expressions.
379 * Note that at this point quals have not yet been converted to
380 * implicit-AND form, so we can apply eval_const_expressions directly.
382 expr = eval_const_expressions(expr);
385 * If it's a qual or havingQual, canonicalize it, and convert it to
386 * implicit-AND format.
388 * XXX Is there any value in re-applying eval_const_expressions after
391 if (kind == EXPRKIND_QUAL)
393 expr = (Node *) canonicalize_qual((Expr *) expr, true);
395 #ifdef OPTIMIZER_DEBUG
396 printf("After canonicalize_qual()\n");
401 /* Expand SubLinks to SubPlans */
402 if (parse->hasSubLinks)
403 expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL));
406 * XXX do not insert anything here unless you have grokked the comments
407 * in SS_replace_correlation_vars ...
410 /* Replace uplevel vars with Param nodes */
411 if (PlannerQueryLevel > 1)
412 expr = SS_replace_correlation_vars(expr);
418 * preprocess_qual_conditions
419 * Recursively scan the query's jointree and do subquery_planner's
420 * preprocessing work on each qual condition found therein.
423 preprocess_qual_conditions(Query *parse, Node *jtnode)
427 if (IsA(jtnode, RangeTblRef))
429 /* nothing to do here */
431 else if (IsA(jtnode, FromExpr))
433 FromExpr *f = (FromExpr *) jtnode;
436 foreach(l, f->fromlist)
437 preprocess_qual_conditions(parse, lfirst(l));
439 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_QUAL);
441 else if (IsA(jtnode, JoinExpr))
443 JoinExpr *j = (JoinExpr *) jtnode;
445 preprocess_qual_conditions(parse, j->larg);
446 preprocess_qual_conditions(parse, j->rarg);
448 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_QUAL);
451 elog(ERROR, "preprocess_qual_conditions: unexpected node type %d",
455 /*--------------------
456 * inheritance_planner
457 * Generate a plan in the case where the result relation is an
460 * We have to handle this case differently from cases where a source
461 * relation is an inheritance set. Source inheritance is expanded at
462 * the bottom of the plan tree (see allpaths.c), but target inheritance
463 * has to be expanded at the top. The reason is that for UPDATE, each
464 * target relation needs a different targetlist matching its own column
465 * set. (This is not so critical for DELETE, but for simplicity we treat
466 * inherited DELETE the same way.) Fortunately, the UPDATE/DELETE target
467 * can never be the nullable side of an outer join, so it's OK to generate
470 * parse is the querytree produced by the parser & rewriter.
471 * inheritlist is an integer list of RT indexes for the result relation set.
473 * Returns a query plan.
474 *--------------------
477 inheritance_planner(Query *parse, List *inheritlist)
479 int parentRTindex = parse->resultRelation;
480 Oid parentOID = getrelid(parentRTindex, parse->rtable);
481 int mainrtlength = length(parse->rtable);
482 List *subplans = NIL;
486 foreach(l, inheritlist)
488 int childRTindex = lfirsti(l);
489 Oid childOID = getrelid(childRTindex, parse->rtable);
494 /* Generate modified query with this rel as target */
495 subquery = (Query *) adjust_inherited_attrs((Node *) parse,
496 parentRTindex, parentOID,
497 childRTindex, childOID);
499 subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */ );
500 subplans = lappend(subplans, subplan);
502 * It's possible that additional RTEs got added to the rangetable
503 * due to expansion of inherited source tables (see allpaths.c).
504 * If so, we must copy 'em back to the main parse tree's rtable.
506 * XXX my goodness this is ugly. Really need to think about ways
507 * to rein in planner's habit of scribbling on its input.
509 subrtlength = length(subquery->rtable);
510 if (subrtlength > mainrtlength)
512 List *subrt = subquery->rtable;
514 while (mainrtlength-- > 0) /* wish we had nthcdr() */
515 subrt = lnext(subrt);
516 parse->rtable = nconc(parse->rtable, subrt);
517 mainrtlength = subrtlength;
519 /* Save preprocessed tlist from first rel for use in Append */
521 tlist = subplan->targetlist;
524 /* Save the target-relations list for the executor, too */
525 parse->resultRelations = inheritlist;
527 /* Mark result as unordered (probably unnecessary) */
528 parse->query_pathkeys = NIL;
530 return (Plan *) make_append(subplans, true, tlist);
533 /*--------------------
535 * Perform planning steps related to grouping, aggregation, etc.
536 * This primarily means adding top-level processing to the basic
537 * query plan produced by query_planner.
539 * parse is the querytree produced by the parser & rewriter.
540 * tuple_fraction is the fraction of tuples we expect will be retrieved
542 * tuple_fraction is interpreted as follows:
543 * 0: expect all tuples to be retrieved (normal case)
544 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
545 * from the plan to be retrieved
546 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
547 * expected to be retrieved (ie, a LIMIT specification)
549 * Returns a query plan. Also, parse->query_pathkeys is returned as the
550 * actual output ordering of the plan (in pathkey format).
551 *--------------------
554 grouping_planner(Query *parse, double tuple_fraction)
556 List *tlist = parse->targetList;
558 List *current_pathkeys;
561 if (parse->setOperations)
564 * Construct the plan for set operations. The result will not
565 * need any work except perhaps a top-level sort and/or LIMIT.
567 result_plan = plan_set_operations(parse);
570 * We should not need to call preprocess_targetlist, since we must
571 * be in a SELECT query node. Instead, use the targetlist
572 * returned by plan_set_operations (since this tells whether it
573 * returned any resjunk columns!), and transfer any sort key
574 * information from the original tlist.
576 Assert(parse->commandType == CMD_SELECT);
578 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
581 * Can't handle FOR UPDATE here (parser should have checked
582 * already, but let's make sure).
585 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
588 * We set current_pathkeys NIL indicating we do not know sort
589 * order. This is correct when the top set operation is UNION
590 * ALL, since the appended-together results are unsorted even if
591 * the subplans were sorted. For other set operations we could be
592 * smarter --- room for future improvement!
594 current_pathkeys = NIL;
597 * Calculate pathkeys that represent ordering requirements
599 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
601 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
605 /* No set operations, do regular planning */
607 List *group_pathkeys;
608 AttrNumber *groupColIdx = NULL;
609 bool need_tlist_eval = true;
611 double sub_tuple_fraction;
614 double dNumGroups = 0;
617 int numGroupCols = length(parse->groupClause);
618 bool use_hashed_grouping = false;
620 /* Preprocess targetlist in case we are inside an INSERT/UPDATE. */
621 tlist = preprocess_targetlist(tlist,
623 parse->resultRelation,
627 * Add TID targets for rels selected FOR UPDATE (should this be
628 * done in preprocess_targetlist?). The executor uses the TID to
629 * know which rows to lock, much as for UPDATE or DELETE.
636 * We've got trouble if the FOR UPDATE appears inside
637 * grouping, since grouping renders a reference to individual
638 * tuple CTIDs invalid. This is also checked at parse time,
639 * but that's insufficient because of rule substitution, query
642 CheckSelectForUpdate(parse);
645 * Currently the executor only supports FOR UPDATE at top
648 if (PlannerQueryLevel > 1)
649 elog(ERROR, "SELECT FOR UPDATE is not allowed in subselects");
651 foreach(l, parse->rowMarks)
653 Index rti = lfirsti(l);
659 resname = (char *) palloc(32);
660 snprintf(resname, 32, "ctid%u", rti);
661 resdom = makeResdom(length(tlist) + 1,
668 SelfItemPointerAttributeNumber,
673 ctid = makeTargetEntry(resdom, (Expr *) var);
674 tlist = lappend(tlist, ctid);
679 * Generate appropriate target list for subplan; may be different
680 * from tlist if grouping or aggregation is needed.
682 sub_tlist = make_subplanTargetList(parse, tlist,
683 &groupColIdx, &need_tlist_eval);
686 * Calculate pathkeys that represent grouping/ordering
689 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
691 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
695 * Will need actual number of aggregates for estimating costs.
696 * Also, it's possible that optimization has eliminated all
697 * aggregates, and we may as well check for that here.
699 * Note: we do not attempt to detect duplicate aggregates here;
700 * a somewhat-overestimated count is okay for our present purposes.
704 numAggs = count_agg_clause((Node *) tlist) +
705 count_agg_clause(parse->havingQual);
707 parse->hasAggs = false;
711 * Figure out whether we need a sorted result from query_planner.
713 * If we have a GROUP BY clause, then we want a result sorted
714 * properly for grouping. Otherwise, if there is an ORDER BY
715 * clause, we want to sort by the ORDER BY clause. (Note: if we
716 * have both, and ORDER BY is a superset of GROUP BY, it would be
717 * tempting to request sort by ORDER BY --- but that might just
718 * leave us failing to exploit an available sort order at all.
719 * Needs more thought...)
721 if (parse->groupClause)
722 parse->query_pathkeys = group_pathkeys;
723 else if (parse->sortClause)
724 parse->query_pathkeys = sort_pathkeys;
726 parse->query_pathkeys = NIL;
729 * Adjust tuple_fraction if we see that we are going to apply
730 * limiting/grouping/aggregation/etc. This is not overridable by
731 * the caller, since it reflects plan actions that this routine
732 * will certainly take, not assumptions about context.
734 if (parse->limitCount != NULL)
737 * A LIMIT clause limits the absolute number of tuples
738 * returned. However, if it's not a constant LIMIT then we
739 * have to punt; for lack of a better idea, assume 10% of the
740 * plan's result is wanted.
742 double limit_fraction = 0.0;
744 if (IsA(parse->limitCount, Const))
746 Const *limitc = (Const *) parse->limitCount;
747 int32 count = DatumGetInt32(limitc->constvalue);
750 * A NULL-constant LIMIT represents "LIMIT ALL", which we
751 * treat the same as no limit (ie, expect to retrieve all
754 if (!limitc->constisnull && count > 0)
756 limit_fraction = (double) count;
757 /* We must also consider the OFFSET, if present */
758 if (parse->limitOffset != NULL)
760 if (IsA(parse->limitOffset, Const))
764 limitc = (Const *) parse->limitOffset;
765 offset = DatumGetInt32(limitc->constvalue);
766 if (!limitc->constisnull && offset > 0)
767 limit_fraction += (double) offset;
771 /* OFFSET is an expression ... punt ... */
772 limit_fraction = 0.10;
779 /* LIMIT is an expression ... punt ... */
780 limit_fraction = 0.10;
783 if (limit_fraction > 0.0)
786 * If we have absolute limits from both caller and LIMIT,
787 * use the smaller value; if one is fractional and the
788 * other absolute, treat the fraction as a fraction of the
789 * absolute value; else we can multiply the two fractions
792 if (tuple_fraction >= 1.0)
794 if (limit_fraction >= 1.0)
797 tuple_fraction = Min(tuple_fraction, limit_fraction);
801 /* caller absolute, limit fractional */
802 tuple_fraction *= limit_fraction;
803 if (tuple_fraction < 1.0)
804 tuple_fraction = 1.0;
807 else if (tuple_fraction > 0.0)
809 if (limit_fraction >= 1.0)
811 /* caller fractional, limit absolute */
812 tuple_fraction *= limit_fraction;
813 if (tuple_fraction < 1.0)
814 tuple_fraction = 1.0;
818 /* both fractional */
819 tuple_fraction *= limit_fraction;
824 /* no info from caller, just use limit */
825 tuple_fraction = limit_fraction;
831 * With grouping or aggregation, the tuple fraction to pass to
832 * query_planner() may be different from what it is at top level.
834 sub_tuple_fraction = tuple_fraction;
836 if (parse->groupClause)
839 * In GROUP BY mode, we have the little problem that we don't
840 * really know how many input tuples will be needed to make a
841 * group, so we can't translate an output LIMIT count into an
842 * input count. For lack of a better idea, assume 25% of the
843 * input data will be processed if there is any output limit.
844 * However, if the caller gave us a fraction rather than an
845 * absolute count, we can keep using that fraction (which
846 * amounts to assuming that all the groups are about the same
849 if (sub_tuple_fraction >= 1.0)
850 sub_tuple_fraction = 0.25;
853 * If both GROUP BY and ORDER BY are specified, we will need
854 * two levels of sort --- and, therefore, certainly need to
855 * read all the input tuples --- unless ORDER BY is a subset
856 * of GROUP BY. (We have not yet canonicalized the pathkeys,
857 * so must use the slower noncanonical comparison method.)
859 if (parse->groupClause && parse->sortClause &&
860 !noncanonical_pathkeys_contained_in(sort_pathkeys,
862 sub_tuple_fraction = 0.0;
864 else if (parse->hasAggs)
867 * Ungrouped aggregate will certainly want all the input
870 sub_tuple_fraction = 0.0;
872 else if (parse->distinctClause)
875 * SELECT DISTINCT, like GROUP, will absorb an unpredictable
876 * number of input tuples per output tuple. Handle the same
879 if (sub_tuple_fraction >= 1.0)
880 sub_tuple_fraction = 0.25;
884 * Generate the best unsorted and presorted paths for this Query
885 * (but note there may not be any presorted path).
887 query_planner(parse, sub_tlist, sub_tuple_fraction,
888 &cheapest_path, &sorted_path);
891 * We couldn't canonicalize group_pathkeys and sort_pathkeys before
892 * running query_planner(), so do it now.
894 group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
895 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
898 * Consider whether we might want to use hashed grouping.
900 if (parse->groupClause)
903 double cheapest_path_rows;
904 int cheapest_path_width;
907 * Beware in this section of the possibility that
908 * cheapest_path->parent is NULL. This could happen if user
909 * does something silly like SELECT 'foo' GROUP BY 1;
911 if (cheapest_path->parent)
913 cheapest_path_rows = cheapest_path->parent->rows;
914 cheapest_path_width = cheapest_path->parent->width;
918 cheapest_path_rows = 1; /* assume non-set result */
919 cheapest_path_width = 100; /* arbitrary */
923 * Always estimate the number of groups. We can't do this until
924 * after running query_planner(), either.
926 groupExprs = get_sortgrouplist_exprs(parse->groupClause,
928 dNumGroups = estimate_num_groups(parse,
931 /* Also want it as a long int --- but 'ware overflow! */
932 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
935 * Check can't-do-it conditions, including whether the grouping
936 * operators are hashjoinable.
938 * Executor doesn't support hashed aggregation with DISTINCT
939 * aggregates. (Doing so would imply storing *all* the input
940 * values in the hash table, which seems like a certain loser.)
942 if (!enable_hashagg || !hash_safe_grouping(parse))
943 use_hashed_grouping = false;
944 else if (parse->hasAggs &&
945 (contain_distinct_agg_clause((Node *) tlist) ||
946 contain_distinct_agg_clause(parse->havingQual)))
947 use_hashed_grouping = false;
951 * Use hashed grouping if (a) we think we can fit the
952 * hashtable into SortMem, *and* (b) the estimated cost
953 * is no more than doing it the other way. While avoiding
954 * the need for sorted input is usually a win, the fact
955 * that the output won't be sorted may be a loss; so we
956 * need to do an actual cost comparison.
958 * In most cases we have no good way to estimate the size of
959 * the transition value needed by an aggregate; arbitrarily
960 * assume it is 100 bytes. Also set the overhead per hashtable
963 int hashentrysize = cheapest_path_width + 64 + numAggs * 100;
965 if (hashentrysize * dNumGroups <= SortMem * 1024L)
968 * Okay, do the cost comparison. We need to consider
969 * cheapest_path + hashagg [+ final sort]
971 * cheapest_path [+ sort] + group or agg [+ final sort]
973 * presorted_path + group or agg [+ final sort]
974 * where brackets indicate a step that may not be needed.
975 * We assume query_planner() will have returned a
976 * presorted path only if it's a winner compared to
977 * cheapest_path for this purpose.
979 * These path variables are dummies that just hold cost
980 * fields; we don't make actual Paths for these steps.
985 cost_agg(&hashed_p, parse,
987 numGroupCols, dNumGroups,
988 cheapest_path->startup_cost,
989 cheapest_path->total_cost,
991 /* Result of hashed agg is always unsorted */
993 cost_sort(&hashed_p, parse, sort_pathkeys,
996 cheapest_path_width);
1000 sorted_p.startup_cost = sorted_path->startup_cost;
1001 sorted_p.total_cost = sorted_path->total_cost;
1002 current_pathkeys = sorted_path->pathkeys;
1006 sorted_p.startup_cost = cheapest_path->startup_cost;
1007 sorted_p.total_cost = cheapest_path->total_cost;
1008 current_pathkeys = cheapest_path->pathkeys;
1010 if (!pathkeys_contained_in(group_pathkeys,
1013 cost_sort(&sorted_p, parse, group_pathkeys,
1014 sorted_p.total_cost,
1016 cheapest_path_width);
1017 current_pathkeys = group_pathkeys;
1020 cost_agg(&sorted_p, parse,
1021 AGG_SORTED, numAggs,
1022 numGroupCols, dNumGroups,
1023 sorted_p.startup_cost,
1024 sorted_p.total_cost,
1025 cheapest_path_rows);
1027 cost_group(&sorted_p, parse,
1028 numGroupCols, dNumGroups,
1029 sorted_p.startup_cost,
1030 sorted_p.total_cost,
1031 cheapest_path_rows);
1032 /* The Agg or Group node will preserve ordering */
1033 if (sort_pathkeys &&
1034 !pathkeys_contained_in(sort_pathkeys,
1037 cost_sort(&sorted_p, parse, sort_pathkeys,
1038 sorted_p.total_cost,
1040 cheapest_path_width);
1044 * Now make the decision using the top-level tuple
1045 * fraction. First we have to convert an absolute
1046 * count (LIMIT) into fractional form.
1048 if (tuple_fraction >= 1.0)
1049 tuple_fraction /= dNumGroups;
1051 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1052 tuple_fraction) < 0)
1054 /* Hashed is cheaper, so use it */
1055 use_hashed_grouping = true;
1062 * Select the best path and create a plan to execute it.
1064 * If we are doing hashed grouping, we will always read all the
1065 * input tuples, so use the cheapest-total path. Otherwise,
1066 * trust query_planner's decision about which to use.
1068 if (sorted_path && !use_hashed_grouping)
1070 result_plan = create_plan(parse, sorted_path);
1071 current_pathkeys = sorted_path->pathkeys;
1075 result_plan = create_plan(parse, cheapest_path);
1076 current_pathkeys = cheapest_path->pathkeys;
1080 * create_plan() returns a plan with just a "flat" tlist of required
1081 * Vars. Usually we need to insert the sub_tlist as the tlist of the
1082 * top plan node. However, we can skip that if we determined that
1083 * whatever query_planner chose to return will be good enough.
1085 if (need_tlist_eval)
1088 * If the top-level plan node is one that cannot do expression
1089 * evaluation, we must insert a Result node to project the desired
1091 * Currently, the only plan node we might see here that falls into
1092 * that category is Append.
1094 if (IsA(result_plan, Append))
1096 result_plan = (Plan *) make_result(sub_tlist, NULL,
1102 * Otherwise, just replace the subplan's flat tlist with
1103 * the desired tlist.
1105 result_plan->targetlist = sub_tlist;
1108 * Also, account for the cost of evaluation of the sub_tlist.
1110 * Up to now, we have only been dealing with "flat" tlists,
1111 * containing just Vars. So their evaluation cost is zero
1112 * according to the model used by cost_qual_eval() (or if you
1113 * prefer, the cost is factored into cpu_tuple_cost). Thus we can
1114 * avoid accounting for tlist cost throughout query_planner() and
1115 * subroutines. But now we've inserted a tlist that might contain
1116 * actual operators, sub-selects, etc --- so we'd better account
1119 * Below this point, any tlist eval cost for added-on nodes should
1120 * be accounted for as we create those nodes. Presently, of the
1121 * node types we can add on, only Agg and Group project new tlists
1122 * (the rest just copy their input tuples) --- so make_agg() and
1123 * make_group() are responsible for computing the added cost.
1125 cost_qual_eval(&tlist_cost, sub_tlist);
1126 result_plan->startup_cost += tlist_cost.startup;
1127 result_plan->total_cost += tlist_cost.startup +
1128 tlist_cost.per_tuple * result_plan->plan_rows;
1133 * Since we're using query_planner's tlist and not the one
1134 * make_subplanTargetList calculated, we have to refigure
1135 * any grouping-column indexes make_subplanTargetList computed.
1137 locate_grouping_columns(parse, tlist, result_plan->targetlist,
1142 * Insert AGG or GROUP node if needed, plus an explicit sort step
1145 * HAVING clause, if any, becomes qual of the Agg node
1147 if (use_hashed_grouping)
1149 /* Hashed aggregate plan --- no sort needed */
1150 result_plan = (Plan *) make_agg(parse,
1152 (List *) parse->havingQual,
1159 /* Hashed aggregation produces randomly-ordered results */
1160 current_pathkeys = NIL;
1162 else if (parse->hasAggs)
1164 /* Plain aggregate plan --- sort if needed */
1165 AggStrategy aggstrategy;
1167 if (parse->groupClause)
1169 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1171 result_plan = (Plan *)
1172 make_sort_from_groupcols(parse,
1176 current_pathkeys = group_pathkeys;
1178 aggstrategy = AGG_SORTED;
1180 * The AGG node will not change the sort ordering of its
1181 * groups, so current_pathkeys describes the result too.
1186 aggstrategy = AGG_PLAIN;
1187 /* Result will be only one row anyway; no sort order */
1188 current_pathkeys = NIL;
1191 result_plan = (Plan *) make_agg(parse,
1193 (List *) parse->havingQual,
1204 * If there are no Aggs, we shouldn't have any HAVING qual anymore
1206 Assert(parse->havingQual == NULL);
1209 * If we have a GROUP BY clause, insert a group node (plus the
1210 * appropriate sort node, if necessary).
1212 if (parse->groupClause)
1215 * Add an explicit sort if we couldn't make the path come out
1216 * the way the GROUP node needs it.
1218 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1220 result_plan = (Plan *)
1221 make_sort_from_groupcols(parse,
1225 current_pathkeys = group_pathkeys;
1228 result_plan = (Plan *) make_group(parse,
1234 /* The Group node won't change sort ordering */
1237 } /* end of if (setOperations) */
1240 * If we were not able to make the plan come out in the right order,
1241 * add an explicit sort step.
1243 if (parse->sortClause)
1245 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1247 result_plan = (Plan *)
1248 make_sort_from_sortclauses(parse,
1252 current_pathkeys = sort_pathkeys;
1257 * If there is a DISTINCT clause, add the UNIQUE node.
1259 if (parse->distinctClause)
1261 result_plan = (Plan *) make_unique(tlist, result_plan,
1262 parse->distinctClause);
1264 * If there was grouping or aggregation, leave plan_rows as-is
1265 * (ie, assume the result was already mostly unique). If not,
1266 * it's reasonable to assume the UNIQUE filter has effects
1267 * comparable to GROUP BY.
1269 if (!parse->groupClause && !parse->hasAggs)
1271 List *distinctExprs;
1273 distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
1275 result_plan->plan_rows = estimate_num_groups(parse,
1277 result_plan->plan_rows);
1282 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1284 if (parse->limitOffset || parse->limitCount)
1286 result_plan = (Plan *) make_limit(tlist, result_plan,
1292 * Return the actual output ordering in query_pathkeys for possible
1293 * use by an outer query level.
1295 parse->query_pathkeys = current_pathkeys;
1301 * hash_safe_grouping - are grouping operators hashable?
1303 * We assume hashed aggregation will work if the datatype's equality operator
1304 * is marked hashjoinable.
1307 hash_safe_grouping(Query *parse)
1311 foreach(gl, parse->groupClause)
1313 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1314 TargetEntry *tle = get_sortgroupclause_tle(grpcl, parse->targetList);
1318 optup = equality_oper(tle->resdom->restype, false);
1319 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1320 ReleaseSysCache(optup);
1328 * make_subplanTargetList
1329 * Generate appropriate target list when grouping is required.
1331 * When grouping_planner inserts Aggregate or Group plan nodes above
1332 * the result of query_planner, we typically want to pass a different
1333 * target list to query_planner than the outer plan nodes should have.
1334 * This routine generates the correct target list for the subplan.
1336 * The initial target list passed from the parser already contains entries
1337 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1338 * for variables used only in HAVING clauses; so we need to add those
1339 * variables to the subplan target list. Also, if we are doing either
1340 * grouping or aggregation, we flatten all expressions except GROUP BY items
1341 * into their component variables; the other expressions will be computed by
1342 * the inserted nodes rather than by the subplan. For example,
1343 * given a query like
1344 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1345 * we want to pass this targetlist to the subplan:
1347 * where the a+b target will be used by the Sort/Group steps, and the
1348 * other targets will be used for computing the final results. (In the
1349 * above example we could theoretically suppress the a and b targets and
1350 * pass down only c,d,a+b, but it's not really worth the trouble to
1351 * eliminate simple var references from the subplan. We will avoid doing
1352 * the extra computation to recompute a+b at the outer level; see
1353 * replace_vars_with_subplan_refs() in setrefs.c.)
1355 * If we are grouping or aggregating, *and* there are no non-Var grouping
1356 * expressions, then the returned tlist is effectively dummy; we do not
1357 * need to force it to be evaluated, because all the Vars it contains
1358 * should be present in the output of query_planner anyway.
1360 * 'parse' is the query being processed.
1361 * 'tlist' is the query's target list.
1362 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1363 * expressions (if there are any) in the subplan's target list.
1364 * 'need_tlist_eval' is set true if we really need to evaluate the
1367 * The result is the targetlist to be passed to the subplan.
1371 make_subplanTargetList(Query *parse,
1373 AttrNumber **groupColIdx,
1374 bool *need_tlist_eval)
1380 *groupColIdx = NULL;
1383 * If we're not grouping or aggregating, nothing to do here;
1384 * query_planner should receive the unmodified target list.
1386 if (!parse->hasAggs && !parse->groupClause)
1388 *need_tlist_eval = true;
1393 * Otherwise, start with a "flattened" tlist (having just the vars
1394 * mentioned in the targetlist and HAVING qual --- but not upper-
1395 * level Vars; they will be replaced by Params later on).
1397 sub_tlist = flatten_tlist(tlist);
1398 extravars = pull_var_clause(parse->havingQual, false);
1399 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1400 freeList(extravars);
1401 *need_tlist_eval = false; /* only eval if not flat tlist */
1404 * If grouping, create sub_tlist entries for all GROUP BY expressions
1405 * (GROUP BY items that are simple Vars should be in the list
1406 * already), and make an array showing where the group columns are in
1409 numCols = length(parse->groupClause);
1413 AttrNumber *grpColIdx;
1416 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1417 *groupColIdx = grpColIdx;
1419 foreach(gl, parse->groupClause)
1421 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1422 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1423 TargetEntry *te = NULL;
1426 /* Find or make a matching sub_tlist entry */
1427 foreach(sl, sub_tlist)
1429 te = (TargetEntry *) lfirst(sl);
1430 if (equal(groupexpr, te->expr))
1435 te = makeTargetEntry(makeResdom(length(sub_tlist) + 1,
1436 exprType(groupexpr),
1437 exprTypmod(groupexpr),
1440 (Expr *) groupexpr);
1441 sub_tlist = lappend(sub_tlist, te);
1442 *need_tlist_eval = true; /* it's not flat anymore */
1445 /* and save its resno */
1446 grpColIdx[keyno++] = te->resdom->resno;
1454 * locate_grouping_columns
1455 * Locate grouping columns in the tlist chosen by query_planner.
1457 * This is only needed if we don't use the sub_tlist chosen by
1458 * make_subplanTargetList. We have to forget the column indexes found
1459 * by that routine and re-locate the grouping vars in the real sub_tlist.
1462 locate_grouping_columns(Query *parse,
1465 AttrNumber *groupColIdx)
1471 * No work unless grouping.
1473 if (!parse->groupClause)
1475 Assert(groupColIdx == NULL);
1478 Assert(groupColIdx != NULL);
1480 foreach(gl, parse->groupClause)
1482 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1483 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1484 TargetEntry *te = NULL;
1487 foreach(sl, sub_tlist)
1489 te = (TargetEntry *) lfirst(sl);
1490 if (equal(groupexpr, te->expr))
1494 elog(ERROR, "locate_grouping_columns: failed");
1496 groupColIdx[keyno++] = te->resdom->resno;
1501 * postprocess_setop_tlist
1502 * Fix up targetlist returned by plan_set_operations().
1504 * We need to transpose sort key info from the orig_tlist into new_tlist.
1505 * NOTE: this would not be good enough if we supported resjunk sort keys
1506 * for results of set operations --- then, we'd need to project a whole
1507 * new tlist to evaluate the resjunk columns. For now, just elog if we
1508 * find any resjunk columns in orig_tlist.
1511 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1515 foreach(l, new_tlist)
1517 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1518 TargetEntry *orig_tle;
1520 /* ignore resjunk columns in setop result */
1521 if (new_tle->resdom->resjunk)
1524 Assert(orig_tlist != NIL);
1525 orig_tle = (TargetEntry *) lfirst(orig_tlist);
1526 orig_tlist = lnext(orig_tlist);
1527 if (orig_tle->resdom->resjunk)
1528 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");
1529 Assert(new_tle->resdom->resno == orig_tle->resdom->resno);
1530 Assert(new_tle->resdom->restype == orig_tle->resdom->restype);
1531 new_tle->resdom->ressortgroupref = orig_tle->resdom->ressortgroupref;
1533 if (orig_tlist != NIL)
1534 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");