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.235 2008/07/31 22:47:56 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 Oid *extract_grouping_ops(List *groupClause);
71 static bool choose_hashed_grouping(PlannerInfo *root,
72 double tuple_fraction, double limit_tuples,
73 Path *cheapest_path, Path *sorted_path,
74 Oid *groupOperators, double dNumGroups,
75 AggClauseCounts *agg_counts);
76 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
77 AttrNumber **groupColIdx, bool *need_tlist_eval);
78 static void locate_grouping_columns(PlannerInfo *root,
81 AttrNumber *groupColIdx);
82 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
85 /*****************************************************************************
87 * Query optimizer entry point
89 * To support loadable plugins that monitor or modify planner behavior,
90 * we provide a hook variable that lets a plugin get control before and
91 * after the standard planning process. The plugin would normally call
94 * Note to plugin authors: standard_planner() scribbles on its Query input,
95 * so you'd better copy that data structure if you want to plan more than once.
97 *****************************************************************************/
99 planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
104 result = (*planner_hook) (parse, cursorOptions, boundParams);
106 result = standard_planner(parse, cursorOptions, boundParams);
111 standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
115 double tuple_fraction;
121 /* Cursor options may come from caller or from DECLARE CURSOR stmt */
122 if (parse->utilityStmt &&
123 IsA(parse->utilityStmt, DeclareCursorStmt))
124 cursorOptions |= ((DeclareCursorStmt *) parse->utilityStmt)->options;
127 * Set up global state for this planner invocation. This data is needed
128 * across all levels of sub-Query that might exist in the given command,
129 * so we keep it in a separate struct that's linked to by each per-Query
132 glob = makeNode(PlannerGlobal);
134 glob->boundParams = boundParams;
135 glob->paramlist = NIL;
136 glob->subplans = NIL;
137 glob->subrtables = NIL;
138 glob->rewindPlanIDs = NULL;
139 glob->finalrtable = NIL;
140 glob->relationOids = NIL;
141 glob->transientPlan = false;
143 /* Determine what fraction of the plan is likely to be scanned */
144 if (cursorOptions & CURSOR_OPT_FAST_PLAN)
147 * We have no real idea how many tuples the user will ultimately FETCH
148 * from a cursor, but it is often the case that he doesn't want 'em
149 * all, or would prefer a fast-start plan anyway so that he can
150 * process some of the tuples sooner. Use a GUC parameter to decide
151 * what fraction to optimize for.
153 tuple_fraction = cursor_tuple_fraction;
156 * We document cursor_tuple_fraction as simply being a fraction,
157 * which means the edge cases 0 and 1 have to be treated specially
158 * here. We convert 1 to 0 ("all the tuples") and 0 to a very small
161 if (tuple_fraction >= 1.0)
162 tuple_fraction = 0.0;
163 else if (tuple_fraction <= 0.0)
164 tuple_fraction = 1e-10;
168 /* Default assumption is we need all the tuples */
169 tuple_fraction = 0.0;
172 /* primary planning entry point (may recurse for subqueries) */
173 top_plan = subquery_planner(glob, parse, 1, tuple_fraction, &root);
176 * If creating a plan for a scrollable cursor, make sure it can run
177 * backwards on demand. Add a Material node at the top at need.
179 if (cursorOptions & CURSOR_OPT_SCROLL)
181 if (!ExecSupportsBackwardScan(top_plan))
182 top_plan = materialize_finished_plan(top_plan);
185 /* final cleanup of the plan */
186 Assert(glob->finalrtable == NIL);
187 top_plan = set_plan_references(glob, top_plan, root->parse->rtable);
188 /* ... and the subplans (both regular subplans and initplans) */
189 Assert(list_length(glob->subplans) == list_length(glob->subrtables));
190 forboth(lp, glob->subplans, lr, glob->subrtables)
192 Plan *subplan = (Plan *) lfirst(lp);
193 List *subrtable = (List *) lfirst(lr);
195 lfirst(lp) = set_plan_references(glob, subplan, subrtable);
198 /* build the PlannedStmt result */
199 result = makeNode(PlannedStmt);
201 result->commandType = parse->commandType;
202 result->canSetTag = parse->canSetTag;
203 result->transientPlan = glob->transientPlan;
204 result->planTree = top_plan;
205 result->rtable = glob->finalrtable;
206 result->resultRelations = root->resultRelations;
207 result->utilityStmt = parse->utilityStmt;
208 result->intoClause = parse->intoClause;
209 result->subplans = glob->subplans;
210 result->rewindPlanIDs = glob->rewindPlanIDs;
211 result->returningLists = root->returningLists;
212 result->rowMarks = parse->rowMarks;
213 result->relationOids = glob->relationOids;
214 result->nParamExec = list_length(glob->paramlist);
220 /*--------------------
222 * Invokes the planner on a subquery. We recurse to here for each
223 * sub-SELECT found in the query tree.
225 * glob is the global state for the current planner run.
226 * parse is the querytree produced by the parser & rewriter.
227 * level is the current recursion depth (1 at the top-level Query).
228 * tuple_fraction is the fraction of tuples we expect will be retrieved.
229 * tuple_fraction is interpreted as explained for grouping_planner, below.
231 * If subroot isn't NULL, we pass back the query's final PlannerInfo struct;
232 * among other things this tells the output sort ordering of the plan.
234 * Basically, this routine does the stuff that should only be done once
235 * per Query object. It then calls grouping_planner. At one time,
236 * grouping_planner could be invoked recursively on the same Query object;
237 * that's not currently true, but we keep the separation between the two
238 * routines anyway, in case we need it again someday.
240 * subquery_planner will be called recursively to handle sub-Query nodes
241 * found within the query's expressions and rangetable.
243 * Returns a query plan.
244 *--------------------
247 subquery_planner(PlannerGlobal *glob, Query *parse,
248 Index level, double tuple_fraction,
249 PlannerInfo **subroot)
251 int num_old_subplans = list_length(glob->subplans);
257 /* Create a PlannerInfo data structure for this subquery */
258 root = makeNode(PlannerInfo);
261 root->query_level = level;
262 root->planner_cxt = CurrentMemoryContext;
263 root->init_plans = NIL;
264 root->eq_classes = NIL;
265 root->in_info_list = NIL;
266 root->append_rel_list = NIL;
269 * Look for IN clauses at the top level of WHERE, and transform them into
270 * joins. Note that this step only handles IN clauses originally at top
271 * level of WHERE; if we pull up any subqueries below, their INs are
272 * processed just before pulling them up.
274 if (parse->hasSubLinks)
275 parse->jointree->quals = pull_up_IN_clauses(root,
276 parse->jointree->quals);
279 * Scan the rangetable for set-returning functions, and inline them
280 * if possible (producing subqueries that might get pulled up next).
281 * Recursion issues here are handled in the same way as for IN clauses.
283 inline_set_returning_functions(root);
286 * Check to see if any subqueries in the rangetable can be merged into
289 parse->jointree = (FromExpr *)
290 pull_up_subqueries(root, (Node *) parse->jointree, false, false);
293 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
294 * avoid the expense of doing flatten_join_alias_vars(). Also check for
295 * outer joins --- if none, we can skip reduce_outer_joins() and some
296 * other processing. This must be done after we have done
297 * pull_up_subqueries, of course.
299 * Note: if reduce_outer_joins manages to eliminate all outer joins,
300 * root->hasOuterJoins is not reset currently. This is OK since its
301 * purpose is merely to suppress unnecessary processing in simple cases.
303 root->hasJoinRTEs = false;
304 root->hasOuterJoins = false;
305 foreach(l, parse->rtable)
307 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
309 if (rte->rtekind == RTE_JOIN)
311 root->hasJoinRTEs = true;
312 if (IS_OUTER_JOIN(rte->jointype))
314 root->hasOuterJoins = true;
315 /* Can quit scanning once we find an outer join */
322 * Expand any rangetable entries that are inheritance sets into "append
323 * relations". This can add entries to the rangetable, but they must be
324 * plain base relations not joins, so it's OK (and marginally more
325 * efficient) to do it after checking for join RTEs. We must do it after
326 * pulling up subqueries, else we'd fail to handle inherited tables in
329 expand_inherited_tables(root);
332 * Set hasHavingQual to remember if HAVING clause is present. Needed
333 * because preprocess_expression will reduce a constant-true condition to
334 * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
336 root->hasHavingQual = (parse->havingQual != NULL);
338 /* Clear this flag; might get set in distribute_qual_to_rels */
339 root->hasPseudoConstantQuals = false;
342 * Do expression preprocessing on targetlist and quals.
344 parse->targetList = (List *)
345 preprocess_expression(root, (Node *) parse->targetList,
348 parse->returningList = (List *)
349 preprocess_expression(root, (Node *) parse->returningList,
352 preprocess_qual_conditions(root, (Node *) parse->jointree);
354 parse->havingQual = preprocess_expression(root, parse->havingQual,
357 parse->limitOffset = preprocess_expression(root, parse->limitOffset,
359 parse->limitCount = preprocess_expression(root, parse->limitCount,
362 root->in_info_list = (List *)
363 preprocess_expression(root, (Node *) root->in_info_list,
365 root->append_rel_list = (List *)
366 preprocess_expression(root, (Node *) root->append_rel_list,
369 /* Also need to preprocess expressions for function and values RTEs */
370 foreach(l, parse->rtable)
372 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
374 if (rte->rtekind == RTE_FUNCTION)
375 rte->funcexpr = preprocess_expression(root, rte->funcexpr,
377 else if (rte->rtekind == RTE_VALUES)
378 rte->values_lists = (List *)
379 preprocess_expression(root, (Node *) rte->values_lists,
384 * In some cases we may want to transfer a HAVING clause into WHERE. We
385 * cannot do so if the HAVING clause contains aggregates (obviously) or
386 * volatile functions (since a HAVING clause is supposed to be executed
387 * only once per group). Also, it may be that the clause is so expensive
388 * to execute that we're better off doing it only once per group, despite
389 * the loss of selectivity. This is hard to estimate short of doing the
390 * entire planning process twice, so we use a heuristic: clauses
391 * containing subplans are left in HAVING. Otherwise, we move or copy the
392 * HAVING clause into WHERE, in hopes of eliminating tuples before
393 * aggregation instead of after.
395 * If the query has explicit grouping then we can simply move such a
396 * clause into WHERE; any group that fails the clause will not be in the
397 * output because none of its tuples will reach the grouping or
398 * aggregation stage. Otherwise we must have a degenerate (variable-free)
399 * HAVING clause, which we put in WHERE so that query_planner() can use it
400 * in a gating Result node, but also keep in HAVING to ensure that we
401 * don't emit a bogus aggregated row. (This could be done better, but it
402 * seems not worth optimizing.)
404 * Note that both havingQual and parse->jointree->quals are in
405 * implicitly-ANDed-list form at this point, even though they are declared
409 foreach(l, (List *) parse->havingQual)
411 Node *havingclause = (Node *) lfirst(l);
413 if (contain_agg_clause(havingclause) ||
414 contain_volatile_functions(havingclause) ||
415 contain_subplans(havingclause))
417 /* keep it in HAVING */
418 newHaving = lappend(newHaving, havingclause);
420 else if (parse->groupClause)
422 /* move it to WHERE */
423 parse->jointree->quals = (Node *)
424 lappend((List *) parse->jointree->quals, havingclause);
428 /* put a copy in WHERE, keep it in HAVING */
429 parse->jointree->quals = (Node *)
430 lappend((List *) parse->jointree->quals,
431 copyObject(havingclause));
432 newHaving = lappend(newHaving, havingclause);
435 parse->havingQual = (Node *) newHaving;
438 * If we have any outer joins, try to reduce them to plain inner joins.
439 * This step is most easily done after we've done expression
442 if (root->hasOuterJoins)
443 reduce_outer_joins(root);
446 * Do the main planning. If we have an inherited target relation, that
447 * needs special processing, else go straight to grouping_planner.
449 if (parse->resultRelation &&
450 rt_fetch(parse->resultRelation, parse->rtable)->inh)
451 plan = inheritance_planner(root);
453 plan = grouping_planner(root, tuple_fraction);
456 * If any subplans were generated, or if we're inside a subplan, build
457 * initPlan list and extParam/allParam sets for plan nodes, and attach the
458 * initPlans to the top plan node.
460 if (list_length(glob->subplans) != num_old_subplans ||
461 root->query_level > 1)
462 SS_finalize_plan(root, plan, true);
464 /* Return internal info if caller wants it */
472 * preprocess_expression
473 * Do subquery_planner's preprocessing work for an expression,
474 * which can be a targetlist, a WHERE clause (including JOIN/ON
475 * conditions), or a HAVING clause.
478 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
481 * Fall out quickly if expression is empty. This occurs often enough to
482 * be worth checking. Note that null->null is the correct conversion for
483 * implicit-AND result format, too.
489 * If the query has any join RTEs, replace join alias variables with
490 * base-relation variables. We must do this before sublink processing,
491 * else sublinks expanded out from join aliases wouldn't get processed. We
492 * can skip it in VALUES lists, however, since they can't contain any Vars
495 if (root->hasJoinRTEs && kind != EXPRKIND_VALUES)
496 expr = flatten_join_alias_vars(root, expr);
499 * Simplify constant expressions.
501 * Note: this also flattens nested AND and OR expressions into N-argument
502 * form. All processing of a qual expression after this point must be
503 * careful to maintain AND/OR flatness --- that is, do not generate a tree
504 * with AND directly under AND, nor OR directly under OR.
506 * Because this is a relatively expensive process, we skip it when the
507 * query is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()". The
508 * expression will only be evaluated once anyway, so no point in
509 * pre-simplifying; we can't execute it any faster than the executor can,
510 * and we will waste cycles copying the tree. Notice however that we
511 * still must do it for quals (to get AND/OR flatness); and if we are in a
512 * subquery we should not assume it will be done only once.
514 * For VALUES lists we never do this at all, again on the grounds that we
515 * should optimize for one-time evaluation.
517 if (kind != EXPRKIND_VALUES &&
518 (root->parse->jointree->fromlist != NIL ||
519 kind == EXPRKIND_QUAL ||
520 root->query_level > 1))
521 expr = eval_const_expressions(root, expr);
524 * If it's a qual or havingQual, canonicalize it.
526 if (kind == EXPRKIND_QUAL)
528 expr = (Node *) canonicalize_qual((Expr *) expr);
530 #ifdef OPTIMIZER_DEBUG
531 printf("After canonicalize_qual()\n");
536 /* Expand SubLinks to SubPlans */
537 if (root->parse->hasSubLinks)
538 expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
541 * XXX do not insert anything here unless you have grokked the comments in
542 * SS_replace_correlation_vars ...
545 /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
546 if (root->query_level > 1)
547 expr = SS_replace_correlation_vars(root, expr);
550 * If it's a qual or havingQual, convert it to implicit-AND format. (We
551 * don't want to do this before eval_const_expressions, since the latter
552 * would be unable to simplify a top-level AND correctly. Also,
553 * SS_process_sublinks expects explicit-AND format.)
555 if (kind == EXPRKIND_QUAL)
556 expr = (Node *) make_ands_implicit((Expr *) expr);
562 * preprocess_qual_conditions
563 * Recursively scan the query's jointree and do subquery_planner's
564 * preprocessing work on each qual condition found therein.
567 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
571 if (IsA(jtnode, RangeTblRef))
573 /* nothing to do here */
575 else if (IsA(jtnode, FromExpr))
577 FromExpr *f = (FromExpr *) jtnode;
580 foreach(l, f->fromlist)
581 preprocess_qual_conditions(root, lfirst(l));
583 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
585 else if (IsA(jtnode, JoinExpr))
587 JoinExpr *j = (JoinExpr *) jtnode;
589 preprocess_qual_conditions(root, j->larg);
590 preprocess_qual_conditions(root, j->rarg);
592 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
595 elog(ERROR, "unrecognized node type: %d",
596 (int) nodeTag(jtnode));
600 * inheritance_planner
601 * Generate a plan in the case where the result relation is an
604 * We have to handle this case differently from cases where a source relation
605 * is an inheritance set. Source inheritance is expanded at the bottom of the
606 * plan tree (see allpaths.c), but target inheritance has to be expanded at
607 * the top. The reason is that for UPDATE, each target relation needs a
608 * different targetlist matching its own column set. Also, for both UPDATE
609 * and DELETE, the executor needs the Append plan node at the top, else it
610 * can't keep track of which table is the current target table. Fortunately,
611 * the UPDATE/DELETE target can never be the nullable side of an outer join,
612 * so it's OK to generate the plan this way.
614 * Returns a query plan.
617 inheritance_planner(PlannerInfo *root)
619 Query *parse = root->parse;
620 int parentRTindex = parse->resultRelation;
621 List *subplans = NIL;
622 List *resultRelations = NIL;
623 List *returningLists = NIL;
629 foreach(l, root->append_rel_list)
631 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
634 /* append_rel_list contains all append rels; ignore others */
635 if (appinfo->parent_relid != parentRTindex)
639 * Generate modified query with this rel as target. We have to be
640 * prepared to translate varnos in in_info_list as well as in the
643 memcpy(&subroot, root, sizeof(PlannerInfo));
644 subroot.parse = (Query *)
645 adjust_appendrel_attrs((Node *) parse,
647 subroot.in_info_list = (List *)
648 adjust_appendrel_attrs((Node *) root->in_info_list,
650 subroot.init_plans = NIL;
651 /* There shouldn't be any OJ info to translate, as yet */
652 Assert(subroot.oj_info_list == NIL);
655 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
658 * If this child rel was excluded by constraint exclusion, exclude it
661 if (is_dummy_plan(subplan))
664 /* Save rtable and tlist from first rel for use below */
667 rtable = subroot.parse->rtable;
668 tlist = subplan->targetlist;
671 subplans = lappend(subplans, subplan);
673 /* Make sure any initplans from this rel get into the outer list */
674 root->init_plans = list_concat(root->init_plans, subroot.init_plans);
676 /* Build target-relations list for the executor */
677 resultRelations = lappend_int(resultRelations, appinfo->child_relid);
679 /* Build list of per-relation RETURNING targetlists */
680 if (parse->returningList)
682 Assert(list_length(subroot.returningLists) == 1);
683 returningLists = list_concat(returningLists,
684 subroot.returningLists);
688 root->resultRelations = resultRelations;
689 root->returningLists = returningLists;
691 /* Mark result as unordered (probably unnecessary) */
692 root->query_pathkeys = NIL;
695 * If we managed to exclude every child rel, return a dummy plan
699 root->resultRelations = list_make1_int(parentRTindex);
700 /* although dummy, it must have a valid tlist for executor */
701 tlist = preprocess_targetlist(root, parse->targetList);
702 return (Plan *) make_result(root,
704 (Node *) list_make1(makeBoolConst(false,
710 * Planning might have modified the rangetable, due to changes of the
711 * Query structures inside subquery RTEs. We have to ensure that this
712 * gets propagated back to the master copy. But can't do this until we
713 * are done planning, because all the calls to grouping_planner need
714 * virgin sub-Queries to work from. (We are effectively assuming that
715 * sub-Queries will get planned identically each time, or at least that
716 * the impacts on their rangetables will be the same each time.)
718 * XXX should clean this up someday
720 parse->rtable = rtable;
722 /* Suppress Append if there's only one surviving child rel */
723 if (list_length(subplans) == 1)
724 return (Plan *) linitial(subplans);
726 return (Plan *) make_append(subplans, true, tlist);
729 /*--------------------
731 * Perform planning steps related to grouping, aggregation, etc.
732 * This primarily means adding top-level processing to the basic
733 * query plan produced by query_planner.
735 * tuple_fraction is the fraction of tuples we expect will be retrieved
737 * tuple_fraction is interpreted as follows:
738 * 0: expect all tuples to be retrieved (normal case)
739 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
740 * from the plan to be retrieved
741 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
742 * expected to be retrieved (ie, a LIMIT specification)
744 * Returns a query plan. Also, root->query_pathkeys is returned as the
745 * actual output ordering of the plan (in pathkey format).
746 *--------------------
749 grouping_planner(PlannerInfo *root, double tuple_fraction)
751 Query *parse = root->parse;
752 List *tlist = parse->targetList;
753 int64 offset_est = 0;
755 double limit_tuples = -1.0;
757 List *current_pathkeys;
759 double dNumGroups = 0;
761 /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
762 if (parse->limitCount || parse->limitOffset)
764 tuple_fraction = preprocess_limit(root, tuple_fraction,
765 &offset_est, &count_est);
768 * If we have a known LIMIT, and don't have an unknown OFFSET, we can
769 * estimate the effects of using a bounded sort.
771 if (count_est > 0 && offset_est >= 0)
772 limit_tuples = (double) count_est + (double) offset_est;
775 if (parse->setOperations)
777 List *set_sortclauses;
780 * If there's a top-level ORDER BY, assume we have to fetch all the
781 * tuples. This might seem too simplistic given all the hackery below
782 * to possibly avoid the sort ... but a nonzero tuple_fraction is only
783 * of use to plan_set_operations() when the setop is UNION ALL, and
784 * the result of UNION ALL is always unsorted.
786 if (parse->sortClause)
787 tuple_fraction = 0.0;
790 * Construct the plan for set operations. The result will not need
791 * any work except perhaps a top-level sort and/or LIMIT.
793 result_plan = plan_set_operations(root, tuple_fraction,
797 * Calculate pathkeys representing the sort order (if any) of the set
798 * operation's result. We have to do this before overwriting the sort
801 current_pathkeys = make_pathkeys_for_sortclauses(root,
803 result_plan->targetlist,
807 * We should not need to call preprocess_targetlist, since we must be
808 * in a SELECT query node. Instead, use the targetlist returned by
809 * plan_set_operations (since this tells whether it returned any
810 * resjunk columns!), and transfer any sort key information from the
813 Assert(parse->commandType == CMD_SELECT);
815 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
818 * Can't handle FOR UPDATE/SHARE here (parser should have checked
819 * already, but let's make sure).
823 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
824 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
827 * Calculate pathkeys that represent result ordering requirements
829 Assert(parse->distinctClause == NIL);
830 sort_pathkeys = make_pathkeys_for_sortclauses(root,
837 /* No set operations, do regular planning */
839 List *group_pathkeys;
840 AttrNumber *groupColIdx = NULL;
841 Oid *groupOperators = NULL;
842 bool need_tlist_eval = true;
848 AggClauseCounts agg_counts;
849 int numGroupCols = list_length(parse->groupClause);
850 bool use_hashed_grouping = false;
852 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
854 /* Preprocess targetlist */
855 tlist = preprocess_targetlist(root, tlist);
858 * Generate appropriate target list for subplan; may be different from
859 * tlist if grouping or aggregation is needed.
861 sub_tlist = make_subplanTargetList(root, tlist,
862 &groupColIdx, &need_tlist_eval);
865 * Calculate pathkeys that represent grouping/ordering requirements.
866 * Stash them in PlannerInfo so that query_planner can canonicalize
867 * them after EquivalenceClasses have been formed.
869 * Note: for the moment, DISTINCT is always implemented via sort/uniq,
870 * and we set the sort_pathkeys to be the more rigorous of the
871 * DISTINCT and ORDER BY requirements. This should be changed
872 * someday, but DISTINCT ON is a bit of a problem ...
874 root->group_pathkeys =
875 make_pathkeys_for_sortclauses(root,
879 if (list_length(parse->distinctClause) > list_length(parse->sortClause))
880 root->sort_pathkeys =
881 make_pathkeys_for_sortclauses(root,
882 parse->distinctClause,
886 root->sort_pathkeys =
887 make_pathkeys_for_sortclauses(root,
893 * Will need actual number of aggregates for estimating costs.
895 * Note: we do not attempt to detect duplicate aggregates here; a
896 * somewhat-overestimated count is okay for our present purposes.
898 * Note: think not that we can turn off hasAggs if we find no aggs. It
899 * is possible for constant-expression simplification to remove all
900 * explicit references to aggs, but we still have to follow the
901 * aggregate semantics (eg, producing only one output row).
905 count_agg_clauses((Node *) tlist, &agg_counts);
906 count_agg_clauses(parse->havingQual, &agg_counts);
910 * Figure out whether we need a sorted result from query_planner.
912 * If we have a GROUP BY clause, then we want a result sorted properly
913 * for grouping. Otherwise, if there is an ORDER BY clause, we want
914 * to sort by the ORDER BY clause. (Note: if we have both, and ORDER
915 * BY is a superset of GROUP BY, it would be tempting to request sort
916 * by ORDER BY --- but that might just leave us failing to exploit an
917 * available sort order at all. Needs more thought...)
919 if (root->group_pathkeys)
920 root->query_pathkeys = root->group_pathkeys;
921 else if (root->sort_pathkeys)
922 root->query_pathkeys = root->sort_pathkeys;
924 root->query_pathkeys = NIL;
927 * Generate the best unsorted and presorted paths for this Query (but
928 * note there may not be any presorted path). query_planner will also
929 * estimate the number of groups in the query, and canonicalize all
932 query_planner(root, sub_tlist, tuple_fraction, limit_tuples,
933 &cheapest_path, &sorted_path, &dNumGroups);
935 group_pathkeys = root->group_pathkeys;
936 sort_pathkeys = root->sort_pathkeys;
939 * If grouping, extract the grouping operators and decide whether we
940 * want to use hashed grouping.
942 if (parse->groupClause)
944 groupOperators = extract_grouping_ops(parse->groupClause);
945 use_hashed_grouping =
946 choose_hashed_grouping(root, tuple_fraction, limit_tuples,
947 cheapest_path, sorted_path,
948 groupOperators, dNumGroups,
951 /* Also convert # groups to long int --- but 'ware overflow! */
952 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
956 * Select the best path. If we are doing hashed grouping, we will
957 * always read all the input tuples, so use the cheapest-total path.
958 * Otherwise, trust query_planner's decision about which to use.
960 if (use_hashed_grouping || !sorted_path)
961 best_path = cheapest_path;
963 best_path = sorted_path;
966 * Check to see if it's possible to optimize MIN/MAX aggregates. If
967 * so, we will forget all the work we did so far to choose a "regular"
968 * path ... but we had to do it anyway to be able to tell which way is
971 result_plan = optimize_minmax_aggregates(root,
974 if (result_plan != NULL)
977 * optimize_minmax_aggregates generated the full plan, with the
978 * right tlist, and it has no sort order.
980 current_pathkeys = NIL;
985 * Normal case --- create a plan according to query_planner's
988 bool need_sort_for_grouping = false;
990 result_plan = create_plan(root, best_path);
991 current_pathkeys = best_path->pathkeys;
993 /* Detect if we'll need an explicit sort for grouping */
994 if (parse->groupClause && !use_hashed_grouping &&
995 !pathkeys_contained_in(group_pathkeys, current_pathkeys))
997 need_sort_for_grouping = true;
999 * Always override query_planner's tlist, so that we don't
1000 * sort useless data from a "physical" tlist.
1002 need_tlist_eval = true;
1006 * create_plan() returns a plan with just a "flat" tlist of
1007 * required Vars. Usually we need to insert the sub_tlist as the
1008 * tlist of the top plan node. However, we can skip that if we
1009 * determined that whatever query_planner chose to return will be
1012 if (need_tlist_eval)
1015 * If the top-level plan node is one that cannot do expression
1016 * evaluation, we must insert a Result node to project the
1019 if (!is_projection_capable_plan(result_plan))
1021 result_plan = (Plan *) make_result(root,
1029 * Otherwise, just replace the subplan's flat tlist with
1030 * the desired tlist.
1032 result_plan->targetlist = sub_tlist;
1036 * Also, account for the cost of evaluation of the sub_tlist.
1038 * Up to now, we have only been dealing with "flat" tlists,
1039 * containing just Vars. So their evaluation cost is zero
1040 * according to the model used by cost_qual_eval() (or if you
1041 * prefer, the cost is factored into cpu_tuple_cost). Thus we
1042 * can avoid accounting for tlist cost throughout
1043 * query_planner() and subroutines. But now we've inserted a
1044 * tlist that might contain actual operators, sub-selects, etc
1045 * --- so we'd better account for its cost.
1047 * Below this point, any tlist eval cost for added-on nodes
1048 * should be accounted for as we create those nodes.
1049 * Presently, of the node types we can add on, only Agg and
1050 * Group project new tlists (the rest just copy their input
1051 * tuples) --- so make_agg() and make_group() are responsible
1052 * for computing the added cost.
1054 cost_qual_eval(&tlist_cost, sub_tlist, root);
1055 result_plan->startup_cost += tlist_cost.startup;
1056 result_plan->total_cost += tlist_cost.startup +
1057 tlist_cost.per_tuple * result_plan->plan_rows;
1062 * Since we're using query_planner's tlist and not the one
1063 * make_subplanTargetList calculated, we have to refigure any
1064 * grouping-column indexes make_subplanTargetList computed.
1066 locate_grouping_columns(root, tlist, result_plan->targetlist,
1071 * Insert AGG or GROUP node if needed, plus an explicit sort step
1074 * HAVING clause, if any, becomes qual of the Agg or Group node.
1076 if (use_hashed_grouping)
1078 /* Hashed aggregate plan --- no sort needed */
1079 result_plan = (Plan *) make_agg(root,
1081 (List *) parse->havingQual,
1089 /* Hashed aggregation produces randomly-ordered results */
1090 current_pathkeys = NIL;
1092 else if (parse->hasAggs)
1094 /* Plain aggregate plan --- sort if needed */
1095 AggStrategy aggstrategy;
1097 if (parse->groupClause)
1099 if (need_sort_for_grouping)
1101 result_plan = (Plan *)
1102 make_sort_from_groupcols(root,
1106 current_pathkeys = group_pathkeys;
1108 aggstrategy = AGG_SORTED;
1111 * The AGG node will not change the sort ordering of its
1112 * groups, so current_pathkeys describes the result too.
1117 aggstrategy = AGG_PLAIN;
1118 /* Result will be only one row anyway; no sort order */
1119 current_pathkeys = NIL;
1122 result_plan = (Plan *) make_agg(root,
1124 (List *) parse->havingQual,
1133 else if (parse->groupClause)
1136 * GROUP BY without aggregation, so insert a group node (plus
1137 * the appropriate sort node, if necessary).
1139 * Add an explicit sort if we couldn't make the path come out
1140 * the way the GROUP node needs it.
1142 if (need_sort_for_grouping)
1144 result_plan = (Plan *)
1145 make_sort_from_groupcols(root,
1149 current_pathkeys = group_pathkeys;
1152 result_plan = (Plan *) make_group(root,
1154 (List *) parse->havingQual,
1160 /* The Group node won't change sort ordering */
1162 else if (root->hasHavingQual)
1165 * No aggregates, and no GROUP BY, but we have a HAVING qual.
1166 * This is a degenerate case in which we are supposed to emit
1167 * either 0 or 1 row depending on whether HAVING succeeds.
1168 * Furthermore, there cannot be any variables in either HAVING
1169 * or the targetlist, so we actually do not need the FROM
1170 * table at all! We can just throw away the plan-so-far and
1171 * generate a Result node. This is a sufficiently unusual
1172 * corner case that it's not worth contorting the structure of
1173 * this routine to avoid having to generate the plan in the
1176 result_plan = (Plan *) make_result(root,
1181 } /* end of non-minmax-aggregate case */
1182 } /* end of if (setOperations) */
1185 * If we were not able to make the plan come out in the right order, add
1186 * an explicit sort step.
1190 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1192 result_plan = (Plan *) make_sort_from_pathkeys(root,
1196 current_pathkeys = sort_pathkeys;
1201 * If there is a DISTINCT clause, add the UNIQUE node.
1203 if (parse->distinctClause)
1205 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1208 * If there was grouping or aggregation, leave plan_rows as-is (ie,
1209 * assume the result was already mostly unique). If not, use the
1210 * number of distinct-groups calculated by query_planner.
1212 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1213 result_plan->plan_rows = dNumGroups;
1217 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1219 if (parse->limitCount || parse->limitOffset)
1221 result_plan = (Plan *) make_limit(result_plan,
1229 * Deal with the RETURNING clause if any. It's convenient to pass the
1230 * returningList through setrefs.c now rather than at top level (if we
1231 * waited, handling inherited UPDATE/DELETE would be much harder).
1233 if (parse->returningList)
1237 Assert(parse->resultRelation);
1238 rlist = set_returning_clause_references(root->glob,
1239 parse->returningList,
1241 parse->resultRelation);
1242 root->returningLists = list_make1(rlist);
1245 root->returningLists = NIL;
1247 /* Compute result-relations list if needed */
1248 if (parse->resultRelation)
1249 root->resultRelations = list_make1_int(parse->resultRelation);
1251 root->resultRelations = NIL;
1254 * Return the actual output ordering in query_pathkeys for possible use by
1255 * an outer query level.
1257 root->query_pathkeys = current_pathkeys;
1263 * Detect whether a plan node is a "dummy" plan created when a relation
1264 * is deemed not to need scanning due to constraint exclusion.
1266 * Currently, such dummy plans are Result nodes with constant FALSE
1270 is_dummy_plan(Plan *plan)
1272 if (IsA(plan, Result))
1274 List *rcqual = (List *) ((Result *) plan)->resconstantqual;
1276 if (list_length(rcqual) == 1)
1278 Const *constqual = (Const *) linitial(rcqual);
1280 if (constqual && IsA(constqual, Const))
1282 if (!constqual->constisnull &&
1283 !DatumGetBool(constqual->constvalue))
1292 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1294 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1295 * results back in *count_est and *offset_est. These variables are set to
1296 * 0 if the corresponding clause is not present, and -1 if it's present
1297 * but we couldn't estimate the value for it. (The "0" convention is OK
1298 * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1299 * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
1300 * usual practice of never estimating less than one row.) These values will
1301 * be passed to make_limit, which see if you change this code.
1303 * The return value is the suitably adjusted tuple_fraction to use for
1304 * planning the query. This adjustment is not overridable, since it reflects
1305 * plan actions that grouping_planner() will certainly take, not assumptions
1309 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1310 int64 *offset_est, int64 *count_est)
1312 Query *parse = root->parse;
1314 double limit_fraction;
1316 /* Should not be called unless LIMIT or OFFSET */
1317 Assert(parse->limitCount || parse->limitOffset);
1320 * Try to obtain the clause values. We use estimate_expression_value
1321 * primarily because it can sometimes do something useful with Params.
1323 if (parse->limitCount)
1325 est = estimate_expression_value(root, parse->limitCount);
1326 if (est && IsA(est, Const))
1328 if (((Const *) est)->constisnull)
1330 /* NULL indicates LIMIT ALL, ie, no limit */
1331 *count_est = 0; /* treat as not present */
1335 *count_est = DatumGetInt64(((Const *) est)->constvalue);
1336 if (*count_est <= 0)
1337 *count_est = 1; /* force to at least 1 */
1341 *count_est = -1; /* can't estimate */
1344 *count_est = 0; /* not present */
1346 if (parse->limitOffset)
1348 est = estimate_expression_value(root, parse->limitOffset);
1349 if (est && IsA(est, Const))
1351 if (((Const *) est)->constisnull)
1353 /* Treat NULL as no offset; the executor will too */
1354 *offset_est = 0; /* treat as not present */
1358 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
1359 if (*offset_est < 0)
1360 *offset_est = 0; /* less than 0 is same as 0 */
1364 *offset_est = -1; /* can't estimate */
1367 *offset_est = 0; /* not present */
1369 if (*count_est != 0)
1372 * A LIMIT clause limits the absolute number of tuples returned.
1373 * However, if it's not a constant LIMIT then we have to guess; for
1374 * lack of a better idea, assume 10% of the plan's result is wanted.
1376 if (*count_est < 0 || *offset_est < 0)
1378 /* LIMIT or OFFSET is an expression ... punt ... */
1379 limit_fraction = 0.10;
1383 /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
1384 limit_fraction = (double) *count_est + (double) *offset_est;
1388 * If we have absolute limits from both caller and LIMIT, use the
1389 * smaller value; likewise if they are both fractional. If one is
1390 * fractional and the other absolute, we can't easily determine which
1391 * is smaller, but we use the heuristic that the absolute will usually
1394 if (tuple_fraction >= 1.0)
1396 if (limit_fraction >= 1.0)
1399 tuple_fraction = Min(tuple_fraction, limit_fraction);
1403 /* caller absolute, limit fractional; use caller's value */
1406 else if (tuple_fraction > 0.0)
1408 if (limit_fraction >= 1.0)
1410 /* caller fractional, limit absolute; use limit */
1411 tuple_fraction = limit_fraction;
1415 /* both fractional */
1416 tuple_fraction = Min(tuple_fraction, limit_fraction);
1421 /* no info from caller, just use limit */
1422 tuple_fraction = limit_fraction;
1425 else if (*offset_est != 0 && tuple_fraction > 0.0)
1428 * We have an OFFSET but no LIMIT. This acts entirely differently
1429 * from the LIMIT case: here, we need to increase rather than decrease
1430 * the caller's tuple_fraction, because the OFFSET acts to cause more
1431 * tuples to be fetched instead of fewer. This only matters if we got
1432 * a tuple_fraction > 0, however.
1434 * As above, use 10% if OFFSET is present but unestimatable.
1436 if (*offset_est < 0)
1437 limit_fraction = 0.10;
1439 limit_fraction = (double) *offset_est;
1442 * If we have absolute counts from both caller and OFFSET, add them
1443 * together; likewise if they are both fractional. If one is
1444 * fractional and the other absolute, we want to take the larger, and
1445 * we heuristically assume that's the fractional one.
1447 if (tuple_fraction >= 1.0)
1449 if (limit_fraction >= 1.0)
1451 /* both absolute, so add them together */
1452 tuple_fraction += limit_fraction;
1456 /* caller absolute, limit fractional; use limit */
1457 tuple_fraction = limit_fraction;
1462 if (limit_fraction >= 1.0)
1464 /* caller fractional, limit absolute; use caller's value */
1468 /* both fractional, so add them together */
1469 tuple_fraction += limit_fraction;
1470 if (tuple_fraction >= 1.0)
1471 tuple_fraction = 0.0; /* assume fetch all */
1476 return tuple_fraction;
1480 * extract_grouping_ops - make an array of the equality operator OIDs
1481 * for the GROUP BY clause
1484 extract_grouping_ops(List *groupClause)
1486 int numCols = list_length(groupClause);
1488 Oid *groupOperators;
1491 groupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
1493 foreach(glitem, groupClause)
1495 GroupClause *groupcl = (GroupClause *) lfirst(glitem);
1497 groupOperators[colno] = get_equality_op_for_ordering_op(groupcl->sortop);
1498 if (!OidIsValid(groupOperators[colno])) /* shouldn't happen */
1499 elog(ERROR, "could not find equality operator for ordering operator %u",
1504 return groupOperators;
1508 * choose_hashed_grouping - should we use hashed grouping?
1511 choose_hashed_grouping(PlannerInfo *root,
1512 double tuple_fraction, double limit_tuples,
1513 Path *cheapest_path, Path *sorted_path,
1514 Oid *groupOperators, double dNumGroups,
1515 AggClauseCounts *agg_counts)
1517 int numGroupCols = list_length(root->parse->groupClause);
1518 double cheapest_path_rows;
1519 int cheapest_path_width;
1521 List *current_pathkeys;
1527 * Check can't-do-it conditions, including whether the grouping operators
1528 * are hashjoinable. (We assume hashing is OK if they are marked
1529 * oprcanhash. If there isn't actually a supporting hash function, the
1530 * executor will complain at runtime.)
1532 * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1533 * (Doing so would imply storing *all* the input values in the hash table,
1534 * which seems like a certain loser.)
1536 if (!enable_hashagg)
1538 if (agg_counts->numDistinctAggs != 0)
1540 for (i = 0; i < numGroupCols; i++)
1542 if (!op_hashjoinable(groupOperators[i]))
1547 * Don't do it if it doesn't look like the hashtable will fit into
1550 * Beware here of the possibility that cheapest_path->parent is NULL. This
1551 * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
1553 if (cheapest_path->parent)
1555 cheapest_path_rows = cheapest_path->parent->rows;
1556 cheapest_path_width = cheapest_path->parent->width;
1560 cheapest_path_rows = 1; /* assume non-set result */
1561 cheapest_path_width = 100; /* arbitrary */
1564 /* Estimate per-hash-entry space at tuple width... */
1565 hashentrysize = MAXALIGN(cheapest_path_width) + MAXALIGN(sizeof(MinimalTupleData));
1566 /* plus space for pass-by-ref transition values... */
1567 hashentrysize += agg_counts->transitionSpace;
1568 /* plus the per-hash-entry overhead */
1569 hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1571 if (hashentrysize * dNumGroups > work_mem * 1024L)
1575 * See if the estimated cost is no more than doing it the other way. While
1576 * avoiding the need for sorted input is usually a win, the fact that the
1577 * output won't be sorted may be a loss; so we need to do an actual cost
1580 * We need to consider cheapest_path + hashagg [+ final sort] versus
1581 * either cheapest_path [+ sort] + group or agg [+ final sort] or
1582 * presorted_path + group or agg [+ final sort] where brackets indicate a
1583 * step that may not be needed. We assume query_planner() will have
1584 * returned a presorted path only if it's a winner compared to
1585 * cheapest_path for this purpose.
1587 * These path variables are dummies that just hold cost fields; we don't
1588 * make actual Paths for these steps.
1590 cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1591 numGroupCols, dNumGroups,
1592 cheapest_path->startup_cost, cheapest_path->total_cost,
1593 cheapest_path_rows);
1594 /* Result of hashed agg is always unsorted */
1595 if (root->sort_pathkeys)
1596 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
1597 dNumGroups, cheapest_path_width, limit_tuples);
1601 sorted_p.startup_cost = sorted_path->startup_cost;
1602 sorted_p.total_cost = sorted_path->total_cost;
1603 current_pathkeys = sorted_path->pathkeys;
1607 sorted_p.startup_cost = cheapest_path->startup_cost;
1608 sorted_p.total_cost = cheapest_path->total_cost;
1609 current_pathkeys = cheapest_path->pathkeys;
1611 if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1613 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
1614 cheapest_path_rows, cheapest_path_width, -1.0);
1615 current_pathkeys = root->group_pathkeys;
1618 if (root->parse->hasAggs)
1619 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1620 numGroupCols, dNumGroups,
1621 sorted_p.startup_cost, sorted_p.total_cost,
1622 cheapest_path_rows);
1624 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1625 sorted_p.startup_cost, sorted_p.total_cost,
1626 cheapest_path_rows);
1627 /* The Agg or Group node will preserve ordering */
1628 if (root->sort_pathkeys &&
1629 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1630 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
1631 dNumGroups, cheapest_path_width, limit_tuples);
1634 * Now make the decision using the top-level tuple fraction. First we
1635 * have to convert an absolute count (LIMIT) into fractional form.
1637 if (tuple_fraction >= 1.0)
1638 tuple_fraction /= dNumGroups;
1640 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1641 tuple_fraction) < 0)
1643 /* Hashed is cheaper, so use it */
1650 * make_subplanTargetList
1651 * Generate appropriate target list when grouping is required.
1653 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1654 * above the result of query_planner, we typically want to pass a different
1655 * target list to query_planner than the outer plan nodes should have.
1656 * This routine generates the correct target list for the subplan.
1658 * The initial target list passed from the parser already contains entries
1659 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1660 * for variables used only in HAVING clauses; so we need to add those
1661 * variables to the subplan target list. Also, we flatten all expressions
1662 * except GROUP BY items into their component variables; the other expressions
1663 * will be computed by the inserted nodes rather than by the subplan.
1664 * For example, given a query like
1665 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1666 * we want to pass this targetlist to the subplan:
1668 * where the a+b target will be used by the Sort/Group steps, and the
1669 * other targets will be used for computing the final results. (In the
1670 * above example we could theoretically suppress the a and b targets and
1671 * pass down only c,d,a+b, but it's not really worth the trouble to
1672 * eliminate simple var references from the subplan. We will avoid doing
1673 * the extra computation to recompute a+b at the outer level; see
1674 * fix_upper_expr() in setrefs.c.)
1676 * If we are grouping or aggregating, *and* there are no non-Var grouping
1677 * expressions, then the returned tlist is effectively dummy; we do not
1678 * need to force it to be evaluated, because all the Vars it contains
1679 * should be present in the output of query_planner anyway.
1681 * 'tlist' is the query's target list.
1682 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1683 * expressions (if there are any) in the subplan's target list.
1684 * 'need_tlist_eval' is set true if we really need to evaluate the
1687 * The result is the targetlist to be passed to the subplan.
1691 make_subplanTargetList(PlannerInfo *root,
1693 AttrNumber **groupColIdx,
1694 bool *need_tlist_eval)
1696 Query *parse = root->parse;
1701 *groupColIdx = NULL;
1704 * If we're not grouping or aggregating, there's nothing to do here;
1705 * query_planner should receive the unmodified target list.
1707 if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1709 *need_tlist_eval = true;
1714 * Otherwise, start with a "flattened" tlist (having just the vars
1715 * mentioned in the targetlist and HAVING qual --- but not upper- level
1716 * Vars; they will be replaced by Params later on).
1718 sub_tlist = flatten_tlist(tlist);
1719 extravars = pull_var_clause(parse->havingQual, false);
1720 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1721 list_free(extravars);
1722 *need_tlist_eval = false; /* only eval if not flat tlist */
1725 * If grouping, create sub_tlist entries for all GROUP BY expressions
1726 * (GROUP BY items that are simple Vars should be in the list already),
1727 * and make an array showing where the group columns are in the sub_tlist.
1729 numCols = list_length(parse->groupClause);
1733 AttrNumber *grpColIdx;
1736 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1737 *groupColIdx = grpColIdx;
1739 foreach(gl, parse->groupClause)
1741 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1742 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1743 TargetEntry *te = NULL;
1746 /* Find or make a matching sub_tlist entry */
1747 foreach(sl, sub_tlist)
1749 te = (TargetEntry *) lfirst(sl);
1750 if (equal(groupexpr, te->expr))
1755 te = makeTargetEntry((Expr *) groupexpr,
1756 list_length(sub_tlist) + 1,
1759 sub_tlist = lappend(sub_tlist, te);
1760 *need_tlist_eval = true; /* it's not flat anymore */
1763 /* and save its resno */
1764 grpColIdx[keyno++] = te->resno;
1772 * locate_grouping_columns
1773 * Locate grouping columns in the tlist chosen by query_planner.
1775 * This is only needed if we don't use the sub_tlist chosen by
1776 * make_subplanTargetList. We have to forget the column indexes found
1777 * by that routine and re-locate the grouping vars in the real sub_tlist.
1780 locate_grouping_columns(PlannerInfo *root,
1783 AttrNumber *groupColIdx)
1789 * No work unless grouping.
1791 if (!root->parse->groupClause)
1793 Assert(groupColIdx == NULL);
1796 Assert(groupColIdx != NULL);
1798 foreach(gl, root->parse->groupClause)
1800 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1801 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1802 TargetEntry *te = NULL;
1805 foreach(sl, sub_tlist)
1807 te = (TargetEntry *) lfirst(sl);
1808 if (equal(groupexpr, te->expr))
1812 elog(ERROR, "failed to locate grouping columns");
1814 groupColIdx[keyno++] = te->resno;
1819 * postprocess_setop_tlist
1820 * Fix up targetlist returned by plan_set_operations().
1822 * We need to transpose sort key info from the orig_tlist into new_tlist.
1823 * NOTE: this would not be good enough if we supported resjunk sort keys
1824 * for results of set operations --- then, we'd need to project a whole
1825 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1826 * find any resjunk columns in orig_tlist.
1829 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1832 ListCell *orig_tlist_item = list_head(orig_tlist);
1834 foreach(l, new_tlist)
1836 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1837 TargetEntry *orig_tle;
1839 /* ignore resjunk columns in setop result */
1840 if (new_tle->resjunk)
1843 Assert(orig_tlist_item != NULL);
1844 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1845 orig_tlist_item = lnext(orig_tlist_item);
1846 if (orig_tle->resjunk) /* should not happen */
1847 elog(ERROR, "resjunk output columns are not implemented");
1848 Assert(new_tle->resno == orig_tle->resno);
1849 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1851 if (orig_tlist_item != NULL)
1852 elog(ERROR, "resjunk output columns are not implemented");