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.238 2008/08/05 02:43:17 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 AttrNumber *extract_grouping_cols(List *groupClause, List *tlist);
73 static bool grouping_is_sortable(List *groupClause);
74 static bool grouping_is_hashable(List *groupClause);
75 static bool choose_hashed_grouping(PlannerInfo *root,
76 double tuple_fraction, double limit_tuples,
77 Path *cheapest_path, Path *sorted_path,
78 double dNumGroups, AggClauseCounts *agg_counts);
79 static bool choose_hashed_distinct(PlannerInfo *root,
80 Plan *input_plan, List *input_pathkeys,
81 double tuple_fraction, double limit_tuples,
82 double dNumDistinctRows);
83 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
84 AttrNumber **groupColIdx, bool *need_tlist_eval);
85 static void locate_grouping_columns(PlannerInfo *root,
88 AttrNumber *groupColIdx);
89 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
92 /*****************************************************************************
94 * Query optimizer entry point
96 * To support loadable plugins that monitor or modify planner behavior,
97 * we provide a hook variable that lets a plugin get control before and
98 * after the standard planning process. The plugin would normally call
101 * Note to plugin authors: standard_planner() scribbles on its Query input,
102 * so you'd better copy that data structure if you want to plan more than once.
104 *****************************************************************************/
106 planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
111 result = (*planner_hook) (parse, cursorOptions, boundParams);
113 result = standard_planner(parse, cursorOptions, boundParams);
118 standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
122 double tuple_fraction;
128 /* Cursor options may come from caller or from DECLARE CURSOR stmt */
129 if (parse->utilityStmt &&
130 IsA(parse->utilityStmt, DeclareCursorStmt))
131 cursorOptions |= ((DeclareCursorStmt *) parse->utilityStmt)->options;
134 * Set up global state for this planner invocation. This data is needed
135 * across all levels of sub-Query that might exist in the given command,
136 * so we keep it in a separate struct that's linked to by each per-Query
139 glob = makeNode(PlannerGlobal);
141 glob->boundParams = boundParams;
142 glob->paramlist = NIL;
143 glob->subplans = NIL;
144 glob->subrtables = NIL;
145 glob->rewindPlanIDs = NULL;
146 glob->finalrtable = NIL;
147 glob->relationOids = NIL;
148 glob->transientPlan = false;
150 /* Determine what fraction of the plan is likely to be scanned */
151 if (cursorOptions & CURSOR_OPT_FAST_PLAN)
154 * We have no real idea how many tuples the user will ultimately FETCH
155 * from a cursor, but it is often the case that he doesn't want 'em
156 * all, or would prefer a fast-start plan anyway so that he can
157 * process some of the tuples sooner. Use a GUC parameter to decide
158 * what fraction to optimize for.
160 tuple_fraction = cursor_tuple_fraction;
163 * We document cursor_tuple_fraction as simply being a fraction,
164 * which means the edge cases 0 and 1 have to be treated specially
165 * here. We convert 1 to 0 ("all the tuples") and 0 to a very small
168 if (tuple_fraction >= 1.0)
169 tuple_fraction = 0.0;
170 else if (tuple_fraction <= 0.0)
171 tuple_fraction = 1e-10;
175 /* Default assumption is we need all the tuples */
176 tuple_fraction = 0.0;
179 /* primary planning entry point (may recurse for subqueries) */
180 top_plan = subquery_planner(glob, parse, 1, tuple_fraction, &root);
183 * If creating a plan for a scrollable cursor, make sure it can run
184 * backwards on demand. Add a Material node at the top at need.
186 if (cursorOptions & CURSOR_OPT_SCROLL)
188 if (!ExecSupportsBackwardScan(top_plan))
189 top_plan = materialize_finished_plan(top_plan);
192 /* final cleanup of the plan */
193 Assert(glob->finalrtable == NIL);
194 top_plan = set_plan_references(glob, top_plan, root->parse->rtable);
195 /* ... and the subplans (both regular subplans and initplans) */
196 Assert(list_length(glob->subplans) == list_length(glob->subrtables));
197 forboth(lp, glob->subplans, lr, glob->subrtables)
199 Plan *subplan = (Plan *) lfirst(lp);
200 List *subrtable = (List *) lfirst(lr);
202 lfirst(lp) = set_plan_references(glob, subplan, subrtable);
205 /* build the PlannedStmt result */
206 result = makeNode(PlannedStmt);
208 result->commandType = parse->commandType;
209 result->canSetTag = parse->canSetTag;
210 result->transientPlan = glob->transientPlan;
211 result->planTree = top_plan;
212 result->rtable = glob->finalrtable;
213 result->resultRelations = root->resultRelations;
214 result->utilityStmt = parse->utilityStmt;
215 result->intoClause = parse->intoClause;
216 result->subplans = glob->subplans;
217 result->rewindPlanIDs = glob->rewindPlanIDs;
218 result->returningLists = root->returningLists;
219 result->rowMarks = parse->rowMarks;
220 result->relationOids = glob->relationOids;
221 result->nParamExec = list_length(glob->paramlist);
227 /*--------------------
229 * Invokes the planner on a subquery. We recurse to here for each
230 * sub-SELECT found in the query tree.
232 * glob is the global state for the current planner run.
233 * parse is the querytree produced by the parser & rewriter.
234 * level is the current recursion depth (1 at the top-level Query).
235 * tuple_fraction is the fraction of tuples we expect will be retrieved.
236 * tuple_fraction is interpreted as explained for grouping_planner, below.
238 * If subroot isn't NULL, we pass back the query's final PlannerInfo struct;
239 * among other things this tells the output sort ordering of the plan.
241 * Basically, this routine does the stuff that should only be done once
242 * per Query object. It then calls grouping_planner. At one time,
243 * grouping_planner could be invoked recursively on the same Query object;
244 * that's not currently true, but we keep the separation between the two
245 * routines anyway, in case we need it again someday.
247 * subquery_planner will be called recursively to handle sub-Query nodes
248 * found within the query's expressions and rangetable.
250 * Returns a query plan.
251 *--------------------
254 subquery_planner(PlannerGlobal *glob, Query *parse,
255 Index level, double tuple_fraction,
256 PlannerInfo **subroot)
258 int num_old_subplans = list_length(glob->subplans);
264 /* Create a PlannerInfo data structure for this subquery */
265 root = makeNode(PlannerInfo);
268 root->query_level = level;
269 root->planner_cxt = CurrentMemoryContext;
270 root->init_plans = NIL;
271 root->eq_classes = NIL;
272 root->in_info_list = NIL;
273 root->append_rel_list = NIL;
276 * Look for IN clauses at the top level of WHERE, and transform them into
277 * joins. Note that this step only handles IN clauses originally at top
278 * level of WHERE; if we pull up any subqueries below, their INs are
279 * processed just before pulling them up.
281 if (parse->hasSubLinks)
282 parse->jointree->quals = pull_up_IN_clauses(root,
283 parse->jointree->quals);
286 * Scan the rangetable for set-returning functions, and inline them
287 * if possible (producing subqueries that might get pulled up next).
288 * Recursion issues here are handled in the same way as for IN clauses.
290 inline_set_returning_functions(root);
293 * Check to see if any subqueries in the rangetable can be merged into
296 parse->jointree = (FromExpr *)
297 pull_up_subqueries(root, (Node *) parse->jointree, false, false);
300 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
301 * avoid the expense of doing flatten_join_alias_vars(). Also check for
302 * outer joins --- if none, we can skip reduce_outer_joins() and some
303 * other processing. This must be done after we have done
304 * pull_up_subqueries, of course.
306 * Note: if reduce_outer_joins manages to eliminate all outer joins,
307 * root->hasOuterJoins is not reset currently. This is OK since its
308 * purpose is merely to suppress unnecessary processing in simple cases.
310 root->hasJoinRTEs = false;
311 root->hasOuterJoins = false;
312 foreach(l, parse->rtable)
314 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
316 if (rte->rtekind == RTE_JOIN)
318 root->hasJoinRTEs = true;
319 if (IS_OUTER_JOIN(rte->jointype))
321 root->hasOuterJoins = true;
322 /* Can quit scanning once we find an outer join */
329 * Expand any rangetable entries that are inheritance sets into "append
330 * relations". This can add entries to the rangetable, but they must be
331 * plain base relations not joins, so it's OK (and marginally more
332 * efficient) to do it after checking for join RTEs. We must do it after
333 * pulling up subqueries, else we'd fail to handle inherited tables in
336 expand_inherited_tables(root);
339 * Set hasHavingQual to remember if HAVING clause is present. Needed
340 * because preprocess_expression will reduce a constant-true condition to
341 * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
343 root->hasHavingQual = (parse->havingQual != NULL);
345 /* Clear this flag; might get set in distribute_qual_to_rels */
346 root->hasPseudoConstantQuals = false;
349 * Do expression preprocessing on targetlist and quals.
351 parse->targetList = (List *)
352 preprocess_expression(root, (Node *) parse->targetList,
355 parse->returningList = (List *)
356 preprocess_expression(root, (Node *) parse->returningList,
359 preprocess_qual_conditions(root, (Node *) parse->jointree);
361 parse->havingQual = preprocess_expression(root, parse->havingQual,
364 parse->limitOffset = preprocess_expression(root, parse->limitOffset,
366 parse->limitCount = preprocess_expression(root, parse->limitCount,
369 root->in_info_list = (List *)
370 preprocess_expression(root, (Node *) root->in_info_list,
372 root->append_rel_list = (List *)
373 preprocess_expression(root, (Node *) root->append_rel_list,
376 /* Also need to preprocess expressions for function and values RTEs */
377 foreach(l, parse->rtable)
379 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
381 if (rte->rtekind == RTE_FUNCTION)
382 rte->funcexpr = preprocess_expression(root, rte->funcexpr,
384 else if (rte->rtekind == RTE_VALUES)
385 rte->values_lists = (List *)
386 preprocess_expression(root, (Node *) rte->values_lists,
391 * In some cases we may want to transfer a HAVING clause into WHERE. We
392 * cannot do so if the HAVING clause contains aggregates (obviously) or
393 * volatile functions (since a HAVING clause is supposed to be executed
394 * only once per group). Also, it may be that the clause is so expensive
395 * to execute that we're better off doing it only once per group, despite
396 * the loss of selectivity. This is hard to estimate short of doing the
397 * entire planning process twice, so we use a heuristic: clauses
398 * containing subplans are left in HAVING. Otherwise, we move or copy the
399 * HAVING clause into WHERE, in hopes of eliminating tuples before
400 * aggregation instead of after.
402 * If the query has explicit grouping then we can simply move such a
403 * clause into WHERE; any group that fails the clause will not be in the
404 * output because none of its tuples will reach the grouping or
405 * aggregation stage. Otherwise we must have a degenerate (variable-free)
406 * HAVING clause, which we put in WHERE so that query_planner() can use it
407 * in a gating Result node, but also keep in HAVING to ensure that we
408 * don't emit a bogus aggregated row. (This could be done better, but it
409 * seems not worth optimizing.)
411 * Note that both havingQual and parse->jointree->quals are in
412 * implicitly-ANDed-list form at this point, even though they are declared
416 foreach(l, (List *) parse->havingQual)
418 Node *havingclause = (Node *) lfirst(l);
420 if (contain_agg_clause(havingclause) ||
421 contain_volatile_functions(havingclause) ||
422 contain_subplans(havingclause))
424 /* keep it in HAVING */
425 newHaving = lappend(newHaving, havingclause);
427 else if (parse->groupClause)
429 /* move it to WHERE */
430 parse->jointree->quals = (Node *)
431 lappend((List *) parse->jointree->quals, havingclause);
435 /* put a copy in WHERE, keep it in HAVING */
436 parse->jointree->quals = (Node *)
437 lappend((List *) parse->jointree->quals,
438 copyObject(havingclause));
439 newHaving = lappend(newHaving, havingclause);
442 parse->havingQual = (Node *) newHaving;
445 * If we have any outer joins, try to reduce them to plain inner joins.
446 * This step is most easily done after we've done expression
449 if (root->hasOuterJoins)
450 reduce_outer_joins(root);
453 * Do the main planning. If we have an inherited target relation, that
454 * needs special processing, else go straight to grouping_planner.
456 if (parse->resultRelation &&
457 rt_fetch(parse->resultRelation, parse->rtable)->inh)
458 plan = inheritance_planner(root);
460 plan = grouping_planner(root, tuple_fraction);
463 * If any subplans were generated, or if we're inside a subplan, build
464 * initPlan list and extParam/allParam sets for plan nodes, and attach the
465 * initPlans to the top plan node.
467 if (list_length(glob->subplans) != num_old_subplans ||
468 root->query_level > 1)
469 SS_finalize_plan(root, plan, true);
471 /* Return internal info if caller wants it */
479 * preprocess_expression
480 * Do subquery_planner's preprocessing work for an expression,
481 * which can be a targetlist, a WHERE clause (including JOIN/ON
482 * conditions), or a HAVING clause.
485 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
488 * Fall out quickly if expression is empty. This occurs often enough to
489 * be worth checking. Note that null->null is the correct conversion for
490 * implicit-AND result format, too.
496 * If the query has any join RTEs, replace join alias variables with
497 * base-relation variables. We must do this before sublink processing,
498 * else sublinks expanded out from join aliases wouldn't get processed. We
499 * can skip it in VALUES lists, however, since they can't contain any Vars
502 if (root->hasJoinRTEs && kind != EXPRKIND_VALUES)
503 expr = flatten_join_alias_vars(root, expr);
506 * Simplify constant expressions.
508 * Note: this also flattens nested AND and OR expressions into N-argument
509 * form. All processing of a qual expression after this point must be
510 * careful to maintain AND/OR flatness --- that is, do not generate a tree
511 * with AND directly under AND, nor OR directly under OR.
513 * Because this is a relatively expensive process, we skip it when the
514 * query is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()". The
515 * expression will only be evaluated once anyway, so no point in
516 * pre-simplifying; we can't execute it any faster than the executor can,
517 * and we will waste cycles copying the tree. Notice however that we
518 * still must do it for quals (to get AND/OR flatness); and if we are in a
519 * subquery we should not assume it will be done only once.
521 * For VALUES lists we never do this at all, again on the grounds that we
522 * should optimize for one-time evaluation.
524 if (kind != EXPRKIND_VALUES &&
525 (root->parse->jointree->fromlist != NIL ||
526 kind == EXPRKIND_QUAL ||
527 root->query_level > 1))
528 expr = eval_const_expressions(root, expr);
531 * If it's a qual or havingQual, canonicalize it.
533 if (kind == EXPRKIND_QUAL)
535 expr = (Node *) canonicalize_qual((Expr *) expr);
537 #ifdef OPTIMIZER_DEBUG
538 printf("After canonicalize_qual()\n");
543 /* Expand SubLinks to SubPlans */
544 if (root->parse->hasSubLinks)
545 expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
548 * XXX do not insert anything here unless you have grokked the comments in
549 * SS_replace_correlation_vars ...
552 /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
553 if (root->query_level > 1)
554 expr = SS_replace_correlation_vars(root, expr);
557 * If it's a qual or havingQual, convert it to implicit-AND format. (We
558 * don't want to do this before eval_const_expressions, since the latter
559 * would be unable to simplify a top-level AND correctly. Also,
560 * SS_process_sublinks expects explicit-AND format.)
562 if (kind == EXPRKIND_QUAL)
563 expr = (Node *) make_ands_implicit((Expr *) expr);
569 * preprocess_qual_conditions
570 * Recursively scan the query's jointree and do subquery_planner's
571 * preprocessing work on each qual condition found therein.
574 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
578 if (IsA(jtnode, RangeTblRef))
580 /* nothing to do here */
582 else if (IsA(jtnode, FromExpr))
584 FromExpr *f = (FromExpr *) jtnode;
587 foreach(l, f->fromlist)
588 preprocess_qual_conditions(root, lfirst(l));
590 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
592 else if (IsA(jtnode, JoinExpr))
594 JoinExpr *j = (JoinExpr *) jtnode;
596 preprocess_qual_conditions(root, j->larg);
597 preprocess_qual_conditions(root, j->rarg);
599 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
602 elog(ERROR, "unrecognized node type: %d",
603 (int) nodeTag(jtnode));
607 * inheritance_planner
608 * Generate a plan in the case where the result relation is an
611 * We have to handle this case differently from cases where a source relation
612 * is an inheritance set. Source inheritance is expanded at the bottom of the
613 * plan tree (see allpaths.c), but target inheritance has to be expanded at
614 * the top. The reason is that for UPDATE, each target relation needs a
615 * different targetlist matching its own column set. Also, for both UPDATE
616 * and DELETE, the executor needs the Append plan node at the top, else it
617 * can't keep track of which table is the current target table. Fortunately,
618 * the UPDATE/DELETE target can never be the nullable side of an outer join,
619 * so it's OK to generate the plan this way.
621 * Returns a query plan.
624 inheritance_planner(PlannerInfo *root)
626 Query *parse = root->parse;
627 int parentRTindex = parse->resultRelation;
628 List *subplans = NIL;
629 List *resultRelations = NIL;
630 List *returningLists = NIL;
636 foreach(l, root->append_rel_list)
638 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
641 /* append_rel_list contains all append rels; ignore others */
642 if (appinfo->parent_relid != parentRTindex)
646 * Generate modified query with this rel as target. We have to be
647 * prepared to translate varnos in in_info_list as well as in the
650 memcpy(&subroot, root, sizeof(PlannerInfo));
651 subroot.parse = (Query *)
652 adjust_appendrel_attrs((Node *) parse,
654 subroot.in_info_list = (List *)
655 adjust_appendrel_attrs((Node *) root->in_info_list,
657 subroot.init_plans = NIL;
658 /* There shouldn't be any OJ info to translate, as yet */
659 Assert(subroot.oj_info_list == NIL);
662 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
665 * If this child rel was excluded by constraint exclusion, exclude it
668 if (is_dummy_plan(subplan))
671 /* Save rtable and tlist from first rel for use below */
674 rtable = subroot.parse->rtable;
675 tlist = subplan->targetlist;
678 subplans = lappend(subplans, subplan);
680 /* Make sure any initplans from this rel get into the outer list */
681 root->init_plans = list_concat(root->init_plans, subroot.init_plans);
683 /* Build target-relations list for the executor */
684 resultRelations = lappend_int(resultRelations, appinfo->child_relid);
686 /* Build list of per-relation RETURNING targetlists */
687 if (parse->returningList)
689 Assert(list_length(subroot.returningLists) == 1);
690 returningLists = list_concat(returningLists,
691 subroot.returningLists);
695 root->resultRelations = resultRelations;
696 root->returningLists = returningLists;
698 /* Mark result as unordered (probably unnecessary) */
699 root->query_pathkeys = NIL;
702 * If we managed to exclude every child rel, return a dummy plan
706 root->resultRelations = list_make1_int(parentRTindex);
707 /* although dummy, it must have a valid tlist for executor */
708 tlist = preprocess_targetlist(root, parse->targetList);
709 return (Plan *) make_result(root,
711 (Node *) list_make1(makeBoolConst(false,
717 * Planning might have modified the rangetable, due to changes of the
718 * Query structures inside subquery RTEs. We have to ensure that this
719 * gets propagated back to the master copy. But can't do this until we
720 * are done planning, because all the calls to grouping_planner need
721 * virgin sub-Queries to work from. (We are effectively assuming that
722 * sub-Queries will get planned identically each time, or at least that
723 * the impacts on their rangetables will be the same each time.)
725 * XXX should clean this up someday
727 parse->rtable = rtable;
729 /* Suppress Append if there's only one surviving child rel */
730 if (list_length(subplans) == 1)
731 return (Plan *) linitial(subplans);
733 return (Plan *) make_append(subplans, true, tlist);
736 /*--------------------
738 * Perform planning steps related to grouping, aggregation, etc.
739 * This primarily means adding top-level processing to the basic
740 * query plan produced by query_planner.
742 * tuple_fraction is the fraction of tuples we expect will be retrieved
744 * tuple_fraction is interpreted as follows:
745 * 0: expect all tuples to be retrieved (normal case)
746 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
747 * from the plan to be retrieved
748 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
749 * expected to be retrieved (ie, a LIMIT specification)
751 * Returns a query plan. Also, root->query_pathkeys is returned as the
752 * actual output ordering of the plan (in pathkey format).
753 *--------------------
756 grouping_planner(PlannerInfo *root, double tuple_fraction)
758 Query *parse = root->parse;
759 List *tlist = parse->targetList;
760 int64 offset_est = 0;
762 double limit_tuples = -1.0;
764 List *current_pathkeys;
765 double dNumGroups = 0;
767 /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
768 if (parse->limitCount || parse->limitOffset)
770 tuple_fraction = preprocess_limit(root, tuple_fraction,
771 &offset_est, &count_est);
774 * If we have a known LIMIT, and don't have an unknown OFFSET, we can
775 * estimate the effects of using a bounded sort.
777 if (count_est > 0 && offset_est >= 0)
778 limit_tuples = (double) count_est + (double) offset_est;
781 if (parse->setOperations)
783 List *set_sortclauses;
786 * If there's a top-level ORDER BY, assume we have to fetch all the
787 * tuples. This might seem too simplistic given all the hackery below
788 * to possibly avoid the sort ... but a nonzero tuple_fraction is only
789 * of use to plan_set_operations() when the setop is UNION ALL, and
790 * the result of UNION ALL is always unsorted.
792 if (parse->sortClause)
793 tuple_fraction = 0.0;
796 * Construct the plan for set operations. The result will not need
797 * any work except perhaps a top-level sort and/or LIMIT.
799 result_plan = plan_set_operations(root, tuple_fraction,
803 * Calculate pathkeys representing the sort order (if any) of the set
804 * operation's result. We have to do this before overwriting the sort
807 current_pathkeys = make_pathkeys_for_sortclauses(root,
809 result_plan->targetlist,
813 * We should not need to call preprocess_targetlist, since we must be
814 * in a SELECT query node. Instead, use the targetlist returned by
815 * plan_set_operations (since this tells whether it returned any
816 * resjunk columns!), and transfer any sort key information from the
819 Assert(parse->commandType == CMD_SELECT);
821 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
824 * Can't handle FOR UPDATE/SHARE here (parser should have checked
825 * already, but let's make sure).
829 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
830 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
833 * Calculate pathkeys that represent result ordering requirements
835 Assert(parse->distinctClause == NIL);
836 root->sort_pathkeys = make_pathkeys_for_sortclauses(root,
843 /* No set operations, do regular planning */
845 AttrNumber *groupColIdx = NULL;
846 bool need_tlist_eval = true;
852 AggClauseCounts agg_counts;
854 bool use_hashed_grouping = false;
856 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
858 /* Preprocess GROUP BY clause, if any */
859 if (parse->groupClause)
860 preprocess_groupclause(root);
861 numGroupCols = list_length(parse->groupClause);
863 /* Preprocess targetlist */
864 tlist = preprocess_targetlist(root, tlist);
867 * Generate appropriate target list for subplan; may be different from
868 * tlist if grouping or aggregation is needed.
870 sub_tlist = make_subplanTargetList(root, tlist,
871 &groupColIdx, &need_tlist_eval);
874 * Calculate pathkeys that represent grouping/ordering requirements.
875 * Stash them in PlannerInfo so that query_planner can canonicalize
876 * them after EquivalenceClasses have been formed. The sortClause
877 * is certainly sort-able, but GROUP BY and DISTINCT might not be,
878 * in which case we just leave their pathkeys empty.
880 if (parse->groupClause &&
881 grouping_is_sortable(parse->groupClause))
882 root->group_pathkeys =
883 make_pathkeys_for_sortclauses(root,
888 root->group_pathkeys = NIL;
890 if (parse->distinctClause &&
891 grouping_is_sortable(parse->distinctClause))
892 root->distinct_pathkeys =
893 make_pathkeys_for_sortclauses(root,
894 parse->distinctClause,
898 root->distinct_pathkeys = NIL;
900 root->sort_pathkeys =
901 make_pathkeys_for_sortclauses(root,
907 * Will need actual number of aggregates for estimating costs.
909 * Note: we do not attempt to detect duplicate aggregates here; a
910 * somewhat-overestimated count is okay for our present purposes.
912 * Note: think not that we can turn off hasAggs if we find no aggs. It
913 * is possible for constant-expression simplification to remove all
914 * explicit references to aggs, but we still have to follow the
915 * aggregate semantics (eg, producing only one output row).
919 count_agg_clauses((Node *) tlist, &agg_counts);
920 count_agg_clauses(parse->havingQual, &agg_counts);
924 * Figure out whether we want a sorted result from query_planner.
926 * If we have a sortable GROUP BY clause, then we want a result sorted
927 * properly for grouping. Otherwise, if there's a sortable DISTINCT
928 * clause that's more rigorous than the ORDER BY clause, we try to
929 * produce output that's sufficiently well sorted for the DISTINCT.
930 * Otherwise, if there is an ORDER BY clause, we want to sort by the
933 * Note: if we have both ORDER BY and GROUP BY, and ORDER BY is a
934 * superset of GROUP BY, it would be tempting to request sort by ORDER
935 * BY --- but that might just leave us failing to exploit an available
936 * sort order at all. Needs more thought. The choice for DISTINCT
937 * versus ORDER BY is much easier, since we know that the parser
938 * ensured that one is a superset of the other.
940 if (root->group_pathkeys)
941 root->query_pathkeys = root->group_pathkeys;
942 else if (list_length(root->distinct_pathkeys) >
943 list_length(root->sort_pathkeys))
944 root->query_pathkeys = root->distinct_pathkeys;
945 else if (root->sort_pathkeys)
946 root->query_pathkeys = root->sort_pathkeys;
948 root->query_pathkeys = NIL;
951 * Generate the best unsorted and presorted paths for this Query (but
952 * note there may not be any presorted path). query_planner will also
953 * estimate the number of groups in the query, and canonicalize all
956 query_planner(root, sub_tlist, tuple_fraction, limit_tuples,
957 &cheapest_path, &sorted_path, &dNumGroups);
960 * If grouping, decide whether to use sorted or hashed grouping.
962 if (parse->groupClause)
968 * Executor doesn't support hashed aggregation with DISTINCT
969 * aggregates. (Doing so would imply storing *all* the input
970 * values in the hash table, which seems like a certain loser.)
972 can_hash = (agg_counts.numDistinctAggs == 0 &&
973 grouping_is_hashable(parse->groupClause));
974 can_sort = grouping_is_sortable(parse->groupClause);
975 if (can_hash && can_sort)
977 /* we have a meaningful choice to make ... */
978 use_hashed_grouping =
979 choose_hashed_grouping(root,
980 tuple_fraction, limit_tuples,
981 cheapest_path, sorted_path,
982 dNumGroups, &agg_counts);
985 use_hashed_grouping = true;
987 use_hashed_grouping = false;
990 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
991 errmsg("could not implement GROUP BY"),
992 errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
994 /* Also convert # groups to long int --- but 'ware overflow! */
995 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
999 * Select the best path. If we are doing hashed grouping, we will
1000 * always read all the input tuples, so use the cheapest-total path.
1001 * Otherwise, trust query_planner's decision about which to use.
1003 if (use_hashed_grouping || !sorted_path)
1004 best_path = cheapest_path;
1006 best_path = sorted_path;
1009 * Check to see if it's possible to optimize MIN/MAX aggregates. If
1010 * so, we will forget all the work we did so far to choose a "regular"
1011 * path ... but we had to do it anyway to be able to tell which way is
1014 result_plan = optimize_minmax_aggregates(root,
1017 if (result_plan != NULL)
1020 * optimize_minmax_aggregates generated the full plan, with the
1021 * right tlist, and it has no sort order.
1023 current_pathkeys = NIL;
1028 * Normal case --- create a plan according to query_planner's
1031 bool need_sort_for_grouping = false;
1033 result_plan = create_plan(root, best_path);
1034 current_pathkeys = best_path->pathkeys;
1036 /* Detect if we'll need an explicit sort for grouping */
1037 if (parse->groupClause && !use_hashed_grouping &&
1038 !pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1040 need_sort_for_grouping = true;
1042 * Always override query_planner's tlist, so that we don't
1043 * sort useless data from a "physical" tlist.
1045 need_tlist_eval = true;
1049 * create_plan() returns a plan with just a "flat" tlist of
1050 * required Vars. Usually we need to insert the sub_tlist as the
1051 * tlist of the top plan node. However, we can skip that if we
1052 * determined that whatever query_planner chose to return will be
1055 if (need_tlist_eval)
1058 * If the top-level plan node is one that cannot do expression
1059 * evaluation, we must insert a Result node to project the
1062 if (!is_projection_capable_plan(result_plan))
1064 result_plan = (Plan *) make_result(root,
1072 * Otherwise, just replace the subplan's flat tlist with
1073 * the desired tlist.
1075 result_plan->targetlist = sub_tlist;
1079 * Also, account for the cost of evaluation of the sub_tlist.
1081 * Up to now, we have only been dealing with "flat" tlists,
1082 * containing just Vars. So their evaluation cost is zero
1083 * according to the model used by cost_qual_eval() (or if you
1084 * prefer, the cost is factored into cpu_tuple_cost). Thus we
1085 * can avoid accounting for tlist cost throughout
1086 * query_planner() and subroutines. But now we've inserted a
1087 * tlist that might contain actual operators, sub-selects, etc
1088 * --- so we'd better account for its cost.
1090 * Below this point, any tlist eval cost for added-on nodes
1091 * should be accounted for as we create those nodes.
1092 * Presently, of the node types we can add on, only Agg and
1093 * Group project new tlists (the rest just copy their input
1094 * tuples) --- so make_agg() and make_group() are responsible
1095 * for computing the added cost.
1097 cost_qual_eval(&tlist_cost, sub_tlist, root);
1098 result_plan->startup_cost += tlist_cost.startup;
1099 result_plan->total_cost += tlist_cost.startup +
1100 tlist_cost.per_tuple * result_plan->plan_rows;
1105 * Since we're using query_planner's tlist and not the one
1106 * make_subplanTargetList calculated, we have to refigure any
1107 * grouping-column indexes make_subplanTargetList computed.
1109 locate_grouping_columns(root, tlist, result_plan->targetlist,
1114 * Insert AGG or GROUP node if needed, plus an explicit sort step
1117 * HAVING clause, if any, becomes qual of the Agg or Group node.
1119 if (use_hashed_grouping)
1121 /* Hashed aggregate plan --- no sort needed */
1122 result_plan = (Plan *) make_agg(root,
1124 (List *) parse->havingQual,
1128 extract_grouping_ops(parse->groupClause),
1132 /* Hashed aggregation produces randomly-ordered results */
1133 current_pathkeys = NIL;
1135 else if (parse->hasAggs)
1137 /* Plain aggregate plan --- sort if needed */
1138 AggStrategy aggstrategy;
1140 if (parse->groupClause)
1142 if (need_sort_for_grouping)
1144 result_plan = (Plan *)
1145 make_sort_from_groupcols(root,
1149 current_pathkeys = root->group_pathkeys;
1151 aggstrategy = AGG_SORTED;
1154 * The AGG node will not change the sort ordering of its
1155 * groups, so current_pathkeys describes the result too.
1160 aggstrategy = AGG_PLAIN;
1161 /* Result will be only one row anyway; no sort order */
1162 current_pathkeys = NIL;
1165 result_plan = (Plan *) make_agg(root,
1167 (List *) parse->havingQual,
1171 extract_grouping_ops(parse->groupClause),
1176 else if (parse->groupClause)
1179 * GROUP BY without aggregation, so insert a group node (plus
1180 * the appropriate sort node, if necessary).
1182 * Add an explicit sort if we couldn't make the path come out
1183 * the way the GROUP node needs it.
1185 if (need_sort_for_grouping)
1187 result_plan = (Plan *)
1188 make_sort_from_groupcols(root,
1192 current_pathkeys = root->group_pathkeys;
1195 result_plan = (Plan *) make_group(root,
1197 (List *) parse->havingQual,
1200 extract_grouping_ops(parse->groupClause),
1203 /* The Group node won't change sort ordering */
1205 else if (root->hasHavingQual)
1208 * No aggregates, and no GROUP BY, but we have a HAVING qual.
1209 * This is a degenerate case in which we are supposed to emit
1210 * either 0 or 1 row depending on whether HAVING succeeds.
1211 * Furthermore, there cannot be any variables in either HAVING
1212 * or the targetlist, so we actually do not need the FROM
1213 * table at all! We can just throw away the plan-so-far and
1214 * generate a Result node. This is a sufficiently unusual
1215 * corner case that it's not worth contorting the structure of
1216 * this routine to avoid having to generate the plan in the
1219 result_plan = (Plan *) make_result(root,
1224 } /* end of non-minmax-aggregate case */
1225 } /* end of if (setOperations) */
1228 * If there is a DISTINCT clause, add the necessary node(s).
1230 if (parse->distinctClause)
1232 double dNumDistinctRows;
1233 long numDistinctRows;
1234 bool use_hashed_distinct;
1239 * If there was grouping or aggregation, use the current number of
1240 * rows as the estimated number of DISTINCT rows (ie, assume the
1241 * result was already mostly unique). If not, use the number of
1242 * distinct-groups calculated by query_planner.
1244 if (parse->groupClause || root->hasHavingQual || parse->hasAggs)
1245 dNumDistinctRows = result_plan->plan_rows;
1247 dNumDistinctRows = dNumGroups;
1249 /* Also convert to long int --- but 'ware overflow! */
1250 numDistinctRows = (long) Min(dNumDistinctRows, (double) LONG_MAX);
1253 * If we have a sortable DISTINCT ON clause, we always use sorting.
1254 * This enforces the expected behavior of DISTINCT ON.
1256 can_sort = grouping_is_sortable(parse->distinctClause);
1257 if (can_sort && parse->hasDistinctOn)
1258 use_hashed_distinct = false;
1261 can_hash = grouping_is_hashable(parse->distinctClause);
1262 if (can_hash && can_sort)
1264 /* we have a meaningful choice to make ... */
1265 use_hashed_distinct =
1266 choose_hashed_distinct(root,
1267 result_plan, current_pathkeys,
1268 tuple_fraction, limit_tuples,
1272 use_hashed_distinct = true;
1274 use_hashed_distinct = false;
1278 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1279 errmsg("could not implement DISTINCT"),
1280 errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
1281 use_hashed_distinct = false; /* keep compiler quiet */
1285 if (use_hashed_distinct)
1287 /* Hashed aggregate plan --- no sort needed */
1288 result_plan = (Plan *) make_agg(root,
1289 result_plan->targetlist,
1292 list_length(parse->distinctClause),
1293 extract_grouping_cols(parse->distinctClause,
1294 result_plan->targetlist),
1295 extract_grouping_ops(parse->distinctClause),
1299 /* Hashed aggregation produces randomly-ordered results */
1300 current_pathkeys = NIL;
1305 * Use a Unique node to implement DISTINCT. Add an explicit sort
1306 * if we couldn't make the path come out the way the Unique node
1307 * needs it. If we do have to sort, sort by the more rigorous
1308 * of DISTINCT and ORDER BY, to avoid a second sort below.
1310 if (!pathkeys_contained_in(root->distinct_pathkeys,
1313 if (list_length(root->distinct_pathkeys) >=
1314 list_length(root->sort_pathkeys))
1315 current_pathkeys = root->distinct_pathkeys;
1318 current_pathkeys = root->sort_pathkeys;
1319 /* Assert checks that parser didn't mess up... */
1320 Assert(pathkeys_contained_in(root->distinct_pathkeys,
1324 result_plan = (Plan *) make_sort_from_pathkeys(root,
1330 result_plan = (Plan *) make_unique(result_plan,
1331 parse->distinctClause);
1332 result_plan->plan_rows = dNumDistinctRows;
1333 /* The Unique node won't change sort ordering */
1338 * If ORDER BY was given and we were not able to make the plan come out in
1339 * the right order, add an explicit sort step.
1341 if (parse->sortClause)
1343 if (!pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1345 result_plan = (Plan *) make_sort_from_pathkeys(root,
1347 root->sort_pathkeys,
1349 current_pathkeys = root->sort_pathkeys;
1354 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1356 if (parse->limitCount || parse->limitOffset)
1358 result_plan = (Plan *) make_limit(result_plan,
1366 * Deal with the RETURNING clause if any. It's convenient to pass the
1367 * returningList through setrefs.c now rather than at top level (if we
1368 * waited, handling inherited UPDATE/DELETE would be much harder).
1370 if (parse->returningList)
1374 Assert(parse->resultRelation);
1375 rlist = set_returning_clause_references(root->glob,
1376 parse->returningList,
1378 parse->resultRelation);
1379 root->returningLists = list_make1(rlist);
1382 root->returningLists = NIL;
1384 /* Compute result-relations list if needed */
1385 if (parse->resultRelation)
1386 root->resultRelations = list_make1_int(parse->resultRelation);
1388 root->resultRelations = NIL;
1391 * Return the actual output ordering in query_pathkeys for possible use by
1392 * an outer query level.
1394 root->query_pathkeys = current_pathkeys;
1400 * Detect whether a plan node is a "dummy" plan created when a relation
1401 * is deemed not to need scanning due to constraint exclusion.
1403 * Currently, such dummy plans are Result nodes with constant FALSE
1407 is_dummy_plan(Plan *plan)
1409 if (IsA(plan, Result))
1411 List *rcqual = (List *) ((Result *) plan)->resconstantqual;
1413 if (list_length(rcqual) == 1)
1415 Const *constqual = (Const *) linitial(rcqual);
1417 if (constqual && IsA(constqual, Const))
1419 if (!constqual->constisnull &&
1420 !DatumGetBool(constqual->constvalue))
1429 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1431 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1432 * results back in *count_est and *offset_est. These variables are set to
1433 * 0 if the corresponding clause is not present, and -1 if it's present
1434 * but we couldn't estimate the value for it. (The "0" convention is OK
1435 * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1436 * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
1437 * usual practice of never estimating less than one row.) These values will
1438 * be passed to make_limit, which see if you change this code.
1440 * The return value is the suitably adjusted tuple_fraction to use for
1441 * planning the query. This adjustment is not overridable, since it reflects
1442 * plan actions that grouping_planner() will certainly take, not assumptions
1446 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1447 int64 *offset_est, int64 *count_est)
1449 Query *parse = root->parse;
1451 double limit_fraction;
1453 /* Should not be called unless LIMIT or OFFSET */
1454 Assert(parse->limitCount || parse->limitOffset);
1457 * Try to obtain the clause values. We use estimate_expression_value
1458 * primarily because it can sometimes do something useful with Params.
1460 if (parse->limitCount)
1462 est = estimate_expression_value(root, parse->limitCount);
1463 if (est && IsA(est, Const))
1465 if (((Const *) est)->constisnull)
1467 /* NULL indicates LIMIT ALL, ie, no limit */
1468 *count_est = 0; /* treat as not present */
1472 *count_est = DatumGetInt64(((Const *) est)->constvalue);
1473 if (*count_est <= 0)
1474 *count_est = 1; /* force to at least 1 */
1478 *count_est = -1; /* can't estimate */
1481 *count_est = 0; /* not present */
1483 if (parse->limitOffset)
1485 est = estimate_expression_value(root, parse->limitOffset);
1486 if (est && IsA(est, Const))
1488 if (((Const *) est)->constisnull)
1490 /* Treat NULL as no offset; the executor will too */
1491 *offset_est = 0; /* treat as not present */
1495 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
1496 if (*offset_est < 0)
1497 *offset_est = 0; /* less than 0 is same as 0 */
1501 *offset_est = -1; /* can't estimate */
1504 *offset_est = 0; /* not present */
1506 if (*count_est != 0)
1509 * A LIMIT clause limits the absolute number of tuples returned.
1510 * However, if it's not a constant LIMIT then we have to guess; for
1511 * lack of a better idea, assume 10% of the plan's result is wanted.
1513 if (*count_est < 0 || *offset_est < 0)
1515 /* LIMIT or OFFSET is an expression ... punt ... */
1516 limit_fraction = 0.10;
1520 /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
1521 limit_fraction = (double) *count_est + (double) *offset_est;
1525 * If we have absolute limits from both caller and LIMIT, use the
1526 * smaller value; likewise if they are both fractional. If one is
1527 * fractional and the other absolute, we can't easily determine which
1528 * is smaller, but we use the heuristic that the absolute will usually
1531 if (tuple_fraction >= 1.0)
1533 if (limit_fraction >= 1.0)
1536 tuple_fraction = Min(tuple_fraction, limit_fraction);
1540 /* caller absolute, limit fractional; use caller's value */
1543 else if (tuple_fraction > 0.0)
1545 if (limit_fraction >= 1.0)
1547 /* caller fractional, limit absolute; use limit */
1548 tuple_fraction = limit_fraction;
1552 /* both fractional */
1553 tuple_fraction = Min(tuple_fraction, limit_fraction);
1558 /* no info from caller, just use limit */
1559 tuple_fraction = limit_fraction;
1562 else if (*offset_est != 0 && tuple_fraction > 0.0)
1565 * We have an OFFSET but no LIMIT. This acts entirely differently
1566 * from the LIMIT case: here, we need to increase rather than decrease
1567 * the caller's tuple_fraction, because the OFFSET acts to cause more
1568 * tuples to be fetched instead of fewer. This only matters if we got
1569 * a tuple_fraction > 0, however.
1571 * As above, use 10% if OFFSET is present but unestimatable.
1573 if (*offset_est < 0)
1574 limit_fraction = 0.10;
1576 limit_fraction = (double) *offset_est;
1579 * If we have absolute counts from both caller and OFFSET, add them
1580 * together; likewise if they are both fractional. If one is
1581 * fractional and the other absolute, we want to take the larger, and
1582 * we heuristically assume that's the fractional one.
1584 if (tuple_fraction >= 1.0)
1586 if (limit_fraction >= 1.0)
1588 /* both absolute, so add them together */
1589 tuple_fraction += limit_fraction;
1593 /* caller absolute, limit fractional; use limit */
1594 tuple_fraction = limit_fraction;
1599 if (limit_fraction >= 1.0)
1601 /* caller fractional, limit absolute; use caller's value */
1605 /* both fractional, so add them together */
1606 tuple_fraction += limit_fraction;
1607 if (tuple_fraction >= 1.0)
1608 tuple_fraction = 0.0; /* assume fetch all */
1613 return tuple_fraction;
1618 * preprocess_groupclause - do preparatory work on GROUP BY clause
1620 * The idea here is to adjust the ordering of the GROUP BY elements
1621 * (which in itself is semantically insignificant) to match ORDER BY,
1622 * thereby allowing a single sort operation to both implement the ORDER BY
1623 * requirement and set up for a Unique step that implements GROUP BY.
1625 * In principle it might be interesting to consider other orderings of the
1626 * GROUP BY elements, which could match the sort ordering of other
1627 * possible plans (eg an indexscan) and thereby reduce cost. We don't
1628 * bother with that, though. Hashed grouping will frequently win anyway.
1630 * Note: we need no comparable processing of the distinctClause because
1631 * the parser already enforced that that matches ORDER BY.
1634 preprocess_groupclause(PlannerInfo *root)
1636 Query *parse = root->parse;
1637 List *new_groupclause;
1642 /* If no ORDER BY, nothing useful to do here */
1643 if (parse->sortClause == NIL)
1647 * Scan the ORDER BY clause and construct a list of matching GROUP BY
1648 * items, but only as far as we can make a matching prefix.
1650 * This code assumes that the sortClause contains no duplicate items.
1652 new_groupclause = NIL;
1653 foreach(sl, parse->sortClause)
1655 SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
1657 foreach(gl, parse->groupClause)
1659 SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
1663 new_groupclause = lappend(new_groupclause, gc);
1668 break; /* no match, so stop scanning */
1671 /* Did we match all of the ORDER BY list, or just some of it? */
1672 partial_match = (sl != NULL);
1674 /* If no match at all, no point in reordering GROUP BY */
1675 if (new_groupclause == NIL)
1679 * Add any remaining GROUP BY items to the new list, but only if we
1680 * were able to make a complete match. In other words, we only
1681 * rearrange the GROUP BY list if the result is that one list is a
1682 * prefix of the other --- otherwise there's no possibility of a
1683 * common sort. Also, give up if there are any non-sortable GROUP BY
1684 * items, since then there's no hope anyway.
1686 foreach(gl, parse->groupClause)
1688 SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
1690 if (list_member_ptr(new_groupclause, gc))
1691 continue; /* it matched an ORDER BY item */
1693 return; /* give up, no common sort possible */
1694 if (!OidIsValid(gc->sortop))
1695 return; /* give up, GROUP BY can't be sorted */
1696 new_groupclause = lappend(new_groupclause, gc);
1699 /* Success --- install the rearranged GROUP BY list */
1700 Assert(list_length(parse->groupClause) == list_length(new_groupclause));
1701 parse->groupClause = new_groupclause;
1705 * extract_grouping_ops - make an array of the equality operator OIDs
1706 * for a SortGroupClause list
1709 extract_grouping_ops(List *groupClause)
1711 int numCols = list_length(groupClause);
1713 Oid *groupOperators;
1716 groupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
1718 foreach(glitem, groupClause)
1720 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1722 groupOperators[colno] = groupcl->eqop;
1723 Assert(OidIsValid(groupOperators[colno]));
1727 return groupOperators;
1731 * extract_grouping_cols - make an array of the grouping column resnos
1732 * for a SortGroupClause list
1735 extract_grouping_cols(List *groupClause, List *tlist)
1737 AttrNumber *grpColIdx;
1738 int numCols = list_length(groupClause);
1742 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1744 foreach(glitem, groupClause)
1746 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1747 TargetEntry *tle = get_sortgroupclause_tle(groupcl, tlist);
1749 grpColIdx[colno++] = tle->resno;
1756 * grouping_is_sortable - is it possible to implement grouping list by sorting?
1758 * This is easy since the parser will have included a sortop if one exists.
1761 grouping_is_sortable(List *groupClause)
1765 foreach(glitem, groupClause)
1767 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1769 if (!OidIsValid(groupcl->sortop))
1776 * grouping_is_hashable - is it possible to implement grouping list by hashing?
1778 * We assume hashing is OK if the equality operators are marked oprcanhash.
1779 * (If there isn't actually a supporting hash function, the executor will
1780 * complain at runtime; but this is a misdeclaration of the operator, not
1784 grouping_is_hashable(List *groupClause)
1788 foreach(glitem, groupClause)
1790 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1792 if (!op_hashjoinable(groupcl->eqop))
1799 * choose_hashed_grouping - should we use hashed grouping?
1801 * Note: this is only applied when both alternatives are actually feasible.
1804 choose_hashed_grouping(PlannerInfo *root,
1805 double tuple_fraction, double limit_tuples,
1806 Path *cheapest_path, Path *sorted_path,
1807 double dNumGroups, AggClauseCounts *agg_counts)
1809 int numGroupCols = list_length(root->parse->groupClause);
1810 double cheapest_path_rows;
1811 int cheapest_path_width;
1813 List *target_pathkeys;
1814 List *current_pathkeys;
1818 /* Prefer sorting when enable_hashagg is off */
1819 if (!enable_hashagg)
1823 * Don't do it if it doesn't look like the hashtable will fit into
1826 * Beware here of the possibility that cheapest_path->parent is NULL. This
1827 * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
1829 if (cheapest_path->parent)
1831 cheapest_path_rows = cheapest_path->parent->rows;
1832 cheapest_path_width = cheapest_path->parent->width;
1836 cheapest_path_rows = 1; /* assume non-set result */
1837 cheapest_path_width = 100; /* arbitrary */
1840 /* Estimate per-hash-entry space at tuple width... */
1841 hashentrysize = MAXALIGN(cheapest_path_width) + MAXALIGN(sizeof(MinimalTupleData));
1842 /* plus space for pass-by-ref transition values... */
1843 hashentrysize += agg_counts->transitionSpace;
1844 /* plus the per-hash-entry overhead */
1845 hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1847 if (hashentrysize * dNumGroups > work_mem * 1024L)
1851 * When we have both GROUP BY and DISTINCT, use the more-rigorous of
1852 * DISTINCT and ORDER BY as the assumed required output sort order.
1853 * This is an oversimplification because the DISTINCT might get
1854 * implemented via hashing, but it's not clear that the case is common
1855 * enough (or that our estimates are good enough) to justify trying to
1858 if (list_length(root->distinct_pathkeys) >
1859 list_length(root->sort_pathkeys))
1860 target_pathkeys = root->distinct_pathkeys;
1862 target_pathkeys = root->sort_pathkeys;
1865 * See if the estimated cost is no more than doing it the other way. While
1866 * avoiding the need for sorted input is usually a win, the fact that the
1867 * output won't be sorted may be a loss; so we need to do an actual cost
1870 * We need to consider cheapest_path + hashagg [+ final sort] versus
1871 * either cheapest_path [+ sort] + group or agg [+ final sort] or
1872 * presorted_path + group or agg [+ final sort] where brackets indicate a
1873 * step that may not be needed. We assume query_planner() will have
1874 * returned a presorted path only if it's a winner compared to
1875 * cheapest_path for this purpose.
1877 * These path variables are dummies that just hold cost fields; we don't
1878 * make actual Paths for these steps.
1880 cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1881 numGroupCols, dNumGroups,
1882 cheapest_path->startup_cost, cheapest_path->total_cost,
1883 cheapest_path_rows);
1884 /* Result of hashed agg is always unsorted */
1885 if (target_pathkeys)
1886 cost_sort(&hashed_p, root, target_pathkeys, hashed_p.total_cost,
1887 dNumGroups, cheapest_path_width, limit_tuples);
1891 sorted_p.startup_cost = sorted_path->startup_cost;
1892 sorted_p.total_cost = sorted_path->total_cost;
1893 current_pathkeys = sorted_path->pathkeys;
1897 sorted_p.startup_cost = cheapest_path->startup_cost;
1898 sorted_p.total_cost = cheapest_path->total_cost;
1899 current_pathkeys = cheapest_path->pathkeys;
1901 if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1903 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
1904 cheapest_path_rows, cheapest_path_width, -1.0);
1905 current_pathkeys = root->group_pathkeys;
1908 if (root->parse->hasAggs)
1909 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1910 numGroupCols, dNumGroups,
1911 sorted_p.startup_cost, sorted_p.total_cost,
1912 cheapest_path_rows);
1914 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1915 sorted_p.startup_cost, sorted_p.total_cost,
1916 cheapest_path_rows);
1917 /* The Agg or Group node will preserve ordering */
1918 if (target_pathkeys &&
1919 !pathkeys_contained_in(target_pathkeys, current_pathkeys))
1920 cost_sort(&sorted_p, root, target_pathkeys, sorted_p.total_cost,
1921 dNumGroups, cheapest_path_width, limit_tuples);
1924 * Now make the decision using the top-level tuple fraction. First we
1925 * have to convert an absolute count (LIMIT) into fractional form.
1927 if (tuple_fraction >= 1.0)
1928 tuple_fraction /= dNumGroups;
1930 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1931 tuple_fraction) < 0)
1933 /* Hashed is cheaper, so use it */
1940 * choose_hashed_distinct - should we use hashing for DISTINCT?
1942 * This is fairly similar to choose_hashed_grouping, but there are enough
1943 * differences that it doesn't seem worth trying to unify the two functions.
1945 * But note that making the two choices independently is a bit bogus in
1946 * itself. If the two could be combined into a single choice operation
1947 * it'd probably be better, but that seems far too unwieldy to be practical,
1948 * especially considering that the combination of GROUP BY and DISTINCT
1949 * isn't very common in real queries. By separating them, we are giving
1950 * extra preference to using a sorting implementation when a common sort key
1951 * is available ... and that's not necessarily wrong anyway.
1953 * Note: this is only applied when both alternatives are actually feasible.
1956 choose_hashed_distinct(PlannerInfo *root,
1957 Plan *input_plan, List *input_pathkeys,
1958 double tuple_fraction, double limit_tuples,
1959 double dNumDistinctRows)
1961 int numDistinctCols = list_length(root->parse->distinctClause);
1963 List *current_pathkeys;
1967 /* Prefer sorting when enable_hashagg is off */
1968 if (!enable_hashagg)
1972 * Don't do it if it doesn't look like the hashtable will fit into
1975 hashentrysize = MAXALIGN(input_plan->plan_width) + MAXALIGN(sizeof(MinimalTupleData));
1977 if (hashentrysize * dNumDistinctRows > work_mem * 1024L)
1981 * See if the estimated cost is no more than doing it the other way. While
1982 * avoiding the need for sorted input is usually a win, the fact that the
1983 * output won't be sorted may be a loss; so we need to do an actual cost
1986 * We need to consider input_plan + hashagg [+ final sort] versus
1987 * input_plan [+ sort] + group [+ final sort] where brackets indicate
1988 * a step that may not be needed.
1990 * These path variables are dummies that just hold cost fields; we don't
1991 * make actual Paths for these steps.
1993 cost_agg(&hashed_p, root, AGG_HASHED, 0,
1994 numDistinctCols, dNumDistinctRows,
1995 input_plan->startup_cost, input_plan->total_cost,
1996 input_plan->plan_rows);
1998 * Result of hashed agg is always unsorted, so if ORDER BY is present
1999 * we need to charge for the final sort.
2001 if (root->parse->sortClause)
2002 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
2003 dNumDistinctRows, input_plan->plan_width, limit_tuples);
2005 /* Now for the GROUP case ... */
2006 sorted_p.startup_cost = input_plan->startup_cost;
2007 sorted_p.total_cost = input_plan->total_cost;
2008 current_pathkeys = input_pathkeys;
2009 if (!pathkeys_contained_in(root->distinct_pathkeys, current_pathkeys))
2011 /* We don't want to sort twice */
2012 if (list_length(root->distinct_pathkeys) >=
2013 list_length(root->sort_pathkeys))
2014 current_pathkeys = root->distinct_pathkeys;
2016 current_pathkeys = root->sort_pathkeys;
2017 cost_sort(&sorted_p, root, current_pathkeys, sorted_p.total_cost,
2018 input_plan->plan_rows, input_plan->plan_width, -1.0);
2020 cost_group(&sorted_p, root, numDistinctCols, dNumDistinctRows,
2021 sorted_p.startup_cost, sorted_p.total_cost,
2022 input_plan->plan_rows);
2023 if (root->parse->sortClause &&
2024 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
2025 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
2026 dNumDistinctRows, input_plan->plan_width, limit_tuples);
2029 * Now make the decision using the top-level tuple fraction. First we
2030 * have to convert an absolute count (LIMIT) into fractional form.
2032 if (tuple_fraction >= 1.0)
2033 tuple_fraction /= dNumDistinctRows;
2035 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
2036 tuple_fraction) < 0)
2038 /* Hashed is cheaper, so use it */
2045 * make_subplanTargetList
2046 * Generate appropriate target list when grouping is required.
2048 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
2049 * above the result of query_planner, we typically want to pass a different
2050 * target list to query_planner than the outer plan nodes should have.
2051 * This routine generates the correct target list for the subplan.
2053 * The initial target list passed from the parser already contains entries
2054 * for all ORDER BY and GROUP BY expressions, but it will not have entries
2055 * for variables used only in HAVING clauses; so we need to add those
2056 * variables to the subplan target list. Also, we flatten all expressions
2057 * except GROUP BY items into their component variables; the other expressions
2058 * will be computed by the inserted nodes rather than by the subplan.
2059 * For example, given a query like
2060 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
2061 * we want to pass this targetlist to the subplan:
2063 * where the a+b target will be used by the Sort/Group steps, and the
2064 * other targets will be used for computing the final results. (In the
2065 * above example we could theoretically suppress the a and b targets and
2066 * pass down only c,d,a+b, but it's not really worth the trouble to
2067 * eliminate simple var references from the subplan. We will avoid doing
2068 * the extra computation to recompute a+b at the outer level; see
2069 * fix_upper_expr() in setrefs.c.)
2071 * If we are grouping or aggregating, *and* there are no non-Var grouping
2072 * expressions, then the returned tlist is effectively dummy; we do not
2073 * need to force it to be evaluated, because all the Vars it contains
2074 * should be present in the output of query_planner anyway.
2076 * 'tlist' is the query's target list.
2077 * 'groupColIdx' receives an array of column numbers for the GROUP BY
2078 * expressions (if there are any) in the subplan's target list.
2079 * 'need_tlist_eval' is set true if we really need to evaluate the
2082 * The result is the targetlist to be passed to the subplan.
2086 make_subplanTargetList(PlannerInfo *root,
2088 AttrNumber **groupColIdx,
2089 bool *need_tlist_eval)
2091 Query *parse = root->parse;
2096 *groupColIdx = NULL;
2099 * If we're not grouping or aggregating, there's nothing to do here;
2100 * query_planner should receive the unmodified target list.
2102 if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
2104 *need_tlist_eval = true;
2109 * Otherwise, start with a "flattened" tlist (having just the vars
2110 * mentioned in the targetlist and HAVING qual --- but not upper-level
2111 * Vars; they will be replaced by Params later on).
2113 sub_tlist = flatten_tlist(tlist);
2114 extravars = pull_var_clause(parse->havingQual, false);
2115 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
2116 list_free(extravars);
2117 *need_tlist_eval = false; /* only eval if not flat tlist */
2120 * If grouping, create sub_tlist entries for all GROUP BY expressions
2121 * (GROUP BY items that are simple Vars should be in the list already),
2122 * and make an array showing where the group columns are in the sub_tlist.
2124 numCols = list_length(parse->groupClause);
2128 AttrNumber *grpColIdx;
2131 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
2132 *groupColIdx = grpColIdx;
2134 foreach(gl, parse->groupClause)
2136 SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
2137 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
2138 TargetEntry *te = NULL;
2141 * Find or make a matching sub_tlist entry. If the groupexpr
2142 * isn't a Var, no point in searching. (Note that the parser
2143 * won't make multiple groupClause entries for the same TLE.)
2145 if (groupexpr && IsA(groupexpr, Var))
2149 foreach(sl, sub_tlist)
2151 TargetEntry *lte = (TargetEntry *) lfirst(sl);
2153 if (equal(groupexpr, lte->expr))
2162 te = makeTargetEntry((Expr *) groupexpr,
2163 list_length(sub_tlist) + 1,
2166 sub_tlist = lappend(sub_tlist, te);
2167 *need_tlist_eval = true; /* it's not flat anymore */
2170 /* and save its resno */
2171 grpColIdx[keyno++] = te->resno;
2179 * locate_grouping_columns
2180 * Locate grouping columns in the tlist chosen by query_planner.
2182 * This is only needed if we don't use the sub_tlist chosen by
2183 * make_subplanTargetList. We have to forget the column indexes found
2184 * by that routine and re-locate the grouping vars in the real sub_tlist.
2187 locate_grouping_columns(PlannerInfo *root,
2190 AttrNumber *groupColIdx)
2196 * No work unless grouping.
2198 if (!root->parse->groupClause)
2200 Assert(groupColIdx == NULL);
2203 Assert(groupColIdx != NULL);
2205 foreach(gl, root->parse->groupClause)
2207 SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
2208 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
2209 TargetEntry *te = NULL;
2212 foreach(sl, sub_tlist)
2214 te = (TargetEntry *) lfirst(sl);
2215 if (equal(groupexpr, te->expr))
2219 elog(ERROR, "failed to locate grouping columns");
2221 groupColIdx[keyno++] = te->resno;
2226 * postprocess_setop_tlist
2227 * Fix up targetlist returned by plan_set_operations().
2229 * We need to transpose sort key info from the orig_tlist into new_tlist.
2230 * NOTE: this would not be good enough if we supported resjunk sort keys
2231 * for results of set operations --- then, we'd need to project a whole
2232 * new tlist to evaluate the resjunk columns. For now, just ereport if we
2233 * find any resjunk columns in orig_tlist.
2236 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
2239 ListCell *orig_tlist_item = list_head(orig_tlist);
2241 foreach(l, new_tlist)
2243 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
2244 TargetEntry *orig_tle;
2246 /* ignore resjunk columns in setop result */
2247 if (new_tle->resjunk)
2250 Assert(orig_tlist_item != NULL);
2251 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
2252 orig_tlist_item = lnext(orig_tlist_item);
2253 if (orig_tle->resjunk) /* should not happen */
2254 elog(ERROR, "resjunk output columns are not implemented");
2255 Assert(new_tle->resno == orig_tle->resno);
2256 new_tle->ressortgroupref = orig_tle->ressortgroupref;
2258 if (orig_tlist_item != NULL)
2259 elog(ERROR, "resjunk output columns are not implemented");