1 /*-------------------------------------------------------------------------
4 * The query optimizer external interface.
6 * Portions Copyright (c) 1996-2008, 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.237 2008/08/03 19:10:52 tgl Exp $
13 *-------------------------------------------------------------------------
20 #include "catalog/pg_operator.h"
21 #include "executor/executor.h"
22 #include "executor/nodeAgg.h"
23 #include "miscadmin.h"
24 #include "nodes/makefuncs.h"
25 #include "optimizer/clauses.h"
26 #include "optimizer/cost.h"
27 #include "optimizer/pathnode.h"
28 #include "optimizer/paths.h"
29 #include "optimizer/planmain.h"
30 #include "optimizer/planner.h"
31 #include "optimizer/prep.h"
32 #include "optimizer/subselect.h"
33 #include "optimizer/tlist.h"
34 #include "optimizer/var.h"
35 #ifdef OPTIMIZER_DEBUG
36 #include "nodes/print.h"
38 #include "parser/parse_expr.h"
39 #include "parser/parse_oper.h"
40 #include "parser/parsetree.h"
41 #include "utils/lsyscache.h"
42 #include "utils/syscache.h"
46 double cursor_tuple_fraction = DEFAULT_CURSOR_TUPLE_FRACTION;
48 /* Hook for plugins to get control in planner() */
49 planner_hook_type planner_hook = NULL;
52 /* Expression kind codes for preprocess_expression */
53 #define EXPRKIND_QUAL 0
54 #define EXPRKIND_TARGET 1
55 #define EXPRKIND_RTFUNC 2
56 #define EXPRKIND_VALUES 3
57 #define EXPRKIND_LIMIT 4
58 #define EXPRKIND_ININFO 5
59 #define EXPRKIND_APPINFO 6
62 static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
63 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
64 static Plan *inheritance_planner(PlannerInfo *root);
65 static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
66 static bool is_dummy_plan(Plan *plan);
67 static double preprocess_limit(PlannerInfo *root,
68 double tuple_fraction,
69 int64 *offset_est, int64 *count_est);
70 static void preprocess_groupclause(PlannerInfo *root);
71 static Oid *extract_grouping_ops(List *groupClause);
72 static bool grouping_is_sortable(List *groupClause);
73 static bool grouping_is_hashable(List *groupClause);
74 static bool choose_hashed_grouping(PlannerInfo *root,
75 double tuple_fraction, double limit_tuples,
76 Path *cheapest_path, Path *sorted_path,
77 double dNumGroups, AggClauseCounts *agg_counts);
78 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
79 AttrNumber **groupColIdx, bool *need_tlist_eval);
80 static void locate_grouping_columns(PlannerInfo *root,
83 AttrNumber *groupColIdx);
84 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
87 /*****************************************************************************
89 * Query optimizer entry point
91 * To support loadable plugins that monitor or modify planner behavior,
92 * we provide a hook variable that lets a plugin get control before and
93 * after the standard planning process. The plugin would normally call
96 * Note to plugin authors: standard_planner() scribbles on its Query input,
97 * so you'd better copy that data structure if you want to plan more than once.
99 *****************************************************************************/
101 planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
106 result = (*planner_hook) (parse, cursorOptions, boundParams);
108 result = standard_planner(parse, cursorOptions, boundParams);
113 standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
117 double tuple_fraction;
123 /* Cursor options may come from caller or from DECLARE CURSOR stmt */
124 if (parse->utilityStmt &&
125 IsA(parse->utilityStmt, DeclareCursorStmt))
126 cursorOptions |= ((DeclareCursorStmt *) parse->utilityStmt)->options;
129 * Set up global state for this planner invocation. This data is needed
130 * across all levels of sub-Query that might exist in the given command,
131 * so we keep it in a separate struct that's linked to by each per-Query
134 glob = makeNode(PlannerGlobal);
136 glob->boundParams = boundParams;
137 glob->paramlist = NIL;
138 glob->subplans = NIL;
139 glob->subrtables = NIL;
140 glob->rewindPlanIDs = NULL;
141 glob->finalrtable = NIL;
142 glob->relationOids = NIL;
143 glob->transientPlan = false;
145 /* Determine what fraction of the plan is likely to be scanned */
146 if (cursorOptions & CURSOR_OPT_FAST_PLAN)
149 * We have no real idea how many tuples the user will ultimately FETCH
150 * from a cursor, but it is often the case that he doesn't want 'em
151 * all, or would prefer a fast-start plan anyway so that he can
152 * process some of the tuples sooner. Use a GUC parameter to decide
153 * what fraction to optimize for.
155 tuple_fraction = cursor_tuple_fraction;
158 * We document cursor_tuple_fraction as simply being a fraction,
159 * which means the edge cases 0 and 1 have to be treated specially
160 * here. We convert 1 to 0 ("all the tuples") and 0 to a very small
163 if (tuple_fraction >= 1.0)
164 tuple_fraction = 0.0;
165 else if (tuple_fraction <= 0.0)
166 tuple_fraction = 1e-10;
170 /* Default assumption is we need all the tuples */
171 tuple_fraction = 0.0;
174 /* primary planning entry point (may recurse for subqueries) */
175 top_plan = subquery_planner(glob, parse, 1, tuple_fraction, &root);
178 * If creating a plan for a scrollable cursor, make sure it can run
179 * backwards on demand. Add a Material node at the top at need.
181 if (cursorOptions & CURSOR_OPT_SCROLL)
183 if (!ExecSupportsBackwardScan(top_plan))
184 top_plan = materialize_finished_plan(top_plan);
187 /* final cleanup of the plan */
188 Assert(glob->finalrtable == NIL);
189 top_plan = set_plan_references(glob, top_plan, root->parse->rtable);
190 /* ... and the subplans (both regular subplans and initplans) */
191 Assert(list_length(glob->subplans) == list_length(glob->subrtables));
192 forboth(lp, glob->subplans, lr, glob->subrtables)
194 Plan *subplan = (Plan *) lfirst(lp);
195 List *subrtable = (List *) lfirst(lr);
197 lfirst(lp) = set_plan_references(glob, subplan, subrtable);
200 /* build the PlannedStmt result */
201 result = makeNode(PlannedStmt);
203 result->commandType = parse->commandType;
204 result->canSetTag = parse->canSetTag;
205 result->transientPlan = glob->transientPlan;
206 result->planTree = top_plan;
207 result->rtable = glob->finalrtable;
208 result->resultRelations = root->resultRelations;
209 result->utilityStmt = parse->utilityStmt;
210 result->intoClause = parse->intoClause;
211 result->subplans = glob->subplans;
212 result->rewindPlanIDs = glob->rewindPlanIDs;
213 result->returningLists = root->returningLists;
214 result->rowMarks = parse->rowMarks;
215 result->relationOids = glob->relationOids;
216 result->nParamExec = list_length(glob->paramlist);
222 /*--------------------
224 * Invokes the planner on a subquery. We recurse to here for each
225 * sub-SELECT found in the query tree.
227 * glob is the global state for the current planner run.
228 * parse is the querytree produced by the parser & rewriter.
229 * level is the current recursion depth (1 at the top-level Query).
230 * tuple_fraction is the fraction of tuples we expect will be retrieved.
231 * tuple_fraction is interpreted as explained for grouping_planner, below.
233 * If subroot isn't NULL, we pass back the query's final PlannerInfo struct;
234 * among other things this tells the output sort ordering of the plan.
236 * Basically, this routine does the stuff that should only be done once
237 * per Query object. It then calls grouping_planner. At one time,
238 * grouping_planner could be invoked recursively on the same Query object;
239 * that's not currently true, but we keep the separation between the two
240 * routines anyway, in case we need it again someday.
242 * subquery_planner will be called recursively to handle sub-Query nodes
243 * found within the query's expressions and rangetable.
245 * Returns a query plan.
246 *--------------------
249 subquery_planner(PlannerGlobal *glob, Query *parse,
250 Index level, double tuple_fraction,
251 PlannerInfo **subroot)
253 int num_old_subplans = list_length(glob->subplans);
259 /* Create a PlannerInfo data structure for this subquery */
260 root = makeNode(PlannerInfo);
263 root->query_level = level;
264 root->planner_cxt = CurrentMemoryContext;
265 root->init_plans = NIL;
266 root->eq_classes = NIL;
267 root->in_info_list = NIL;
268 root->append_rel_list = NIL;
271 * Look for IN clauses at the top level of WHERE, and transform them into
272 * joins. Note that this step only handles IN clauses originally at top
273 * level of WHERE; if we pull up any subqueries below, their INs are
274 * processed just before pulling them up.
276 if (parse->hasSubLinks)
277 parse->jointree->quals = pull_up_IN_clauses(root,
278 parse->jointree->quals);
281 * Scan the rangetable for set-returning functions, and inline them
282 * if possible (producing subqueries that might get pulled up next).
283 * Recursion issues here are handled in the same way as for IN clauses.
285 inline_set_returning_functions(root);
288 * Check to see if any subqueries in the rangetable can be merged into
291 parse->jointree = (FromExpr *)
292 pull_up_subqueries(root, (Node *) parse->jointree, false, false);
295 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
296 * avoid the expense of doing flatten_join_alias_vars(). Also check for
297 * outer joins --- if none, we can skip reduce_outer_joins() and some
298 * other processing. This must be done after we have done
299 * pull_up_subqueries, of course.
301 * Note: if reduce_outer_joins manages to eliminate all outer joins,
302 * root->hasOuterJoins is not reset currently. This is OK since its
303 * purpose is merely to suppress unnecessary processing in simple cases.
305 root->hasJoinRTEs = false;
306 root->hasOuterJoins = false;
307 foreach(l, parse->rtable)
309 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
311 if (rte->rtekind == RTE_JOIN)
313 root->hasJoinRTEs = true;
314 if (IS_OUTER_JOIN(rte->jointype))
316 root->hasOuterJoins = true;
317 /* Can quit scanning once we find an outer join */
324 * Expand any rangetable entries that are inheritance sets into "append
325 * relations". This can add entries to the rangetable, but they must be
326 * plain base relations not joins, so it's OK (and marginally more
327 * efficient) to do it after checking for join RTEs. We must do it after
328 * pulling up subqueries, else we'd fail to handle inherited tables in
331 expand_inherited_tables(root);
334 * Set hasHavingQual to remember if HAVING clause is present. Needed
335 * because preprocess_expression will reduce a constant-true condition to
336 * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
338 root->hasHavingQual = (parse->havingQual != NULL);
340 /* Clear this flag; might get set in distribute_qual_to_rels */
341 root->hasPseudoConstantQuals = false;
344 * Do expression preprocessing on targetlist and quals.
346 parse->targetList = (List *)
347 preprocess_expression(root, (Node *) parse->targetList,
350 parse->returningList = (List *)
351 preprocess_expression(root, (Node *) parse->returningList,
354 preprocess_qual_conditions(root, (Node *) parse->jointree);
356 parse->havingQual = preprocess_expression(root, parse->havingQual,
359 parse->limitOffset = preprocess_expression(root, parse->limitOffset,
361 parse->limitCount = preprocess_expression(root, parse->limitCount,
364 root->in_info_list = (List *)
365 preprocess_expression(root, (Node *) root->in_info_list,
367 root->append_rel_list = (List *)
368 preprocess_expression(root, (Node *) root->append_rel_list,
371 /* Also need to preprocess expressions for function and values RTEs */
372 foreach(l, parse->rtable)
374 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
376 if (rte->rtekind == RTE_FUNCTION)
377 rte->funcexpr = preprocess_expression(root, rte->funcexpr,
379 else if (rte->rtekind == RTE_VALUES)
380 rte->values_lists = (List *)
381 preprocess_expression(root, (Node *) rte->values_lists,
386 * In some cases we may want to transfer a HAVING clause into WHERE. We
387 * cannot do so if the HAVING clause contains aggregates (obviously) or
388 * volatile functions (since a HAVING clause is supposed to be executed
389 * only once per group). Also, it may be that the clause is so expensive
390 * to execute that we're better off doing it only once per group, despite
391 * the loss of selectivity. This is hard to estimate short of doing the
392 * entire planning process twice, so we use a heuristic: clauses
393 * containing subplans are left in HAVING. Otherwise, we move or copy the
394 * HAVING clause into WHERE, in hopes of eliminating tuples before
395 * aggregation instead of after.
397 * If the query has explicit grouping then we can simply move such a
398 * clause into WHERE; any group that fails the clause will not be in the
399 * output because none of its tuples will reach the grouping or
400 * aggregation stage. Otherwise we must have a degenerate (variable-free)
401 * HAVING clause, which we put in WHERE so that query_planner() can use it
402 * in a gating Result node, but also keep in HAVING to ensure that we
403 * don't emit a bogus aggregated row. (This could be done better, but it
404 * seems not worth optimizing.)
406 * Note that both havingQual and parse->jointree->quals are in
407 * implicitly-ANDed-list form at this point, even though they are declared
411 foreach(l, (List *) parse->havingQual)
413 Node *havingclause = (Node *) lfirst(l);
415 if (contain_agg_clause(havingclause) ||
416 contain_volatile_functions(havingclause) ||
417 contain_subplans(havingclause))
419 /* keep it in HAVING */
420 newHaving = lappend(newHaving, havingclause);
422 else if (parse->groupClause)
424 /* move it to WHERE */
425 parse->jointree->quals = (Node *)
426 lappend((List *) parse->jointree->quals, havingclause);
430 /* put a copy in WHERE, keep it in HAVING */
431 parse->jointree->quals = (Node *)
432 lappend((List *) parse->jointree->quals,
433 copyObject(havingclause));
434 newHaving = lappend(newHaving, havingclause);
437 parse->havingQual = (Node *) newHaving;
440 * If we have any outer joins, try to reduce them to plain inner joins.
441 * This step is most easily done after we've done expression
444 if (root->hasOuterJoins)
445 reduce_outer_joins(root);
448 * Do the main planning. If we have an inherited target relation, that
449 * needs special processing, else go straight to grouping_planner.
451 if (parse->resultRelation &&
452 rt_fetch(parse->resultRelation, parse->rtable)->inh)
453 plan = inheritance_planner(root);
455 plan = grouping_planner(root, tuple_fraction);
458 * If any subplans were generated, or if we're inside a subplan, build
459 * initPlan list and extParam/allParam sets for plan nodes, and attach the
460 * initPlans to the top plan node.
462 if (list_length(glob->subplans) != num_old_subplans ||
463 root->query_level > 1)
464 SS_finalize_plan(root, plan, true);
466 /* Return internal info if caller wants it */
474 * preprocess_expression
475 * Do subquery_planner's preprocessing work for an expression,
476 * which can be a targetlist, a WHERE clause (including JOIN/ON
477 * conditions), or a HAVING clause.
480 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
483 * Fall out quickly if expression is empty. This occurs often enough to
484 * be worth checking. Note that null->null is the correct conversion for
485 * implicit-AND result format, too.
491 * If the query has any join RTEs, replace join alias variables with
492 * base-relation variables. We must do this before sublink processing,
493 * else sublinks expanded out from join aliases wouldn't get processed. We
494 * can skip it in VALUES lists, however, since they can't contain any Vars
497 if (root->hasJoinRTEs && kind != EXPRKIND_VALUES)
498 expr = flatten_join_alias_vars(root, expr);
501 * Simplify constant expressions.
503 * Note: this also flattens nested AND and OR expressions into N-argument
504 * form. All processing of a qual expression after this point must be
505 * careful to maintain AND/OR flatness --- that is, do not generate a tree
506 * with AND directly under AND, nor OR directly under OR.
508 * Because this is a relatively expensive process, we skip it when the
509 * query is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()". The
510 * expression will only be evaluated once anyway, so no point in
511 * pre-simplifying; we can't execute it any faster than the executor can,
512 * and we will waste cycles copying the tree. Notice however that we
513 * still must do it for quals (to get AND/OR flatness); and if we are in a
514 * subquery we should not assume it will be done only once.
516 * For VALUES lists we never do this at all, again on the grounds that we
517 * should optimize for one-time evaluation.
519 if (kind != EXPRKIND_VALUES &&
520 (root->parse->jointree->fromlist != NIL ||
521 kind == EXPRKIND_QUAL ||
522 root->query_level > 1))
523 expr = eval_const_expressions(root, expr);
526 * If it's a qual or havingQual, canonicalize it.
528 if (kind == EXPRKIND_QUAL)
530 expr = (Node *) canonicalize_qual((Expr *) expr);
532 #ifdef OPTIMIZER_DEBUG
533 printf("After canonicalize_qual()\n");
538 /* Expand SubLinks to SubPlans */
539 if (root->parse->hasSubLinks)
540 expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
543 * XXX do not insert anything here unless you have grokked the comments in
544 * SS_replace_correlation_vars ...
547 /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
548 if (root->query_level > 1)
549 expr = SS_replace_correlation_vars(root, expr);
552 * If it's a qual or havingQual, convert it to implicit-AND format. (We
553 * don't want to do this before eval_const_expressions, since the latter
554 * would be unable to simplify a top-level AND correctly. Also,
555 * SS_process_sublinks expects explicit-AND format.)
557 if (kind == EXPRKIND_QUAL)
558 expr = (Node *) make_ands_implicit((Expr *) expr);
564 * preprocess_qual_conditions
565 * Recursively scan the query's jointree and do subquery_planner's
566 * preprocessing work on each qual condition found therein.
569 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
573 if (IsA(jtnode, RangeTblRef))
575 /* nothing to do here */
577 else if (IsA(jtnode, FromExpr))
579 FromExpr *f = (FromExpr *) jtnode;
582 foreach(l, f->fromlist)
583 preprocess_qual_conditions(root, lfirst(l));
585 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
587 else if (IsA(jtnode, JoinExpr))
589 JoinExpr *j = (JoinExpr *) jtnode;
591 preprocess_qual_conditions(root, j->larg);
592 preprocess_qual_conditions(root, j->rarg);
594 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
597 elog(ERROR, "unrecognized node type: %d",
598 (int) nodeTag(jtnode));
602 * inheritance_planner
603 * Generate a plan in the case where the result relation is an
606 * We have to handle this case differently from cases where a source relation
607 * is an inheritance set. Source inheritance is expanded at the bottom of the
608 * plan tree (see allpaths.c), but target inheritance has to be expanded at
609 * the top. The reason is that for UPDATE, each target relation needs a
610 * different targetlist matching its own column set. Also, for both UPDATE
611 * and DELETE, the executor needs the Append plan node at the top, else it
612 * can't keep track of which table is the current target table. Fortunately,
613 * the UPDATE/DELETE target can never be the nullable side of an outer join,
614 * so it's OK to generate the plan this way.
616 * Returns a query plan.
619 inheritance_planner(PlannerInfo *root)
621 Query *parse = root->parse;
622 int parentRTindex = parse->resultRelation;
623 List *subplans = NIL;
624 List *resultRelations = NIL;
625 List *returningLists = NIL;
631 foreach(l, root->append_rel_list)
633 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
636 /* append_rel_list contains all append rels; ignore others */
637 if (appinfo->parent_relid != parentRTindex)
641 * Generate modified query with this rel as target. We have to be
642 * prepared to translate varnos in in_info_list as well as in the
645 memcpy(&subroot, root, sizeof(PlannerInfo));
646 subroot.parse = (Query *)
647 adjust_appendrel_attrs((Node *) parse,
649 subroot.in_info_list = (List *)
650 adjust_appendrel_attrs((Node *) root->in_info_list,
652 subroot.init_plans = NIL;
653 /* There shouldn't be any OJ info to translate, as yet */
654 Assert(subroot.oj_info_list == NIL);
657 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
660 * If this child rel was excluded by constraint exclusion, exclude it
663 if (is_dummy_plan(subplan))
666 /* Save rtable and tlist from first rel for use below */
669 rtable = subroot.parse->rtable;
670 tlist = subplan->targetlist;
673 subplans = lappend(subplans, subplan);
675 /* Make sure any initplans from this rel get into the outer list */
676 root->init_plans = list_concat(root->init_plans, subroot.init_plans);
678 /* Build target-relations list for the executor */
679 resultRelations = lappend_int(resultRelations, appinfo->child_relid);
681 /* Build list of per-relation RETURNING targetlists */
682 if (parse->returningList)
684 Assert(list_length(subroot.returningLists) == 1);
685 returningLists = list_concat(returningLists,
686 subroot.returningLists);
690 root->resultRelations = resultRelations;
691 root->returningLists = returningLists;
693 /* Mark result as unordered (probably unnecessary) */
694 root->query_pathkeys = NIL;
697 * If we managed to exclude every child rel, return a dummy plan
701 root->resultRelations = list_make1_int(parentRTindex);
702 /* although dummy, it must have a valid tlist for executor */
703 tlist = preprocess_targetlist(root, parse->targetList);
704 return (Plan *) make_result(root,
706 (Node *) list_make1(makeBoolConst(false,
712 * Planning might have modified the rangetable, due to changes of the
713 * Query structures inside subquery RTEs. We have to ensure that this
714 * gets propagated back to the master copy. But can't do this until we
715 * are done planning, because all the calls to grouping_planner need
716 * virgin sub-Queries to work from. (We are effectively assuming that
717 * sub-Queries will get planned identically each time, or at least that
718 * the impacts on their rangetables will be the same each time.)
720 * XXX should clean this up someday
722 parse->rtable = rtable;
724 /* Suppress Append if there's only one surviving child rel */
725 if (list_length(subplans) == 1)
726 return (Plan *) linitial(subplans);
728 return (Plan *) make_append(subplans, true, tlist);
731 /*--------------------
733 * Perform planning steps related to grouping, aggregation, etc.
734 * This primarily means adding top-level processing to the basic
735 * query plan produced by query_planner.
737 * tuple_fraction is the fraction of tuples we expect will be retrieved
739 * tuple_fraction is interpreted as follows:
740 * 0: expect all tuples to be retrieved (normal case)
741 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
742 * from the plan to be retrieved
743 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
744 * expected to be retrieved (ie, a LIMIT specification)
746 * Returns a query plan. Also, root->query_pathkeys is returned as the
747 * actual output ordering of the plan (in pathkey format).
748 *--------------------
751 grouping_planner(PlannerInfo *root, double tuple_fraction)
753 Query *parse = root->parse;
754 List *tlist = parse->targetList;
755 int64 offset_est = 0;
757 double limit_tuples = -1.0;
759 List *current_pathkeys;
761 double dNumGroups = 0;
763 /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
764 if (parse->limitCount || parse->limitOffset)
766 tuple_fraction = preprocess_limit(root, tuple_fraction,
767 &offset_est, &count_est);
770 * If we have a known LIMIT, and don't have an unknown OFFSET, we can
771 * estimate the effects of using a bounded sort.
773 if (count_est > 0 && offset_est >= 0)
774 limit_tuples = (double) count_est + (double) offset_est;
777 if (parse->setOperations)
779 List *set_sortclauses;
782 * If there's a top-level ORDER BY, assume we have to fetch all the
783 * tuples. This might seem too simplistic given all the hackery below
784 * to possibly avoid the sort ... but a nonzero tuple_fraction is only
785 * of use to plan_set_operations() when the setop is UNION ALL, and
786 * the result of UNION ALL is always unsorted.
788 if (parse->sortClause)
789 tuple_fraction = 0.0;
792 * Construct the plan for set operations. The result will not need
793 * any work except perhaps a top-level sort and/or LIMIT.
795 result_plan = plan_set_operations(root, tuple_fraction,
799 * Calculate pathkeys representing the sort order (if any) of the set
800 * operation's result. We have to do this before overwriting the sort
803 current_pathkeys = make_pathkeys_for_sortclauses(root,
805 result_plan->targetlist,
809 * We should not need to call preprocess_targetlist, since we must be
810 * in a SELECT query node. Instead, use the targetlist returned by
811 * plan_set_operations (since this tells whether it returned any
812 * resjunk columns!), and transfer any sort key information from the
815 Assert(parse->commandType == CMD_SELECT);
817 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
820 * Can't handle FOR UPDATE/SHARE here (parser should have checked
821 * already, but let's make sure).
825 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
826 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
829 * Calculate pathkeys that represent result ordering requirements
831 Assert(parse->distinctClause == NIL);
832 sort_pathkeys = make_pathkeys_for_sortclauses(root,
839 /* No set operations, do regular planning */
841 List *group_pathkeys;
842 AttrNumber *groupColIdx = NULL;
843 bool need_tlist_eval = true;
849 AggClauseCounts agg_counts;
851 bool use_hashed_grouping = false;
853 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
855 /* Preprocess GROUP BY clause, if any */
856 if (parse->groupClause)
857 preprocess_groupclause(root);
858 numGroupCols = list_length(parse->groupClause);
860 /* Preprocess targetlist */
861 tlist = preprocess_targetlist(root, tlist);
864 * Generate appropriate target list for subplan; may be different from
865 * tlist if grouping or aggregation is needed.
867 sub_tlist = make_subplanTargetList(root, tlist,
868 &groupColIdx, &need_tlist_eval);
871 * Calculate pathkeys that represent grouping/ordering requirements.
872 * Stash them in PlannerInfo so that query_planner can canonicalize
873 * them after EquivalenceClasses have been formed.
875 * Note: for the moment, DISTINCT is always implemented via sort/uniq,
876 * and we set the sort_pathkeys to be the more rigorous of the
877 * DISTINCT and ORDER BY requirements. This should be changed
878 * someday, but DISTINCT ON is a bit of a problem ...
880 if (parse->groupClause && grouping_is_sortable(parse->groupClause))
881 root->group_pathkeys =
882 make_pathkeys_for_sortclauses(root,
887 root->group_pathkeys = NIL;
889 if (list_length(parse->distinctClause) > list_length(parse->sortClause))
890 root->sort_pathkeys =
891 make_pathkeys_for_sortclauses(root,
892 parse->distinctClause,
896 root->sort_pathkeys =
897 make_pathkeys_for_sortclauses(root,
903 * Will need actual number of aggregates for estimating costs.
905 * Note: we do not attempt to detect duplicate aggregates here; a
906 * somewhat-overestimated count is okay for our present purposes.
908 * Note: think not that we can turn off hasAggs if we find no aggs. It
909 * is possible for constant-expression simplification to remove all
910 * explicit references to aggs, but we still have to follow the
911 * aggregate semantics (eg, producing only one output row).
915 count_agg_clauses((Node *) tlist, &agg_counts);
916 count_agg_clauses(parse->havingQual, &agg_counts);
920 * Figure out whether we need a sorted result from query_planner.
922 * If we have a sortable GROUP BY clause, then we want a result sorted
923 * properly for grouping. Otherwise, if there is an ORDER BY clause,
924 * we want to sort by the ORDER BY clause. (Note: if we have both, and
925 * ORDER BY is a superset of GROUP BY, it would be tempting to request
926 * sort by ORDER BY --- but that might just leave us failing to
927 * exploit an available sort order at all. Needs more thought...)
929 if (root->group_pathkeys)
930 root->query_pathkeys = root->group_pathkeys;
931 else if (root->sort_pathkeys)
932 root->query_pathkeys = root->sort_pathkeys;
934 root->query_pathkeys = NIL;
937 * Generate the best unsorted and presorted paths for this Query (but
938 * note there may not be any presorted path). query_planner will also
939 * estimate the number of groups in the query, and canonicalize all
942 query_planner(root, sub_tlist, tuple_fraction, limit_tuples,
943 &cheapest_path, &sorted_path, &dNumGroups);
945 group_pathkeys = root->group_pathkeys;
946 sort_pathkeys = root->sort_pathkeys;
949 * If grouping, decide whether to use sorted or hashed grouping.
951 if (parse->groupClause)
957 * Executor doesn't support hashed aggregation with DISTINCT
958 * aggregates. (Doing so would imply storing *all* the input
959 * values in the hash table, which seems like a certain loser.)
961 can_hash = (agg_counts.numDistinctAggs == 0 &&
962 grouping_is_hashable(parse->groupClause));
963 can_sort = grouping_is_sortable(parse->groupClause);
964 if (can_hash && can_sort)
966 /* we have a meaningful choice to make ... */
967 use_hashed_grouping =
968 choose_hashed_grouping(root,
969 tuple_fraction, limit_tuples,
970 cheapest_path, sorted_path,
971 dNumGroups, &agg_counts);
974 use_hashed_grouping = true;
976 use_hashed_grouping = false;
979 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
980 errmsg("could not implement GROUP BY"),
981 errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
983 /* Also convert # groups to long int --- but 'ware overflow! */
984 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
988 * Select the best path. If we are doing hashed grouping, we will
989 * always read all the input tuples, so use the cheapest-total path.
990 * Otherwise, trust query_planner's decision about which to use.
992 if (use_hashed_grouping || !sorted_path)
993 best_path = cheapest_path;
995 best_path = sorted_path;
998 * Check to see if it's possible to optimize MIN/MAX aggregates. If
999 * so, we will forget all the work we did so far to choose a "regular"
1000 * path ... but we had to do it anyway to be able to tell which way is
1003 result_plan = optimize_minmax_aggregates(root,
1006 if (result_plan != NULL)
1009 * optimize_minmax_aggregates generated the full plan, with the
1010 * right tlist, and it has no sort order.
1012 current_pathkeys = NIL;
1017 * Normal case --- create a plan according to query_planner's
1020 bool need_sort_for_grouping = false;
1022 result_plan = create_plan(root, best_path);
1023 current_pathkeys = best_path->pathkeys;
1025 /* Detect if we'll need an explicit sort for grouping */
1026 if (parse->groupClause && !use_hashed_grouping &&
1027 !pathkeys_contained_in(group_pathkeys, current_pathkeys))
1029 need_sort_for_grouping = true;
1031 * Always override query_planner's tlist, so that we don't
1032 * sort useless data from a "physical" tlist.
1034 need_tlist_eval = true;
1038 * create_plan() returns a plan with just a "flat" tlist of
1039 * required Vars. Usually we need to insert the sub_tlist as the
1040 * tlist of the top plan node. However, we can skip that if we
1041 * determined that whatever query_planner chose to return will be
1044 if (need_tlist_eval)
1047 * If the top-level plan node is one that cannot do expression
1048 * evaluation, we must insert a Result node to project the
1051 if (!is_projection_capable_plan(result_plan))
1053 result_plan = (Plan *) make_result(root,
1061 * Otherwise, just replace the subplan's flat tlist with
1062 * the desired tlist.
1064 result_plan->targetlist = sub_tlist;
1068 * Also, account for the cost of evaluation of the sub_tlist.
1070 * Up to now, we have only been dealing with "flat" tlists,
1071 * containing just Vars. So their evaluation cost is zero
1072 * according to the model used by cost_qual_eval() (or if you
1073 * prefer, the cost is factored into cpu_tuple_cost). Thus we
1074 * can avoid accounting for tlist cost throughout
1075 * query_planner() and subroutines. But now we've inserted a
1076 * tlist that might contain actual operators, sub-selects, etc
1077 * --- so we'd better account for its cost.
1079 * Below this point, any tlist eval cost for added-on nodes
1080 * should be accounted for as we create those nodes.
1081 * Presently, of the node types we can add on, only Agg and
1082 * Group project new tlists (the rest just copy their input
1083 * tuples) --- so make_agg() and make_group() are responsible
1084 * for computing the added cost.
1086 cost_qual_eval(&tlist_cost, sub_tlist, root);
1087 result_plan->startup_cost += tlist_cost.startup;
1088 result_plan->total_cost += tlist_cost.startup +
1089 tlist_cost.per_tuple * result_plan->plan_rows;
1094 * Since we're using query_planner's tlist and not the one
1095 * make_subplanTargetList calculated, we have to refigure any
1096 * grouping-column indexes make_subplanTargetList computed.
1098 locate_grouping_columns(root, tlist, result_plan->targetlist,
1103 * Insert AGG or GROUP node if needed, plus an explicit sort step
1106 * HAVING clause, if any, becomes qual of the Agg or Group node.
1108 if (use_hashed_grouping)
1110 /* Hashed aggregate plan --- no sort needed */
1111 result_plan = (Plan *) make_agg(root,
1113 (List *) parse->havingQual,
1117 extract_grouping_ops(parse->groupClause),
1121 /* Hashed aggregation produces randomly-ordered results */
1122 current_pathkeys = NIL;
1124 else if (parse->hasAggs)
1126 /* Plain aggregate plan --- sort if needed */
1127 AggStrategy aggstrategy;
1129 if (parse->groupClause)
1131 if (need_sort_for_grouping)
1133 result_plan = (Plan *)
1134 make_sort_from_groupcols(root,
1138 current_pathkeys = group_pathkeys;
1140 aggstrategy = AGG_SORTED;
1143 * The AGG node will not change the sort ordering of its
1144 * groups, so current_pathkeys describes the result too.
1149 aggstrategy = AGG_PLAIN;
1150 /* Result will be only one row anyway; no sort order */
1151 current_pathkeys = NIL;
1154 result_plan = (Plan *) make_agg(root,
1156 (List *) parse->havingQual,
1160 extract_grouping_ops(parse->groupClause),
1165 else if (parse->groupClause)
1168 * GROUP BY without aggregation, so insert a group node (plus
1169 * the appropriate sort node, if necessary).
1171 * Add an explicit sort if we couldn't make the path come out
1172 * the way the GROUP node needs it.
1174 if (need_sort_for_grouping)
1176 result_plan = (Plan *)
1177 make_sort_from_groupcols(root,
1181 current_pathkeys = group_pathkeys;
1184 result_plan = (Plan *) make_group(root,
1186 (List *) parse->havingQual,
1189 extract_grouping_ops(parse->groupClause),
1192 /* The Group node won't change sort ordering */
1194 else if (root->hasHavingQual)
1197 * No aggregates, and no GROUP BY, but we have a HAVING qual.
1198 * This is a degenerate case in which we are supposed to emit
1199 * either 0 or 1 row depending on whether HAVING succeeds.
1200 * Furthermore, there cannot be any variables in either HAVING
1201 * or the targetlist, so we actually do not need the FROM
1202 * table at all! We can just throw away the plan-so-far and
1203 * generate a Result node. This is a sufficiently unusual
1204 * corner case that it's not worth contorting the structure of
1205 * this routine to avoid having to generate the plan in the
1208 result_plan = (Plan *) make_result(root,
1213 } /* end of non-minmax-aggregate case */
1214 } /* end of if (setOperations) */
1217 * If we were not able to make the plan come out in the right order, add
1218 * an explicit sort step.
1222 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1224 result_plan = (Plan *) make_sort_from_pathkeys(root,
1228 current_pathkeys = sort_pathkeys;
1233 * If there is a DISTINCT clause, add the UNIQUE node.
1235 if (parse->distinctClause)
1237 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1240 * If there was grouping or aggregation, leave plan_rows as-is (ie,
1241 * assume the result was already mostly unique). If not, use the
1242 * number of distinct-groups calculated by query_planner.
1244 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1245 result_plan->plan_rows = dNumGroups;
1249 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1251 if (parse->limitCount || parse->limitOffset)
1253 result_plan = (Plan *) make_limit(result_plan,
1261 * Deal with the RETURNING clause if any. It's convenient to pass the
1262 * returningList through setrefs.c now rather than at top level (if we
1263 * waited, handling inherited UPDATE/DELETE would be much harder).
1265 if (parse->returningList)
1269 Assert(parse->resultRelation);
1270 rlist = set_returning_clause_references(root->glob,
1271 parse->returningList,
1273 parse->resultRelation);
1274 root->returningLists = list_make1(rlist);
1277 root->returningLists = NIL;
1279 /* Compute result-relations list if needed */
1280 if (parse->resultRelation)
1281 root->resultRelations = list_make1_int(parse->resultRelation);
1283 root->resultRelations = NIL;
1286 * Return the actual output ordering in query_pathkeys for possible use by
1287 * an outer query level.
1289 root->query_pathkeys = current_pathkeys;
1295 * Detect whether a plan node is a "dummy" plan created when a relation
1296 * is deemed not to need scanning due to constraint exclusion.
1298 * Currently, such dummy plans are Result nodes with constant FALSE
1302 is_dummy_plan(Plan *plan)
1304 if (IsA(plan, Result))
1306 List *rcqual = (List *) ((Result *) plan)->resconstantqual;
1308 if (list_length(rcqual) == 1)
1310 Const *constqual = (Const *) linitial(rcqual);
1312 if (constqual && IsA(constqual, Const))
1314 if (!constqual->constisnull &&
1315 !DatumGetBool(constqual->constvalue))
1324 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1326 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1327 * results back in *count_est and *offset_est. These variables are set to
1328 * 0 if the corresponding clause is not present, and -1 if it's present
1329 * but we couldn't estimate the value for it. (The "0" convention is OK
1330 * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1331 * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
1332 * usual practice of never estimating less than one row.) These values will
1333 * be passed to make_limit, which see if you change this code.
1335 * The return value is the suitably adjusted tuple_fraction to use for
1336 * planning the query. This adjustment is not overridable, since it reflects
1337 * plan actions that grouping_planner() will certainly take, not assumptions
1341 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1342 int64 *offset_est, int64 *count_est)
1344 Query *parse = root->parse;
1346 double limit_fraction;
1348 /* Should not be called unless LIMIT or OFFSET */
1349 Assert(parse->limitCount || parse->limitOffset);
1352 * Try to obtain the clause values. We use estimate_expression_value
1353 * primarily because it can sometimes do something useful with Params.
1355 if (parse->limitCount)
1357 est = estimate_expression_value(root, parse->limitCount);
1358 if (est && IsA(est, Const))
1360 if (((Const *) est)->constisnull)
1362 /* NULL indicates LIMIT ALL, ie, no limit */
1363 *count_est = 0; /* treat as not present */
1367 *count_est = DatumGetInt64(((Const *) est)->constvalue);
1368 if (*count_est <= 0)
1369 *count_est = 1; /* force to at least 1 */
1373 *count_est = -1; /* can't estimate */
1376 *count_est = 0; /* not present */
1378 if (parse->limitOffset)
1380 est = estimate_expression_value(root, parse->limitOffset);
1381 if (est && IsA(est, Const))
1383 if (((Const *) est)->constisnull)
1385 /* Treat NULL as no offset; the executor will too */
1386 *offset_est = 0; /* treat as not present */
1390 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
1391 if (*offset_est < 0)
1392 *offset_est = 0; /* less than 0 is same as 0 */
1396 *offset_est = -1; /* can't estimate */
1399 *offset_est = 0; /* not present */
1401 if (*count_est != 0)
1404 * A LIMIT clause limits the absolute number of tuples returned.
1405 * However, if it's not a constant LIMIT then we have to guess; for
1406 * lack of a better idea, assume 10% of the plan's result is wanted.
1408 if (*count_est < 0 || *offset_est < 0)
1410 /* LIMIT or OFFSET is an expression ... punt ... */
1411 limit_fraction = 0.10;
1415 /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
1416 limit_fraction = (double) *count_est + (double) *offset_est;
1420 * If we have absolute limits from both caller and LIMIT, use the
1421 * smaller value; likewise if they are both fractional. If one is
1422 * fractional and the other absolute, we can't easily determine which
1423 * is smaller, but we use the heuristic that the absolute will usually
1426 if (tuple_fraction >= 1.0)
1428 if (limit_fraction >= 1.0)
1431 tuple_fraction = Min(tuple_fraction, limit_fraction);
1435 /* caller absolute, limit fractional; use caller's value */
1438 else if (tuple_fraction > 0.0)
1440 if (limit_fraction >= 1.0)
1442 /* caller fractional, limit absolute; use limit */
1443 tuple_fraction = limit_fraction;
1447 /* both fractional */
1448 tuple_fraction = Min(tuple_fraction, limit_fraction);
1453 /* no info from caller, just use limit */
1454 tuple_fraction = limit_fraction;
1457 else if (*offset_est != 0 && tuple_fraction > 0.0)
1460 * We have an OFFSET but no LIMIT. This acts entirely differently
1461 * from the LIMIT case: here, we need to increase rather than decrease
1462 * the caller's tuple_fraction, because the OFFSET acts to cause more
1463 * tuples to be fetched instead of fewer. This only matters if we got
1464 * a tuple_fraction > 0, however.
1466 * As above, use 10% if OFFSET is present but unestimatable.
1468 if (*offset_est < 0)
1469 limit_fraction = 0.10;
1471 limit_fraction = (double) *offset_est;
1474 * If we have absolute counts from both caller and OFFSET, add them
1475 * together; likewise if they are both fractional. If one is
1476 * fractional and the other absolute, we want to take the larger, and
1477 * we heuristically assume that's the fractional one.
1479 if (tuple_fraction >= 1.0)
1481 if (limit_fraction >= 1.0)
1483 /* both absolute, so add them together */
1484 tuple_fraction += limit_fraction;
1488 /* caller absolute, limit fractional; use limit */
1489 tuple_fraction = limit_fraction;
1494 if (limit_fraction >= 1.0)
1496 /* caller fractional, limit absolute; use caller's value */
1500 /* both fractional, so add them together */
1501 tuple_fraction += limit_fraction;
1502 if (tuple_fraction >= 1.0)
1503 tuple_fraction = 0.0; /* assume fetch all */
1508 return tuple_fraction;
1513 * preprocess_groupclause - do preparatory work on GROUP BY clause
1515 * The idea here is to adjust the ordering of the GROUP BY elements
1516 * (which in itself is semantically insignificant) to match ORDER BY,
1517 * thereby allowing a single sort operation to both implement the ORDER BY
1518 * requirement and set up for a Unique step that implements GROUP BY.
1520 * In principle it might be interesting to consider other orderings of the
1521 * GROUP BY elements, which could match the sort ordering of other
1522 * possible plans (eg an indexscan) and thereby reduce cost. We don't
1523 * bother with that, though. Hashed grouping will frequently win anyway.
1525 * Note: we need no comparable processing of the distinctClause because
1526 * the parser already enforced that that matches ORDER BY.
1529 preprocess_groupclause(PlannerInfo *root)
1531 Query *parse = root->parse;
1532 List *new_groupclause;
1537 /* If no ORDER BY, nothing useful to do here */
1538 if (parse->sortClause == NIL)
1542 * Scan the ORDER BY clause and construct a list of matching GROUP BY
1543 * items, but only as far as we can make a matching prefix.
1545 * This code assumes that the sortClause contains no duplicate items.
1547 new_groupclause = NIL;
1548 foreach(sl, parse->sortClause)
1550 SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
1552 foreach(gl, parse->groupClause)
1554 SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
1558 new_groupclause = lappend(new_groupclause, gc);
1563 break; /* no match, so stop scanning */
1566 /* Did we match all of the ORDER BY list, or just some of it? */
1567 partial_match = (sl != NULL);
1569 /* If no match at all, no point in reordering GROUP BY */
1570 if (new_groupclause == NIL)
1574 * Add any remaining GROUP BY items to the new list, but only if we
1575 * were able to make a complete match. In other words, we only
1576 * rearrange the GROUP BY list if the result is that one list is a
1577 * prefix of the other --- otherwise there's no possibility of a
1578 * common sort. Also, give up if there are any non-sortable GROUP BY
1579 * items, since then there's no hope anyway.
1581 foreach(gl, parse->groupClause)
1583 SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
1585 if (list_member_ptr(new_groupclause, gc))
1586 continue; /* it matched an ORDER BY item */
1588 return; /* give up, no common sort possible */
1589 if (!OidIsValid(gc->sortop))
1590 return; /* give up, GROUP BY can't be sorted */
1591 new_groupclause = lappend(new_groupclause, gc);
1594 /* Success --- install the rearranged GROUP BY list */
1595 Assert(list_length(parse->groupClause) == list_length(new_groupclause));
1596 parse->groupClause = new_groupclause;
1600 * extract_grouping_ops - make an array of the equality operator OIDs
1601 * for a SortGroupClause list
1604 extract_grouping_ops(List *groupClause)
1606 int numCols = list_length(groupClause);
1608 Oid *groupOperators;
1611 groupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
1613 foreach(glitem, groupClause)
1615 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1617 groupOperators[colno] = groupcl->eqop;
1618 Assert(OidIsValid(groupOperators[colno]));
1622 return groupOperators;
1626 * grouping_is_sortable - is it possible to implement grouping list by sorting?
1628 * This is easy since the parser will have included a sortop if one exists.
1631 grouping_is_sortable(List *groupClause)
1635 foreach(glitem, groupClause)
1637 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1639 if (!OidIsValid(groupcl->sortop))
1646 * grouping_is_hashable - is it possible to implement grouping list by hashing?
1648 * We assume hashing is OK if the equality operators are marked oprcanhash.
1649 * (If there isn't actually a supporting hash function, the executor will
1650 * complain at runtime; but this is a misdeclaration of the operator, not
1654 grouping_is_hashable(List *groupClause)
1658 foreach(glitem, groupClause)
1660 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1662 if (!op_hashjoinable(groupcl->eqop))
1669 * choose_hashed_grouping - should we use hashed grouping?
1671 * Note: this is only applied when both alternatives are actually feasible.
1674 choose_hashed_grouping(PlannerInfo *root,
1675 double tuple_fraction, double limit_tuples,
1676 Path *cheapest_path, Path *sorted_path,
1677 double dNumGroups, AggClauseCounts *agg_counts)
1679 int numGroupCols = list_length(root->parse->groupClause);
1680 double cheapest_path_rows;
1681 int cheapest_path_width;
1683 List *current_pathkeys;
1687 /* Prefer sorting when enable_hashagg is off */
1688 if (!enable_hashagg)
1692 * Don't do it if it doesn't look like the hashtable will fit into
1695 * Beware here of the possibility that cheapest_path->parent is NULL. This
1696 * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
1698 if (cheapest_path->parent)
1700 cheapest_path_rows = cheapest_path->parent->rows;
1701 cheapest_path_width = cheapest_path->parent->width;
1705 cheapest_path_rows = 1; /* assume non-set result */
1706 cheapest_path_width = 100; /* arbitrary */
1709 /* Estimate per-hash-entry space at tuple width... */
1710 hashentrysize = MAXALIGN(cheapest_path_width) + MAXALIGN(sizeof(MinimalTupleData));
1711 /* plus space for pass-by-ref transition values... */
1712 hashentrysize += agg_counts->transitionSpace;
1713 /* plus the per-hash-entry overhead */
1714 hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1716 if (hashentrysize * dNumGroups > work_mem * 1024L)
1720 * See if the estimated cost is no more than doing it the other way. While
1721 * avoiding the need for sorted input is usually a win, the fact that the
1722 * output won't be sorted may be a loss; so we need to do an actual cost
1725 * We need to consider cheapest_path + hashagg [+ final sort] versus
1726 * either cheapest_path [+ sort] + group or agg [+ final sort] or
1727 * presorted_path + group or agg [+ final sort] where brackets indicate a
1728 * step that may not be needed. We assume query_planner() will have
1729 * returned a presorted path only if it's a winner compared to
1730 * cheapest_path for this purpose.
1732 * These path variables are dummies that just hold cost fields; we don't
1733 * make actual Paths for these steps.
1735 cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1736 numGroupCols, dNumGroups,
1737 cheapest_path->startup_cost, cheapest_path->total_cost,
1738 cheapest_path_rows);
1739 /* Result of hashed agg is always unsorted */
1740 if (root->sort_pathkeys)
1741 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
1742 dNumGroups, cheapest_path_width, limit_tuples);
1746 sorted_p.startup_cost = sorted_path->startup_cost;
1747 sorted_p.total_cost = sorted_path->total_cost;
1748 current_pathkeys = sorted_path->pathkeys;
1752 sorted_p.startup_cost = cheapest_path->startup_cost;
1753 sorted_p.total_cost = cheapest_path->total_cost;
1754 current_pathkeys = cheapest_path->pathkeys;
1756 if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1758 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
1759 cheapest_path_rows, cheapest_path_width, -1.0);
1760 current_pathkeys = root->group_pathkeys;
1763 if (root->parse->hasAggs)
1764 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1765 numGroupCols, dNumGroups,
1766 sorted_p.startup_cost, sorted_p.total_cost,
1767 cheapest_path_rows);
1769 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1770 sorted_p.startup_cost, sorted_p.total_cost,
1771 cheapest_path_rows);
1772 /* The Agg or Group node will preserve ordering */
1773 if (root->sort_pathkeys &&
1774 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1775 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
1776 dNumGroups, cheapest_path_width, limit_tuples);
1779 * Now make the decision using the top-level tuple fraction. First we
1780 * have to convert an absolute count (LIMIT) into fractional form.
1782 if (tuple_fraction >= 1.0)
1783 tuple_fraction /= dNumGroups;
1785 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1786 tuple_fraction) < 0)
1788 /* Hashed is cheaper, so use it */
1795 * make_subplanTargetList
1796 * Generate appropriate target list when grouping is required.
1798 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1799 * above the result of query_planner, we typically want to pass a different
1800 * target list to query_planner than the outer plan nodes should have.
1801 * This routine generates the correct target list for the subplan.
1803 * The initial target list passed from the parser already contains entries
1804 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1805 * for variables used only in HAVING clauses; so we need to add those
1806 * variables to the subplan target list. Also, we flatten all expressions
1807 * except GROUP BY items into their component variables; the other expressions
1808 * will be computed by the inserted nodes rather than by the subplan.
1809 * For example, given a query like
1810 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1811 * we want to pass this targetlist to the subplan:
1813 * where the a+b target will be used by the Sort/Group steps, and the
1814 * other targets will be used for computing the final results. (In the
1815 * above example we could theoretically suppress the a and b targets and
1816 * pass down only c,d,a+b, but it's not really worth the trouble to
1817 * eliminate simple var references from the subplan. We will avoid doing
1818 * the extra computation to recompute a+b at the outer level; see
1819 * fix_upper_expr() in setrefs.c.)
1821 * If we are grouping or aggregating, *and* there are no non-Var grouping
1822 * expressions, then the returned tlist is effectively dummy; we do not
1823 * need to force it to be evaluated, because all the Vars it contains
1824 * should be present in the output of query_planner anyway.
1826 * 'tlist' is the query's target list.
1827 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1828 * expressions (if there are any) in the subplan's target list.
1829 * 'need_tlist_eval' is set true if we really need to evaluate the
1832 * The result is the targetlist to be passed to the subplan.
1836 make_subplanTargetList(PlannerInfo *root,
1838 AttrNumber **groupColIdx,
1839 bool *need_tlist_eval)
1841 Query *parse = root->parse;
1846 *groupColIdx = NULL;
1849 * If we're not grouping or aggregating, there's nothing to do here;
1850 * query_planner should receive the unmodified target list.
1852 if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1854 *need_tlist_eval = true;
1859 * Otherwise, start with a "flattened" tlist (having just the vars
1860 * mentioned in the targetlist and HAVING qual --- but not upper- level
1861 * Vars; they will be replaced by Params later on).
1863 sub_tlist = flatten_tlist(tlist);
1864 extravars = pull_var_clause(parse->havingQual, false);
1865 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1866 list_free(extravars);
1867 *need_tlist_eval = false; /* only eval if not flat tlist */
1870 * If grouping, create sub_tlist entries for all GROUP BY expressions
1871 * (GROUP BY items that are simple Vars should be in the list already),
1872 * and make an array showing where the group columns are in the sub_tlist.
1874 numCols = list_length(parse->groupClause);
1878 AttrNumber *grpColIdx;
1881 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1882 *groupColIdx = grpColIdx;
1884 foreach(gl, parse->groupClause)
1886 SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
1887 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1888 TargetEntry *te = NULL;
1891 /* Find or make a matching sub_tlist entry */
1892 foreach(sl, sub_tlist)
1894 te = (TargetEntry *) lfirst(sl);
1895 if (equal(groupexpr, te->expr))
1900 te = makeTargetEntry((Expr *) groupexpr,
1901 list_length(sub_tlist) + 1,
1904 sub_tlist = lappend(sub_tlist, te);
1905 *need_tlist_eval = true; /* it's not flat anymore */
1908 /* and save its resno */
1909 grpColIdx[keyno++] = te->resno;
1917 * locate_grouping_columns
1918 * Locate grouping columns in the tlist chosen by query_planner.
1920 * This is only needed if we don't use the sub_tlist chosen by
1921 * make_subplanTargetList. We have to forget the column indexes found
1922 * by that routine and re-locate the grouping vars in the real sub_tlist.
1925 locate_grouping_columns(PlannerInfo *root,
1928 AttrNumber *groupColIdx)
1934 * No work unless grouping.
1936 if (!root->parse->groupClause)
1938 Assert(groupColIdx == NULL);
1941 Assert(groupColIdx != NULL);
1943 foreach(gl, root->parse->groupClause)
1945 SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
1946 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1947 TargetEntry *te = NULL;
1950 foreach(sl, sub_tlist)
1952 te = (TargetEntry *) lfirst(sl);
1953 if (equal(groupexpr, te->expr))
1957 elog(ERROR, "failed to locate grouping columns");
1959 groupColIdx[keyno++] = te->resno;
1964 * postprocess_setop_tlist
1965 * Fix up targetlist returned by plan_set_operations().
1967 * We need to transpose sort key info from the orig_tlist into new_tlist.
1968 * NOTE: this would not be good enough if we supported resjunk sort keys
1969 * for results of set operations --- then, we'd need to project a whole
1970 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1971 * find any resjunk columns in orig_tlist.
1974 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1977 ListCell *orig_tlist_item = list_head(orig_tlist);
1979 foreach(l, new_tlist)
1981 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1982 TargetEntry *orig_tle;
1984 /* ignore resjunk columns in setop result */
1985 if (new_tle->resjunk)
1988 Assert(orig_tlist_item != NULL);
1989 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1990 orig_tlist_item = lnext(orig_tlist_item);
1991 if (orig_tle->resjunk) /* should not happen */
1992 elog(ERROR, "resjunk output columns are not implemented");
1993 Assert(new_tle->resno == orig_tle->resno);
1994 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1996 if (orig_tlist_item != NULL)
1997 elog(ERROR, "resjunk output columns are not implemented");