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.236 2008/08/02 21:32:00 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 choose_hashed_grouping(PlannerInfo *root,
73 double tuple_fraction, double limit_tuples,
74 Path *cheapest_path, Path *sorted_path,
75 Oid *groupOperators, double dNumGroups,
76 AggClauseCounts *agg_counts);
77 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
78 AttrNumber **groupColIdx, bool *need_tlist_eval);
79 static void locate_grouping_columns(PlannerInfo *root,
82 AttrNumber *groupColIdx);
83 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
86 /*****************************************************************************
88 * Query optimizer entry point
90 * To support loadable plugins that monitor or modify planner behavior,
91 * we provide a hook variable that lets a plugin get control before and
92 * after the standard planning process. The plugin would normally call
95 * Note to plugin authors: standard_planner() scribbles on its Query input,
96 * so you'd better copy that data structure if you want to plan more than once.
98 *****************************************************************************/
100 planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
105 result = (*planner_hook) (parse, cursorOptions, boundParams);
107 result = standard_planner(parse, cursorOptions, boundParams);
112 standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
116 double tuple_fraction;
122 /* Cursor options may come from caller or from DECLARE CURSOR stmt */
123 if (parse->utilityStmt &&
124 IsA(parse->utilityStmt, DeclareCursorStmt))
125 cursorOptions |= ((DeclareCursorStmt *) parse->utilityStmt)->options;
128 * Set up global state for this planner invocation. This data is needed
129 * across all levels of sub-Query that might exist in the given command,
130 * so we keep it in a separate struct that's linked to by each per-Query
133 glob = makeNode(PlannerGlobal);
135 glob->boundParams = boundParams;
136 glob->paramlist = NIL;
137 glob->subplans = NIL;
138 glob->subrtables = NIL;
139 glob->rewindPlanIDs = NULL;
140 glob->finalrtable = NIL;
141 glob->relationOids = NIL;
142 glob->transientPlan = false;
144 /* Determine what fraction of the plan is likely to be scanned */
145 if (cursorOptions & CURSOR_OPT_FAST_PLAN)
148 * We have no real idea how many tuples the user will ultimately FETCH
149 * from a cursor, but it is often the case that he doesn't want 'em
150 * all, or would prefer a fast-start plan anyway so that he can
151 * process some of the tuples sooner. Use a GUC parameter to decide
152 * what fraction to optimize for.
154 tuple_fraction = cursor_tuple_fraction;
157 * We document cursor_tuple_fraction as simply being a fraction,
158 * which means the edge cases 0 and 1 have to be treated specially
159 * here. We convert 1 to 0 ("all the tuples") and 0 to a very small
162 if (tuple_fraction >= 1.0)
163 tuple_fraction = 0.0;
164 else if (tuple_fraction <= 0.0)
165 tuple_fraction = 1e-10;
169 /* Default assumption is we need all the tuples */
170 tuple_fraction = 0.0;
173 /* primary planning entry point (may recurse for subqueries) */
174 top_plan = subquery_planner(glob, parse, 1, tuple_fraction, &root);
177 * If creating a plan for a scrollable cursor, make sure it can run
178 * backwards on demand. Add a Material node at the top at need.
180 if (cursorOptions & CURSOR_OPT_SCROLL)
182 if (!ExecSupportsBackwardScan(top_plan))
183 top_plan = materialize_finished_plan(top_plan);
186 /* final cleanup of the plan */
187 Assert(glob->finalrtable == NIL);
188 top_plan = set_plan_references(glob, top_plan, root->parse->rtable);
189 /* ... and the subplans (both regular subplans and initplans) */
190 Assert(list_length(glob->subplans) == list_length(glob->subrtables));
191 forboth(lp, glob->subplans, lr, glob->subrtables)
193 Plan *subplan = (Plan *) lfirst(lp);
194 List *subrtable = (List *) lfirst(lr);
196 lfirst(lp) = set_plan_references(glob, subplan, subrtable);
199 /* build the PlannedStmt result */
200 result = makeNode(PlannedStmt);
202 result->commandType = parse->commandType;
203 result->canSetTag = parse->canSetTag;
204 result->transientPlan = glob->transientPlan;
205 result->planTree = top_plan;
206 result->rtable = glob->finalrtable;
207 result->resultRelations = root->resultRelations;
208 result->utilityStmt = parse->utilityStmt;
209 result->intoClause = parse->intoClause;
210 result->subplans = glob->subplans;
211 result->rewindPlanIDs = glob->rewindPlanIDs;
212 result->returningLists = root->returningLists;
213 result->rowMarks = parse->rowMarks;
214 result->relationOids = glob->relationOids;
215 result->nParamExec = list_length(glob->paramlist);
221 /*--------------------
223 * Invokes the planner on a subquery. We recurse to here for each
224 * sub-SELECT found in the query tree.
226 * glob is the global state for the current planner run.
227 * parse is the querytree produced by the parser & rewriter.
228 * level is the current recursion depth (1 at the top-level Query).
229 * tuple_fraction is the fraction of tuples we expect will be retrieved.
230 * tuple_fraction is interpreted as explained for grouping_planner, below.
232 * If subroot isn't NULL, we pass back the query's final PlannerInfo struct;
233 * among other things this tells the output sort ordering of the plan.
235 * Basically, this routine does the stuff that should only be done once
236 * per Query object. It then calls grouping_planner. At one time,
237 * grouping_planner could be invoked recursively on the same Query object;
238 * that's not currently true, but we keep the separation between the two
239 * routines anyway, in case we need it again someday.
241 * subquery_planner will be called recursively to handle sub-Query nodes
242 * found within the query's expressions and rangetable.
244 * Returns a query plan.
245 *--------------------
248 subquery_planner(PlannerGlobal *glob, Query *parse,
249 Index level, double tuple_fraction,
250 PlannerInfo **subroot)
252 int num_old_subplans = list_length(glob->subplans);
258 /* Create a PlannerInfo data structure for this subquery */
259 root = makeNode(PlannerInfo);
262 root->query_level = level;
263 root->planner_cxt = CurrentMemoryContext;
264 root->init_plans = NIL;
265 root->eq_classes = NIL;
266 root->in_info_list = NIL;
267 root->append_rel_list = NIL;
270 * Look for IN clauses at the top level of WHERE, and transform them into
271 * joins. Note that this step only handles IN clauses originally at top
272 * level of WHERE; if we pull up any subqueries below, their INs are
273 * processed just before pulling them up.
275 if (parse->hasSubLinks)
276 parse->jointree->quals = pull_up_IN_clauses(root,
277 parse->jointree->quals);
280 * Scan the rangetable for set-returning functions, and inline them
281 * if possible (producing subqueries that might get pulled up next).
282 * Recursion issues here are handled in the same way as for IN clauses.
284 inline_set_returning_functions(root);
287 * Check to see if any subqueries in the rangetable can be merged into
290 parse->jointree = (FromExpr *)
291 pull_up_subqueries(root, (Node *) parse->jointree, false, false);
294 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
295 * avoid the expense of doing flatten_join_alias_vars(). Also check for
296 * outer joins --- if none, we can skip reduce_outer_joins() and some
297 * other processing. This must be done after we have done
298 * pull_up_subqueries, of course.
300 * Note: if reduce_outer_joins manages to eliminate all outer joins,
301 * root->hasOuterJoins is not reset currently. This is OK since its
302 * purpose is merely to suppress unnecessary processing in simple cases.
304 root->hasJoinRTEs = false;
305 root->hasOuterJoins = false;
306 foreach(l, parse->rtable)
308 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
310 if (rte->rtekind == RTE_JOIN)
312 root->hasJoinRTEs = true;
313 if (IS_OUTER_JOIN(rte->jointype))
315 root->hasOuterJoins = true;
316 /* Can quit scanning once we find an outer join */
323 * Expand any rangetable entries that are inheritance sets into "append
324 * relations". This can add entries to the rangetable, but they must be
325 * plain base relations not joins, so it's OK (and marginally more
326 * efficient) to do it after checking for join RTEs. We must do it after
327 * pulling up subqueries, else we'd fail to handle inherited tables in
330 expand_inherited_tables(root);
333 * Set hasHavingQual to remember if HAVING clause is present. Needed
334 * because preprocess_expression will reduce a constant-true condition to
335 * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
337 root->hasHavingQual = (parse->havingQual != NULL);
339 /* Clear this flag; might get set in distribute_qual_to_rels */
340 root->hasPseudoConstantQuals = false;
343 * Do expression preprocessing on targetlist and quals.
345 parse->targetList = (List *)
346 preprocess_expression(root, (Node *) parse->targetList,
349 parse->returningList = (List *)
350 preprocess_expression(root, (Node *) parse->returningList,
353 preprocess_qual_conditions(root, (Node *) parse->jointree);
355 parse->havingQual = preprocess_expression(root, parse->havingQual,
358 parse->limitOffset = preprocess_expression(root, parse->limitOffset,
360 parse->limitCount = preprocess_expression(root, parse->limitCount,
363 root->in_info_list = (List *)
364 preprocess_expression(root, (Node *) root->in_info_list,
366 root->append_rel_list = (List *)
367 preprocess_expression(root, (Node *) root->append_rel_list,
370 /* Also need to preprocess expressions for function and values RTEs */
371 foreach(l, parse->rtable)
373 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
375 if (rte->rtekind == RTE_FUNCTION)
376 rte->funcexpr = preprocess_expression(root, rte->funcexpr,
378 else if (rte->rtekind == RTE_VALUES)
379 rte->values_lists = (List *)
380 preprocess_expression(root, (Node *) rte->values_lists,
385 * In some cases we may want to transfer a HAVING clause into WHERE. We
386 * cannot do so if the HAVING clause contains aggregates (obviously) or
387 * volatile functions (since a HAVING clause is supposed to be executed
388 * only once per group). Also, it may be that the clause is so expensive
389 * to execute that we're better off doing it only once per group, despite
390 * the loss of selectivity. This is hard to estimate short of doing the
391 * entire planning process twice, so we use a heuristic: clauses
392 * containing subplans are left in HAVING. Otherwise, we move or copy the
393 * HAVING clause into WHERE, in hopes of eliminating tuples before
394 * aggregation instead of after.
396 * If the query has explicit grouping then we can simply move such a
397 * clause into WHERE; any group that fails the clause will not be in the
398 * output because none of its tuples will reach the grouping or
399 * aggregation stage. Otherwise we must have a degenerate (variable-free)
400 * HAVING clause, which we put in WHERE so that query_planner() can use it
401 * in a gating Result node, but also keep in HAVING to ensure that we
402 * don't emit a bogus aggregated row. (This could be done better, but it
403 * seems not worth optimizing.)
405 * Note that both havingQual and parse->jointree->quals are in
406 * implicitly-ANDed-list form at this point, even though they are declared
410 foreach(l, (List *) parse->havingQual)
412 Node *havingclause = (Node *) lfirst(l);
414 if (contain_agg_clause(havingclause) ||
415 contain_volatile_functions(havingclause) ||
416 contain_subplans(havingclause))
418 /* keep it in HAVING */
419 newHaving = lappend(newHaving, havingclause);
421 else if (parse->groupClause)
423 /* move it to WHERE */
424 parse->jointree->quals = (Node *)
425 lappend((List *) parse->jointree->quals, havingclause);
429 /* put a copy in WHERE, keep it in HAVING */
430 parse->jointree->quals = (Node *)
431 lappend((List *) parse->jointree->quals,
432 copyObject(havingclause));
433 newHaving = lappend(newHaving, havingclause);
436 parse->havingQual = (Node *) newHaving;
439 * If we have any outer joins, try to reduce them to plain inner joins.
440 * This step is most easily done after we've done expression
443 if (root->hasOuterJoins)
444 reduce_outer_joins(root);
447 * Do the main planning. If we have an inherited target relation, that
448 * needs special processing, else go straight to grouping_planner.
450 if (parse->resultRelation &&
451 rt_fetch(parse->resultRelation, parse->rtable)->inh)
452 plan = inheritance_planner(root);
454 plan = grouping_planner(root, tuple_fraction);
457 * If any subplans were generated, or if we're inside a subplan, build
458 * initPlan list and extParam/allParam sets for plan nodes, and attach the
459 * initPlans to the top plan node.
461 if (list_length(glob->subplans) != num_old_subplans ||
462 root->query_level > 1)
463 SS_finalize_plan(root, plan, true);
465 /* Return internal info if caller wants it */
473 * preprocess_expression
474 * Do subquery_planner's preprocessing work for an expression,
475 * which can be a targetlist, a WHERE clause (including JOIN/ON
476 * conditions), or a HAVING clause.
479 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
482 * Fall out quickly if expression is empty. This occurs often enough to
483 * be worth checking. Note that null->null is the correct conversion for
484 * implicit-AND result format, too.
490 * If the query has any join RTEs, replace join alias variables with
491 * base-relation variables. We must do this before sublink processing,
492 * else sublinks expanded out from join aliases wouldn't get processed. We
493 * can skip it in VALUES lists, however, since they can't contain any Vars
496 if (root->hasJoinRTEs && kind != EXPRKIND_VALUES)
497 expr = flatten_join_alias_vars(root, expr);
500 * Simplify constant expressions.
502 * Note: this also flattens nested AND and OR expressions into N-argument
503 * form. All processing of a qual expression after this point must be
504 * careful to maintain AND/OR flatness --- that is, do not generate a tree
505 * with AND directly under AND, nor OR directly under OR.
507 * Because this is a relatively expensive process, we skip it when the
508 * query is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()". The
509 * expression will only be evaluated once anyway, so no point in
510 * pre-simplifying; we can't execute it any faster than the executor can,
511 * and we will waste cycles copying the tree. Notice however that we
512 * still must do it for quals (to get AND/OR flatness); and if we are in a
513 * subquery we should not assume it will be done only once.
515 * For VALUES lists we never do this at all, again on the grounds that we
516 * should optimize for one-time evaluation.
518 if (kind != EXPRKIND_VALUES &&
519 (root->parse->jointree->fromlist != NIL ||
520 kind == EXPRKIND_QUAL ||
521 root->query_level > 1))
522 expr = eval_const_expressions(root, expr);
525 * If it's a qual or havingQual, canonicalize it.
527 if (kind == EXPRKIND_QUAL)
529 expr = (Node *) canonicalize_qual((Expr *) expr);
531 #ifdef OPTIMIZER_DEBUG
532 printf("After canonicalize_qual()\n");
537 /* Expand SubLinks to SubPlans */
538 if (root->parse->hasSubLinks)
539 expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
542 * XXX do not insert anything here unless you have grokked the comments in
543 * SS_replace_correlation_vars ...
546 /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
547 if (root->query_level > 1)
548 expr = SS_replace_correlation_vars(root, expr);
551 * If it's a qual or havingQual, convert it to implicit-AND format. (We
552 * don't want to do this before eval_const_expressions, since the latter
553 * would be unable to simplify a top-level AND correctly. Also,
554 * SS_process_sublinks expects explicit-AND format.)
556 if (kind == EXPRKIND_QUAL)
557 expr = (Node *) make_ands_implicit((Expr *) expr);
563 * preprocess_qual_conditions
564 * Recursively scan the query's jointree and do subquery_planner's
565 * preprocessing work on each qual condition found therein.
568 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
572 if (IsA(jtnode, RangeTblRef))
574 /* nothing to do here */
576 else if (IsA(jtnode, FromExpr))
578 FromExpr *f = (FromExpr *) jtnode;
581 foreach(l, f->fromlist)
582 preprocess_qual_conditions(root, lfirst(l));
584 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
586 else if (IsA(jtnode, JoinExpr))
588 JoinExpr *j = (JoinExpr *) jtnode;
590 preprocess_qual_conditions(root, j->larg);
591 preprocess_qual_conditions(root, j->rarg);
593 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
596 elog(ERROR, "unrecognized node type: %d",
597 (int) nodeTag(jtnode));
601 * inheritance_planner
602 * Generate a plan in the case where the result relation is an
605 * We have to handle this case differently from cases where a source relation
606 * is an inheritance set. Source inheritance is expanded at the bottom of the
607 * plan tree (see allpaths.c), but target inheritance has to be expanded at
608 * the top. The reason is that for UPDATE, each target relation needs a
609 * different targetlist matching its own column set. Also, for both UPDATE
610 * and DELETE, the executor needs the Append plan node at the top, else it
611 * can't keep track of which table is the current target table. Fortunately,
612 * the UPDATE/DELETE target can never be the nullable side of an outer join,
613 * so it's OK to generate the plan this way.
615 * Returns a query plan.
618 inheritance_planner(PlannerInfo *root)
620 Query *parse = root->parse;
621 int parentRTindex = parse->resultRelation;
622 List *subplans = NIL;
623 List *resultRelations = NIL;
624 List *returningLists = NIL;
630 foreach(l, root->append_rel_list)
632 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
635 /* append_rel_list contains all append rels; ignore others */
636 if (appinfo->parent_relid != parentRTindex)
640 * Generate modified query with this rel as target. We have to be
641 * prepared to translate varnos in in_info_list as well as in the
644 memcpy(&subroot, root, sizeof(PlannerInfo));
645 subroot.parse = (Query *)
646 adjust_appendrel_attrs((Node *) parse,
648 subroot.in_info_list = (List *)
649 adjust_appendrel_attrs((Node *) root->in_info_list,
651 subroot.init_plans = NIL;
652 /* There shouldn't be any OJ info to translate, as yet */
653 Assert(subroot.oj_info_list == NIL);
656 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
659 * If this child rel was excluded by constraint exclusion, exclude it
662 if (is_dummy_plan(subplan))
665 /* Save rtable and tlist from first rel for use below */
668 rtable = subroot.parse->rtable;
669 tlist = subplan->targetlist;
672 subplans = lappend(subplans, subplan);
674 /* Make sure any initplans from this rel get into the outer list */
675 root->init_plans = list_concat(root->init_plans, subroot.init_plans);
677 /* Build target-relations list for the executor */
678 resultRelations = lappend_int(resultRelations, appinfo->child_relid);
680 /* Build list of per-relation RETURNING targetlists */
681 if (parse->returningList)
683 Assert(list_length(subroot.returningLists) == 1);
684 returningLists = list_concat(returningLists,
685 subroot.returningLists);
689 root->resultRelations = resultRelations;
690 root->returningLists = returningLists;
692 /* Mark result as unordered (probably unnecessary) */
693 root->query_pathkeys = NIL;
696 * If we managed to exclude every child rel, return a dummy plan
700 root->resultRelations = list_make1_int(parentRTindex);
701 /* although dummy, it must have a valid tlist for executor */
702 tlist = preprocess_targetlist(root, parse->targetList);
703 return (Plan *) make_result(root,
705 (Node *) list_make1(makeBoolConst(false,
711 * Planning might have modified the rangetable, due to changes of the
712 * Query structures inside subquery RTEs. We have to ensure that this
713 * gets propagated back to the master copy. But can't do this until we
714 * are done planning, because all the calls to grouping_planner need
715 * virgin sub-Queries to work from. (We are effectively assuming that
716 * sub-Queries will get planned identically each time, or at least that
717 * the impacts on their rangetables will be the same each time.)
719 * XXX should clean this up someday
721 parse->rtable = rtable;
723 /* Suppress Append if there's only one surviving child rel */
724 if (list_length(subplans) == 1)
725 return (Plan *) linitial(subplans);
727 return (Plan *) make_append(subplans, true, tlist);
730 /*--------------------
732 * Perform planning steps related to grouping, aggregation, etc.
733 * This primarily means adding top-level processing to the basic
734 * query plan produced by query_planner.
736 * tuple_fraction is the fraction of tuples we expect will be retrieved
738 * tuple_fraction is interpreted as follows:
739 * 0: expect all tuples to be retrieved (normal case)
740 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
741 * from the plan to be retrieved
742 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
743 * expected to be retrieved (ie, a LIMIT specification)
745 * Returns a query plan. Also, root->query_pathkeys is returned as the
746 * actual output ordering of the plan (in pathkey format).
747 *--------------------
750 grouping_planner(PlannerInfo *root, double tuple_fraction)
752 Query *parse = root->parse;
753 List *tlist = parse->targetList;
754 int64 offset_est = 0;
756 double limit_tuples = -1.0;
758 List *current_pathkeys;
760 double dNumGroups = 0;
762 /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
763 if (parse->limitCount || parse->limitOffset)
765 tuple_fraction = preprocess_limit(root, tuple_fraction,
766 &offset_est, &count_est);
769 * If we have a known LIMIT, and don't have an unknown OFFSET, we can
770 * estimate the effects of using a bounded sort.
772 if (count_est > 0 && offset_est >= 0)
773 limit_tuples = (double) count_est + (double) offset_est;
776 if (parse->setOperations)
778 List *set_sortclauses;
781 * If there's a top-level ORDER BY, assume we have to fetch all the
782 * tuples. This might seem too simplistic given all the hackery below
783 * to possibly avoid the sort ... but a nonzero tuple_fraction is only
784 * of use to plan_set_operations() when the setop is UNION ALL, and
785 * the result of UNION ALL is always unsorted.
787 if (parse->sortClause)
788 tuple_fraction = 0.0;
791 * Construct the plan for set operations. The result will not need
792 * any work except perhaps a top-level sort and/or LIMIT.
794 result_plan = plan_set_operations(root, tuple_fraction,
798 * Calculate pathkeys representing the sort order (if any) of the set
799 * operation's result. We have to do this before overwriting the sort
802 current_pathkeys = make_pathkeys_for_sortclauses(root,
804 result_plan->targetlist,
808 * We should not need to call preprocess_targetlist, since we must be
809 * in a SELECT query node. Instead, use the targetlist returned by
810 * plan_set_operations (since this tells whether it returned any
811 * resjunk columns!), and transfer any sort key information from the
814 Assert(parse->commandType == CMD_SELECT);
816 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
819 * Can't handle FOR UPDATE/SHARE here (parser should have checked
820 * already, but let's make sure).
824 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
825 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
828 * Calculate pathkeys that represent result ordering requirements
830 Assert(parse->distinctClause == NIL);
831 sort_pathkeys = make_pathkeys_for_sortclauses(root,
838 /* No set operations, do regular planning */
840 List *group_pathkeys;
841 AttrNumber *groupColIdx = NULL;
842 Oid *groupOperators = 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 root->group_pathkeys =
881 make_pathkeys_for_sortclauses(root,
885 if (list_length(parse->distinctClause) > list_length(parse->sortClause))
886 root->sort_pathkeys =
887 make_pathkeys_for_sortclauses(root,
888 parse->distinctClause,
892 root->sort_pathkeys =
893 make_pathkeys_for_sortclauses(root,
899 * Will need actual number of aggregates for estimating costs.
901 * Note: we do not attempt to detect duplicate aggregates here; a
902 * somewhat-overestimated count is okay for our present purposes.
904 * Note: think not that we can turn off hasAggs if we find no aggs. It
905 * is possible for constant-expression simplification to remove all
906 * explicit references to aggs, but we still have to follow the
907 * aggregate semantics (eg, producing only one output row).
911 count_agg_clauses((Node *) tlist, &agg_counts);
912 count_agg_clauses(parse->havingQual, &agg_counts);
916 * Figure out whether we need a sorted result from query_planner.
918 * If we have a GROUP BY clause, then we want a result sorted properly
919 * for grouping. Otherwise, if there is an ORDER BY clause, we want
920 * to sort by the ORDER BY clause. (Note: if we have both, and ORDER
921 * BY is a superset of GROUP BY, it would be tempting to request sort
922 * by ORDER BY --- but that might just leave us failing to exploit an
923 * available sort order at all. Needs more thought...)
925 if (root->group_pathkeys)
926 root->query_pathkeys = root->group_pathkeys;
927 else if (root->sort_pathkeys)
928 root->query_pathkeys = root->sort_pathkeys;
930 root->query_pathkeys = NIL;
933 * Generate the best unsorted and presorted paths for this Query (but
934 * note there may not be any presorted path). query_planner will also
935 * estimate the number of groups in the query, and canonicalize all
938 query_planner(root, sub_tlist, tuple_fraction, limit_tuples,
939 &cheapest_path, &sorted_path, &dNumGroups);
941 group_pathkeys = root->group_pathkeys;
942 sort_pathkeys = root->sort_pathkeys;
945 * If grouping, extract the grouping operators and decide whether we
946 * want to use hashed grouping.
948 if (parse->groupClause)
950 groupOperators = extract_grouping_ops(parse->groupClause);
951 use_hashed_grouping =
952 choose_hashed_grouping(root, tuple_fraction, limit_tuples,
953 cheapest_path, sorted_path,
954 groupOperators, dNumGroups,
957 /* Also convert # groups to long int --- but 'ware overflow! */
958 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
962 * Select the best path. If we are doing hashed grouping, we will
963 * always read all the input tuples, so use the cheapest-total path.
964 * Otherwise, trust query_planner's decision about which to use.
966 if (use_hashed_grouping || !sorted_path)
967 best_path = cheapest_path;
969 best_path = sorted_path;
972 * Check to see if it's possible to optimize MIN/MAX aggregates. If
973 * so, we will forget all the work we did so far to choose a "regular"
974 * path ... but we had to do it anyway to be able to tell which way is
977 result_plan = optimize_minmax_aggregates(root,
980 if (result_plan != NULL)
983 * optimize_minmax_aggregates generated the full plan, with the
984 * right tlist, and it has no sort order.
986 current_pathkeys = NIL;
991 * Normal case --- create a plan according to query_planner's
994 bool need_sort_for_grouping = false;
996 result_plan = create_plan(root, best_path);
997 current_pathkeys = best_path->pathkeys;
999 /* Detect if we'll need an explicit sort for grouping */
1000 if (parse->groupClause && !use_hashed_grouping &&
1001 !pathkeys_contained_in(group_pathkeys, current_pathkeys))
1003 need_sort_for_grouping = true;
1005 * Always override query_planner's tlist, so that we don't
1006 * sort useless data from a "physical" tlist.
1008 need_tlist_eval = true;
1012 * create_plan() returns a plan with just a "flat" tlist of
1013 * required Vars. Usually we need to insert the sub_tlist as the
1014 * tlist of the top plan node. However, we can skip that if we
1015 * determined that whatever query_planner chose to return will be
1018 if (need_tlist_eval)
1021 * If the top-level plan node is one that cannot do expression
1022 * evaluation, we must insert a Result node to project the
1025 if (!is_projection_capable_plan(result_plan))
1027 result_plan = (Plan *) make_result(root,
1035 * Otherwise, just replace the subplan's flat tlist with
1036 * the desired tlist.
1038 result_plan->targetlist = sub_tlist;
1042 * Also, account for the cost of evaluation of the sub_tlist.
1044 * Up to now, we have only been dealing with "flat" tlists,
1045 * containing just Vars. So their evaluation cost is zero
1046 * according to the model used by cost_qual_eval() (or if you
1047 * prefer, the cost is factored into cpu_tuple_cost). Thus we
1048 * can avoid accounting for tlist cost throughout
1049 * query_planner() and subroutines. But now we've inserted a
1050 * tlist that might contain actual operators, sub-selects, etc
1051 * --- so we'd better account for its cost.
1053 * Below this point, any tlist eval cost for added-on nodes
1054 * should be accounted for as we create those nodes.
1055 * Presently, of the node types we can add on, only Agg and
1056 * Group project new tlists (the rest just copy their input
1057 * tuples) --- so make_agg() and make_group() are responsible
1058 * for computing the added cost.
1060 cost_qual_eval(&tlist_cost, sub_tlist, root);
1061 result_plan->startup_cost += tlist_cost.startup;
1062 result_plan->total_cost += tlist_cost.startup +
1063 tlist_cost.per_tuple * result_plan->plan_rows;
1068 * Since we're using query_planner's tlist and not the one
1069 * make_subplanTargetList calculated, we have to refigure any
1070 * grouping-column indexes make_subplanTargetList computed.
1072 locate_grouping_columns(root, tlist, result_plan->targetlist,
1077 * Insert AGG or GROUP node if needed, plus an explicit sort step
1080 * HAVING clause, if any, becomes qual of the Agg or Group node.
1082 if (use_hashed_grouping)
1084 /* Hashed aggregate plan --- no sort needed */
1085 result_plan = (Plan *) make_agg(root,
1087 (List *) parse->havingQual,
1095 /* Hashed aggregation produces randomly-ordered results */
1096 current_pathkeys = NIL;
1098 else if (parse->hasAggs)
1100 /* Plain aggregate plan --- sort if needed */
1101 AggStrategy aggstrategy;
1103 if (parse->groupClause)
1105 if (need_sort_for_grouping)
1107 result_plan = (Plan *)
1108 make_sort_from_groupcols(root,
1112 current_pathkeys = group_pathkeys;
1114 aggstrategy = AGG_SORTED;
1117 * The AGG node will not change the sort ordering of its
1118 * groups, so current_pathkeys describes the result too.
1123 aggstrategy = AGG_PLAIN;
1124 /* Result will be only one row anyway; no sort order */
1125 current_pathkeys = NIL;
1128 result_plan = (Plan *) make_agg(root,
1130 (List *) parse->havingQual,
1139 else if (parse->groupClause)
1142 * GROUP BY without aggregation, so insert a group node (plus
1143 * the appropriate sort node, if necessary).
1145 * Add an explicit sort if we couldn't make the path come out
1146 * the way the GROUP node needs it.
1148 if (need_sort_for_grouping)
1150 result_plan = (Plan *)
1151 make_sort_from_groupcols(root,
1155 current_pathkeys = group_pathkeys;
1158 result_plan = (Plan *) make_group(root,
1160 (List *) parse->havingQual,
1166 /* The Group node won't change sort ordering */
1168 else if (root->hasHavingQual)
1171 * No aggregates, and no GROUP BY, but we have a HAVING qual.
1172 * This is a degenerate case in which we are supposed to emit
1173 * either 0 or 1 row depending on whether HAVING succeeds.
1174 * Furthermore, there cannot be any variables in either HAVING
1175 * or the targetlist, so we actually do not need the FROM
1176 * table at all! We can just throw away the plan-so-far and
1177 * generate a Result node. This is a sufficiently unusual
1178 * corner case that it's not worth contorting the structure of
1179 * this routine to avoid having to generate the plan in the
1182 result_plan = (Plan *) make_result(root,
1187 } /* end of non-minmax-aggregate case */
1188 } /* end of if (setOperations) */
1191 * If we were not able to make the plan come out in the right order, add
1192 * an explicit sort step.
1196 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1198 result_plan = (Plan *) make_sort_from_pathkeys(root,
1202 current_pathkeys = sort_pathkeys;
1207 * If there is a DISTINCT clause, add the UNIQUE node.
1209 if (parse->distinctClause)
1211 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1214 * If there was grouping or aggregation, leave plan_rows as-is (ie,
1215 * assume the result was already mostly unique). If not, use the
1216 * number of distinct-groups calculated by query_planner.
1218 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1219 result_plan->plan_rows = dNumGroups;
1223 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1225 if (parse->limitCount || parse->limitOffset)
1227 result_plan = (Plan *) make_limit(result_plan,
1235 * Deal with the RETURNING clause if any. It's convenient to pass the
1236 * returningList through setrefs.c now rather than at top level (if we
1237 * waited, handling inherited UPDATE/DELETE would be much harder).
1239 if (parse->returningList)
1243 Assert(parse->resultRelation);
1244 rlist = set_returning_clause_references(root->glob,
1245 parse->returningList,
1247 parse->resultRelation);
1248 root->returningLists = list_make1(rlist);
1251 root->returningLists = NIL;
1253 /* Compute result-relations list if needed */
1254 if (parse->resultRelation)
1255 root->resultRelations = list_make1_int(parse->resultRelation);
1257 root->resultRelations = NIL;
1260 * Return the actual output ordering in query_pathkeys for possible use by
1261 * an outer query level.
1263 root->query_pathkeys = current_pathkeys;
1269 * Detect whether a plan node is a "dummy" plan created when a relation
1270 * is deemed not to need scanning due to constraint exclusion.
1272 * Currently, such dummy plans are Result nodes with constant FALSE
1276 is_dummy_plan(Plan *plan)
1278 if (IsA(plan, Result))
1280 List *rcqual = (List *) ((Result *) plan)->resconstantqual;
1282 if (list_length(rcqual) == 1)
1284 Const *constqual = (Const *) linitial(rcqual);
1286 if (constqual && IsA(constqual, Const))
1288 if (!constqual->constisnull &&
1289 !DatumGetBool(constqual->constvalue))
1298 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1300 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1301 * results back in *count_est and *offset_est. These variables are set to
1302 * 0 if the corresponding clause is not present, and -1 if it's present
1303 * but we couldn't estimate the value for it. (The "0" convention is OK
1304 * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1305 * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
1306 * usual practice of never estimating less than one row.) These values will
1307 * be passed to make_limit, which see if you change this code.
1309 * The return value is the suitably adjusted tuple_fraction to use for
1310 * planning the query. This adjustment is not overridable, since it reflects
1311 * plan actions that grouping_planner() will certainly take, not assumptions
1315 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1316 int64 *offset_est, int64 *count_est)
1318 Query *parse = root->parse;
1320 double limit_fraction;
1322 /* Should not be called unless LIMIT or OFFSET */
1323 Assert(parse->limitCount || parse->limitOffset);
1326 * Try to obtain the clause values. We use estimate_expression_value
1327 * primarily because it can sometimes do something useful with Params.
1329 if (parse->limitCount)
1331 est = estimate_expression_value(root, parse->limitCount);
1332 if (est && IsA(est, Const))
1334 if (((Const *) est)->constisnull)
1336 /* NULL indicates LIMIT ALL, ie, no limit */
1337 *count_est = 0; /* treat as not present */
1341 *count_est = DatumGetInt64(((Const *) est)->constvalue);
1342 if (*count_est <= 0)
1343 *count_est = 1; /* force to at least 1 */
1347 *count_est = -1; /* can't estimate */
1350 *count_est = 0; /* not present */
1352 if (parse->limitOffset)
1354 est = estimate_expression_value(root, parse->limitOffset);
1355 if (est && IsA(est, Const))
1357 if (((Const *) est)->constisnull)
1359 /* Treat NULL as no offset; the executor will too */
1360 *offset_est = 0; /* treat as not present */
1364 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
1365 if (*offset_est < 0)
1366 *offset_est = 0; /* less than 0 is same as 0 */
1370 *offset_est = -1; /* can't estimate */
1373 *offset_est = 0; /* not present */
1375 if (*count_est != 0)
1378 * A LIMIT clause limits the absolute number of tuples returned.
1379 * However, if it's not a constant LIMIT then we have to guess; for
1380 * lack of a better idea, assume 10% of the plan's result is wanted.
1382 if (*count_est < 0 || *offset_est < 0)
1384 /* LIMIT or OFFSET is an expression ... punt ... */
1385 limit_fraction = 0.10;
1389 /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
1390 limit_fraction = (double) *count_est + (double) *offset_est;
1394 * If we have absolute limits from both caller and LIMIT, use the
1395 * smaller value; likewise if they are both fractional. If one is
1396 * fractional and the other absolute, we can't easily determine which
1397 * is smaller, but we use the heuristic that the absolute will usually
1400 if (tuple_fraction >= 1.0)
1402 if (limit_fraction >= 1.0)
1405 tuple_fraction = Min(tuple_fraction, limit_fraction);
1409 /* caller absolute, limit fractional; use caller's value */
1412 else if (tuple_fraction > 0.0)
1414 if (limit_fraction >= 1.0)
1416 /* caller fractional, limit absolute; use limit */
1417 tuple_fraction = limit_fraction;
1421 /* both fractional */
1422 tuple_fraction = Min(tuple_fraction, limit_fraction);
1427 /* no info from caller, just use limit */
1428 tuple_fraction = limit_fraction;
1431 else if (*offset_est != 0 && tuple_fraction > 0.0)
1434 * We have an OFFSET but no LIMIT. This acts entirely differently
1435 * from the LIMIT case: here, we need to increase rather than decrease
1436 * the caller's tuple_fraction, because the OFFSET acts to cause more
1437 * tuples to be fetched instead of fewer. This only matters if we got
1438 * a tuple_fraction > 0, however.
1440 * As above, use 10% if OFFSET is present but unestimatable.
1442 if (*offset_est < 0)
1443 limit_fraction = 0.10;
1445 limit_fraction = (double) *offset_est;
1448 * If we have absolute counts from both caller and OFFSET, add them
1449 * together; likewise if they are both fractional. If one is
1450 * fractional and the other absolute, we want to take the larger, and
1451 * we heuristically assume that's the fractional one.
1453 if (tuple_fraction >= 1.0)
1455 if (limit_fraction >= 1.0)
1457 /* both absolute, so add them together */
1458 tuple_fraction += limit_fraction;
1462 /* caller absolute, limit fractional; use limit */
1463 tuple_fraction = limit_fraction;
1468 if (limit_fraction >= 1.0)
1470 /* caller fractional, limit absolute; use caller's value */
1474 /* both fractional, so add them together */
1475 tuple_fraction += limit_fraction;
1476 if (tuple_fraction >= 1.0)
1477 tuple_fraction = 0.0; /* assume fetch all */
1482 return tuple_fraction;
1487 * preprocess_groupclause - do preparatory work on GROUP BY clause
1489 * The idea here is to adjust the ordering of the GROUP BY elements
1490 * (which in itself is semantically insignificant) to match ORDER BY,
1491 * thereby allowing a single sort operation to both implement the ORDER BY
1492 * requirement and set up for a Unique step that implements GROUP BY.
1494 * In principle it might be interesting to consider other orderings of the
1495 * GROUP BY elements, which could match the sort ordering of other
1496 * possible plans (eg an indexscan) and thereby reduce cost. We don't
1497 * bother with that, though. Hashed grouping will frequently win anyway.
1500 preprocess_groupclause(PlannerInfo *root)
1502 Query *parse = root->parse;
1503 List *new_groupclause;
1508 /* If no ORDER BY, nothing useful to do here anyway */
1509 if (parse->sortClause == NIL)
1513 * Scan the ORDER BY clause and construct a list of matching GROUP BY
1514 * items, but only as far as we can make a matching prefix.
1516 * This code assumes that the sortClause contains no duplicate items.
1518 new_groupclause = NIL;
1519 foreach(sl, parse->sortClause)
1521 SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
1523 foreach(gl, parse->groupClause)
1525 SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
1529 new_groupclause = lappend(new_groupclause, gc);
1534 break; /* no match, so stop scanning */
1537 /* Did we match all of the ORDER BY list, or just some of it? */
1538 partial_match = (sl != NULL);
1540 /* If no match at all, no point in reordering GROUP BY */
1541 if (new_groupclause == NIL)
1545 * Add any remaining GROUP BY items to the new list, but only if we
1546 * were able to make a complete match. In other words, we only
1547 * rearrange the GROUP BY list if the result is that one list is a
1548 * prefix of the other --- otherwise there's no possibility of a
1551 foreach(gl, parse->groupClause)
1553 SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
1555 if (list_member_ptr(new_groupclause, gc))
1556 continue; /* it matched an ORDER BY item */
1558 return; /* give up, no common sort possible */
1559 new_groupclause = lappend(new_groupclause, gc);
1562 /* Success --- install the rearranged GROUP BY list */
1563 Assert(list_length(parse->groupClause) == list_length(new_groupclause));
1564 parse->groupClause = new_groupclause;
1568 * extract_grouping_ops - make an array of the equality operator OIDs
1569 * for the GROUP BY clause
1572 extract_grouping_ops(List *groupClause)
1574 int numCols = list_length(groupClause);
1576 Oid *groupOperators;
1579 groupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
1581 foreach(glitem, groupClause)
1583 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1585 groupOperators[colno] = groupcl->eqop;
1586 Assert(OidIsValid(groupOperators[colno]));
1590 return groupOperators;
1594 * choose_hashed_grouping - should we use hashed grouping?
1597 choose_hashed_grouping(PlannerInfo *root,
1598 double tuple_fraction, double limit_tuples,
1599 Path *cheapest_path, Path *sorted_path,
1600 Oid *groupOperators, double dNumGroups,
1601 AggClauseCounts *agg_counts)
1603 int numGroupCols = list_length(root->parse->groupClause);
1604 double cheapest_path_rows;
1605 int cheapest_path_width;
1607 List *current_pathkeys;
1613 * Check can't-do-it conditions, including whether the grouping operators
1614 * are hashjoinable. (We assume hashing is OK if they are marked
1615 * oprcanhash. If there isn't actually a supporting hash function, the
1616 * executor will complain at runtime.)
1618 * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1619 * (Doing so would imply storing *all* the input values in the hash table,
1620 * which seems like a certain loser.)
1622 if (!enable_hashagg)
1624 if (agg_counts->numDistinctAggs != 0)
1626 for (i = 0; i < numGroupCols; i++)
1628 if (!op_hashjoinable(groupOperators[i]))
1633 * Don't do it if it doesn't look like the hashtable will fit into
1636 * Beware here of the possibility that cheapest_path->parent is NULL. This
1637 * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
1639 if (cheapest_path->parent)
1641 cheapest_path_rows = cheapest_path->parent->rows;
1642 cheapest_path_width = cheapest_path->parent->width;
1646 cheapest_path_rows = 1; /* assume non-set result */
1647 cheapest_path_width = 100; /* arbitrary */
1650 /* Estimate per-hash-entry space at tuple width... */
1651 hashentrysize = MAXALIGN(cheapest_path_width) + MAXALIGN(sizeof(MinimalTupleData));
1652 /* plus space for pass-by-ref transition values... */
1653 hashentrysize += agg_counts->transitionSpace;
1654 /* plus the per-hash-entry overhead */
1655 hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1657 if (hashentrysize * dNumGroups > work_mem * 1024L)
1661 * See if the estimated cost is no more than doing it the other way. While
1662 * avoiding the need for sorted input is usually a win, the fact that the
1663 * output won't be sorted may be a loss; so we need to do an actual cost
1666 * We need to consider cheapest_path + hashagg [+ final sort] versus
1667 * either cheapest_path [+ sort] + group or agg [+ final sort] or
1668 * presorted_path + group or agg [+ final sort] where brackets indicate a
1669 * step that may not be needed. We assume query_planner() will have
1670 * returned a presorted path only if it's a winner compared to
1671 * cheapest_path for this purpose.
1673 * These path variables are dummies that just hold cost fields; we don't
1674 * make actual Paths for these steps.
1676 cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1677 numGroupCols, dNumGroups,
1678 cheapest_path->startup_cost, cheapest_path->total_cost,
1679 cheapest_path_rows);
1680 /* Result of hashed agg is always unsorted */
1681 if (root->sort_pathkeys)
1682 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
1683 dNumGroups, cheapest_path_width, limit_tuples);
1687 sorted_p.startup_cost = sorted_path->startup_cost;
1688 sorted_p.total_cost = sorted_path->total_cost;
1689 current_pathkeys = sorted_path->pathkeys;
1693 sorted_p.startup_cost = cheapest_path->startup_cost;
1694 sorted_p.total_cost = cheapest_path->total_cost;
1695 current_pathkeys = cheapest_path->pathkeys;
1697 if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1699 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
1700 cheapest_path_rows, cheapest_path_width, -1.0);
1701 current_pathkeys = root->group_pathkeys;
1704 if (root->parse->hasAggs)
1705 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1706 numGroupCols, dNumGroups,
1707 sorted_p.startup_cost, sorted_p.total_cost,
1708 cheapest_path_rows);
1710 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1711 sorted_p.startup_cost, sorted_p.total_cost,
1712 cheapest_path_rows);
1713 /* The Agg or Group node will preserve ordering */
1714 if (root->sort_pathkeys &&
1715 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1716 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
1717 dNumGroups, cheapest_path_width, limit_tuples);
1720 * Now make the decision using the top-level tuple fraction. First we
1721 * have to convert an absolute count (LIMIT) into fractional form.
1723 if (tuple_fraction >= 1.0)
1724 tuple_fraction /= dNumGroups;
1726 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1727 tuple_fraction) < 0)
1729 /* Hashed is cheaper, so use it */
1736 * make_subplanTargetList
1737 * Generate appropriate target list when grouping is required.
1739 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1740 * above the result of query_planner, we typically want to pass a different
1741 * target list to query_planner than the outer plan nodes should have.
1742 * This routine generates the correct target list for the subplan.
1744 * The initial target list passed from the parser already contains entries
1745 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1746 * for variables used only in HAVING clauses; so we need to add those
1747 * variables to the subplan target list. Also, we flatten all expressions
1748 * except GROUP BY items into their component variables; the other expressions
1749 * will be computed by the inserted nodes rather than by the subplan.
1750 * For example, given a query like
1751 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1752 * we want to pass this targetlist to the subplan:
1754 * where the a+b target will be used by the Sort/Group steps, and the
1755 * other targets will be used for computing the final results. (In the
1756 * above example we could theoretically suppress the a and b targets and
1757 * pass down only c,d,a+b, but it's not really worth the trouble to
1758 * eliminate simple var references from the subplan. We will avoid doing
1759 * the extra computation to recompute a+b at the outer level; see
1760 * fix_upper_expr() in setrefs.c.)
1762 * If we are grouping or aggregating, *and* there are no non-Var grouping
1763 * expressions, then the returned tlist is effectively dummy; we do not
1764 * need to force it to be evaluated, because all the Vars it contains
1765 * should be present in the output of query_planner anyway.
1767 * 'tlist' is the query's target list.
1768 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1769 * expressions (if there are any) in the subplan's target list.
1770 * 'need_tlist_eval' is set true if we really need to evaluate the
1773 * The result is the targetlist to be passed to the subplan.
1777 make_subplanTargetList(PlannerInfo *root,
1779 AttrNumber **groupColIdx,
1780 bool *need_tlist_eval)
1782 Query *parse = root->parse;
1787 *groupColIdx = NULL;
1790 * If we're not grouping or aggregating, there's nothing to do here;
1791 * query_planner should receive the unmodified target list.
1793 if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1795 *need_tlist_eval = true;
1800 * Otherwise, start with a "flattened" tlist (having just the vars
1801 * mentioned in the targetlist and HAVING qual --- but not upper- level
1802 * Vars; they will be replaced by Params later on).
1804 sub_tlist = flatten_tlist(tlist);
1805 extravars = pull_var_clause(parse->havingQual, false);
1806 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1807 list_free(extravars);
1808 *need_tlist_eval = false; /* only eval if not flat tlist */
1811 * If grouping, create sub_tlist entries for all GROUP BY expressions
1812 * (GROUP BY items that are simple Vars should be in the list already),
1813 * and make an array showing where the group columns are in the sub_tlist.
1815 numCols = list_length(parse->groupClause);
1819 AttrNumber *grpColIdx;
1822 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1823 *groupColIdx = grpColIdx;
1825 foreach(gl, parse->groupClause)
1827 SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
1828 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1829 TargetEntry *te = NULL;
1832 /* Find or make a matching sub_tlist entry */
1833 foreach(sl, sub_tlist)
1835 te = (TargetEntry *) lfirst(sl);
1836 if (equal(groupexpr, te->expr))
1841 te = makeTargetEntry((Expr *) groupexpr,
1842 list_length(sub_tlist) + 1,
1845 sub_tlist = lappend(sub_tlist, te);
1846 *need_tlist_eval = true; /* it's not flat anymore */
1849 /* and save its resno */
1850 grpColIdx[keyno++] = te->resno;
1858 * locate_grouping_columns
1859 * Locate grouping columns in the tlist chosen by query_planner.
1861 * This is only needed if we don't use the sub_tlist chosen by
1862 * make_subplanTargetList. We have to forget the column indexes found
1863 * by that routine and re-locate the grouping vars in the real sub_tlist.
1866 locate_grouping_columns(PlannerInfo *root,
1869 AttrNumber *groupColIdx)
1875 * No work unless grouping.
1877 if (!root->parse->groupClause)
1879 Assert(groupColIdx == NULL);
1882 Assert(groupColIdx != NULL);
1884 foreach(gl, root->parse->groupClause)
1886 SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
1887 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1888 TargetEntry *te = NULL;
1891 foreach(sl, sub_tlist)
1893 te = (TargetEntry *) lfirst(sl);
1894 if (equal(groupexpr, te->expr))
1898 elog(ERROR, "failed to locate grouping columns");
1900 groupColIdx[keyno++] = te->resno;
1905 * postprocess_setop_tlist
1906 * Fix up targetlist returned by plan_set_operations().
1908 * We need to transpose sort key info from the orig_tlist into new_tlist.
1909 * NOTE: this would not be good enough if we supported resjunk sort keys
1910 * for results of set operations --- then, we'd need to project a whole
1911 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1912 * find any resjunk columns in orig_tlist.
1915 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1918 ListCell *orig_tlist_item = list_head(orig_tlist);
1920 foreach(l, new_tlist)
1922 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1923 TargetEntry *orig_tle;
1925 /* ignore resjunk columns in setop result */
1926 if (new_tle->resjunk)
1929 Assert(orig_tlist_item != NULL);
1930 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1931 orig_tlist_item = lnext(orig_tlist_item);
1932 if (orig_tle->resjunk) /* should not happen */
1933 elog(ERROR, "resjunk output columns are not implemented");
1934 Assert(new_tle->resno == orig_tle->resno);
1935 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1937 if (orig_tlist_item != NULL)
1938 elog(ERROR, "resjunk output columns are not implemented");