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.233 2008/05/02 21:26:09 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);
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 sort_pathkeys = make_pathkeys_for_sortclauses(root,
836 /* No set operations, do regular planning */
838 List *group_pathkeys;
839 AttrNumber *groupColIdx = NULL;
840 Oid *groupOperators = NULL;
841 bool need_tlist_eval = true;
847 AggClauseCounts agg_counts;
848 int numGroupCols = list_length(parse->groupClause);
849 bool use_hashed_grouping = false;
851 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
853 /* Preprocess targetlist */
854 tlist = preprocess_targetlist(root, tlist);
857 * Generate appropriate target list for subplan; may be different from
858 * tlist if grouping or aggregation is needed.
860 sub_tlist = make_subplanTargetList(root, tlist,
861 &groupColIdx, &need_tlist_eval);
864 * Calculate pathkeys that represent grouping/ordering requirements.
865 * Stash them in PlannerInfo so that query_planner can canonicalize
866 * them after EquivalenceClasses have been formed.
868 root->group_pathkeys =
869 make_pathkeys_for_sortclauses(root,
873 root->sort_pathkeys =
874 make_pathkeys_for_sortclauses(root,
880 * Will need actual number of aggregates for estimating costs.
882 * Note: we do not attempt to detect duplicate aggregates here; a
883 * somewhat-overestimated count is okay for our present purposes.
885 * Note: think not that we can turn off hasAggs if we find no aggs. It
886 * is possible for constant-expression simplification to remove all
887 * explicit references to aggs, but we still have to follow the
888 * aggregate semantics (eg, producing only one output row).
892 count_agg_clauses((Node *) tlist, &agg_counts);
893 count_agg_clauses(parse->havingQual, &agg_counts);
897 * Figure out whether we need a sorted result from query_planner.
899 * If we have a GROUP BY clause, then we want a result sorted properly
900 * for grouping. Otherwise, if there is an ORDER BY clause, we want
901 * to sort by the ORDER BY clause. (Note: if we have both, and ORDER
902 * BY is a superset of GROUP BY, it would be tempting to request sort
903 * by ORDER BY --- but that might just leave us failing to exploit an
904 * available sort order at all. Needs more thought...)
906 if (parse->groupClause)
907 root->query_pathkeys = root->group_pathkeys;
908 else if (parse->sortClause)
909 root->query_pathkeys = root->sort_pathkeys;
911 root->query_pathkeys = NIL;
914 * Generate the best unsorted and presorted paths for this Query (but
915 * note there may not be any presorted path). query_planner will also
916 * estimate the number of groups in the query, and canonicalize all
919 query_planner(root, sub_tlist, tuple_fraction, limit_tuples,
920 &cheapest_path, &sorted_path, &dNumGroups);
922 group_pathkeys = root->group_pathkeys;
923 sort_pathkeys = root->sort_pathkeys;
926 * If grouping, extract the grouping operators and decide whether we
927 * want to use hashed grouping.
929 if (parse->groupClause)
931 groupOperators = extract_grouping_ops(parse->groupClause);
932 use_hashed_grouping =
933 choose_hashed_grouping(root, tuple_fraction, limit_tuples,
934 cheapest_path, sorted_path,
935 groupOperators, dNumGroups,
938 /* Also convert # groups to long int --- but 'ware overflow! */
939 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
943 * Select the best path. If we are doing hashed grouping, we will
944 * always read all the input tuples, so use the cheapest-total path.
945 * Otherwise, trust query_planner's decision about which to use.
947 if (use_hashed_grouping || !sorted_path)
948 best_path = cheapest_path;
950 best_path = sorted_path;
953 * Check to see if it's possible to optimize MIN/MAX aggregates. If
954 * so, we will forget all the work we did so far to choose a "regular"
955 * path ... but we had to do it anyway to be able to tell which way is
958 result_plan = optimize_minmax_aggregates(root,
961 if (result_plan != NULL)
964 * optimize_minmax_aggregates generated the full plan, with the
965 * right tlist, and it has no sort order.
967 current_pathkeys = NIL;
972 * Normal case --- create a plan according to query_planner's
975 bool need_sort_for_grouping = false;
977 result_plan = create_plan(root, best_path);
978 current_pathkeys = best_path->pathkeys;
980 /* Detect if we'll need an explicit sort for grouping */
981 if (parse->groupClause && !use_hashed_grouping &&
982 !pathkeys_contained_in(group_pathkeys, current_pathkeys))
984 need_sort_for_grouping = true;
986 * Always override query_planner's tlist, so that we don't
987 * sort useless data from a "physical" tlist.
989 need_tlist_eval = true;
993 * create_plan() returns a plan with just a "flat" tlist of
994 * required Vars. Usually we need to insert the sub_tlist as the
995 * tlist of the top plan node. However, we can skip that if we
996 * determined that whatever query_planner chose to return will be
1002 * If the top-level plan node is one that cannot do expression
1003 * evaluation, we must insert a Result node to project the
1006 if (!is_projection_capable_plan(result_plan))
1008 result_plan = (Plan *) make_result(root,
1016 * Otherwise, just replace the subplan's flat tlist with
1017 * the desired tlist.
1019 result_plan->targetlist = sub_tlist;
1023 * Also, account for the cost of evaluation of the sub_tlist.
1025 * Up to now, we have only been dealing with "flat" tlists,
1026 * containing just Vars. So their evaluation cost is zero
1027 * according to the model used by cost_qual_eval() (or if you
1028 * prefer, the cost is factored into cpu_tuple_cost). Thus we
1029 * can avoid accounting for tlist cost throughout
1030 * query_planner() and subroutines. But now we've inserted a
1031 * tlist that might contain actual operators, sub-selects, etc
1032 * --- so we'd better account for its cost.
1034 * Below this point, any tlist eval cost for added-on nodes
1035 * should be accounted for as we create those nodes.
1036 * Presently, of the node types we can add on, only Agg and
1037 * Group project new tlists (the rest just copy their input
1038 * tuples) --- so make_agg() and make_group() are responsible
1039 * for computing the added cost.
1041 cost_qual_eval(&tlist_cost, sub_tlist, root);
1042 result_plan->startup_cost += tlist_cost.startup;
1043 result_plan->total_cost += tlist_cost.startup +
1044 tlist_cost.per_tuple * result_plan->plan_rows;
1049 * Since we're using query_planner's tlist and not the one
1050 * make_subplanTargetList calculated, we have to refigure any
1051 * grouping-column indexes make_subplanTargetList computed.
1053 locate_grouping_columns(root, tlist, result_plan->targetlist,
1058 * Insert AGG or GROUP node if needed, plus an explicit sort step
1061 * HAVING clause, if any, becomes qual of the Agg or Group node.
1063 if (use_hashed_grouping)
1065 /* Hashed aggregate plan --- no sort needed */
1066 result_plan = (Plan *) make_agg(root,
1068 (List *) parse->havingQual,
1076 /* Hashed aggregation produces randomly-ordered results */
1077 current_pathkeys = NIL;
1079 else if (parse->hasAggs)
1081 /* Plain aggregate plan --- sort if needed */
1082 AggStrategy aggstrategy;
1084 if (parse->groupClause)
1086 if (need_sort_for_grouping)
1088 result_plan = (Plan *)
1089 make_sort_from_groupcols(root,
1093 current_pathkeys = group_pathkeys;
1095 aggstrategy = AGG_SORTED;
1098 * The AGG node will not change the sort ordering of its
1099 * groups, so current_pathkeys describes the result too.
1104 aggstrategy = AGG_PLAIN;
1105 /* Result will be only one row anyway; no sort order */
1106 current_pathkeys = NIL;
1109 result_plan = (Plan *) make_agg(root,
1111 (List *) parse->havingQual,
1120 else if (parse->groupClause)
1123 * GROUP BY without aggregation, so insert a group node (plus
1124 * the appropriate sort node, if necessary).
1126 * Add an explicit sort if we couldn't make the path come out
1127 * the way the GROUP node needs it.
1129 if (need_sort_for_grouping)
1131 result_plan = (Plan *)
1132 make_sort_from_groupcols(root,
1136 current_pathkeys = group_pathkeys;
1139 result_plan = (Plan *) make_group(root,
1141 (List *) parse->havingQual,
1147 /* The Group node won't change sort ordering */
1149 else if (root->hasHavingQual)
1152 * No aggregates, and no GROUP BY, but we have a HAVING qual.
1153 * This is a degenerate case in which we are supposed to emit
1154 * either 0 or 1 row depending on whether HAVING succeeds.
1155 * Furthermore, there cannot be any variables in either HAVING
1156 * or the targetlist, so we actually do not need the FROM
1157 * table at all! We can just throw away the plan-so-far and
1158 * generate a Result node. This is a sufficiently unusual
1159 * corner case that it's not worth contorting the structure of
1160 * this routine to avoid having to generate the plan in the
1163 result_plan = (Plan *) make_result(root,
1168 } /* end of non-minmax-aggregate case */
1169 } /* end of if (setOperations) */
1172 * If we were not able to make the plan come out in the right order, add
1173 * an explicit sort step.
1175 if (parse->sortClause)
1177 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1179 result_plan = (Plan *) make_sort_from_pathkeys(root,
1183 current_pathkeys = sort_pathkeys;
1188 * If there is a DISTINCT clause, add the UNIQUE node.
1190 if (parse->distinctClause)
1192 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1195 * If there was grouping or aggregation, leave plan_rows as-is (ie,
1196 * assume the result was already mostly unique). If not, use the
1197 * number of distinct-groups calculated by query_planner.
1199 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1200 result_plan->plan_rows = dNumGroups;
1204 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1206 if (parse->limitCount || parse->limitOffset)
1208 result_plan = (Plan *) make_limit(result_plan,
1216 * Deal with the RETURNING clause if any. It's convenient to pass the
1217 * returningList through setrefs.c now rather than at top level (if we
1218 * waited, handling inherited UPDATE/DELETE would be much harder).
1220 if (parse->returningList)
1224 Assert(parse->resultRelation);
1225 rlist = set_returning_clause_references(root->glob,
1226 parse->returningList,
1228 parse->resultRelation);
1229 root->returningLists = list_make1(rlist);
1232 root->returningLists = NIL;
1234 /* Compute result-relations list if needed */
1235 if (parse->resultRelation)
1236 root->resultRelations = list_make1_int(parse->resultRelation);
1238 root->resultRelations = NIL;
1241 * Return the actual output ordering in query_pathkeys for possible use by
1242 * an outer query level.
1244 root->query_pathkeys = current_pathkeys;
1250 * Detect whether a plan node is a "dummy" plan created when a relation
1251 * is deemed not to need scanning due to constraint exclusion.
1253 * Currently, such dummy plans are Result nodes with constant FALSE
1257 is_dummy_plan(Plan *plan)
1259 if (IsA(plan, Result))
1261 List *rcqual = (List *) ((Result *) plan)->resconstantqual;
1263 if (list_length(rcqual) == 1)
1265 Const *constqual = (Const *) linitial(rcqual);
1267 if (constqual && IsA(constqual, Const))
1269 if (!constqual->constisnull &&
1270 !DatumGetBool(constqual->constvalue))
1279 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1281 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1282 * results back in *count_est and *offset_est. These variables are set to
1283 * 0 if the corresponding clause is not present, and -1 if it's present
1284 * but we couldn't estimate the value for it. (The "0" convention is OK
1285 * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1286 * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
1287 * usual practice of never estimating less than one row.) These values will
1288 * be passed to make_limit, which see if you change this code.
1290 * The return value is the suitably adjusted tuple_fraction to use for
1291 * planning the query. This adjustment is not overridable, since it reflects
1292 * plan actions that grouping_planner() will certainly take, not assumptions
1296 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1297 int64 *offset_est, int64 *count_est)
1299 Query *parse = root->parse;
1301 double limit_fraction;
1303 /* Should not be called unless LIMIT or OFFSET */
1304 Assert(parse->limitCount || parse->limitOffset);
1307 * Try to obtain the clause values. We use estimate_expression_value
1308 * primarily because it can sometimes do something useful with Params.
1310 if (parse->limitCount)
1312 est = estimate_expression_value(root, parse->limitCount);
1313 if (est && IsA(est, Const))
1315 if (((Const *) est)->constisnull)
1317 /* NULL indicates LIMIT ALL, ie, no limit */
1318 *count_est = 0; /* treat as not present */
1322 *count_est = DatumGetInt64(((Const *) est)->constvalue);
1323 if (*count_est <= 0)
1324 *count_est = 1; /* force to at least 1 */
1328 *count_est = -1; /* can't estimate */
1331 *count_est = 0; /* not present */
1333 if (parse->limitOffset)
1335 est = estimate_expression_value(root, parse->limitOffset);
1336 if (est && IsA(est, Const))
1338 if (((Const *) est)->constisnull)
1340 /* Treat NULL as no offset; the executor will too */
1341 *offset_est = 0; /* treat as not present */
1345 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
1346 if (*offset_est < 0)
1347 *offset_est = 0; /* less than 0 is same as 0 */
1351 *offset_est = -1; /* can't estimate */
1354 *offset_est = 0; /* not present */
1356 if (*count_est != 0)
1359 * A LIMIT clause limits the absolute number of tuples returned.
1360 * However, if it's not a constant LIMIT then we have to guess; for
1361 * lack of a better idea, assume 10% of the plan's result is wanted.
1363 if (*count_est < 0 || *offset_est < 0)
1365 /* LIMIT or OFFSET is an expression ... punt ... */
1366 limit_fraction = 0.10;
1370 /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
1371 limit_fraction = (double) *count_est + (double) *offset_est;
1375 * If we have absolute limits from both caller and LIMIT, use the
1376 * smaller value; likewise if they are both fractional. If one is
1377 * fractional and the other absolute, we can't easily determine which
1378 * is smaller, but we use the heuristic that the absolute will usually
1381 if (tuple_fraction >= 1.0)
1383 if (limit_fraction >= 1.0)
1386 tuple_fraction = Min(tuple_fraction, limit_fraction);
1390 /* caller absolute, limit fractional; use caller's value */
1393 else if (tuple_fraction > 0.0)
1395 if (limit_fraction >= 1.0)
1397 /* caller fractional, limit absolute; use limit */
1398 tuple_fraction = limit_fraction;
1402 /* both fractional */
1403 tuple_fraction = Min(tuple_fraction, limit_fraction);
1408 /* no info from caller, just use limit */
1409 tuple_fraction = limit_fraction;
1412 else if (*offset_est != 0 && tuple_fraction > 0.0)
1415 * We have an OFFSET but no LIMIT. This acts entirely differently
1416 * from the LIMIT case: here, we need to increase rather than decrease
1417 * the caller's tuple_fraction, because the OFFSET acts to cause more
1418 * tuples to be fetched instead of fewer. This only matters if we got
1419 * a tuple_fraction > 0, however.
1421 * As above, use 10% if OFFSET is present but unestimatable.
1423 if (*offset_est < 0)
1424 limit_fraction = 0.10;
1426 limit_fraction = (double) *offset_est;
1429 * If we have absolute counts from both caller and OFFSET, add them
1430 * together; likewise if they are both fractional. If one is
1431 * fractional and the other absolute, we want to take the larger, and
1432 * we heuristically assume that's the fractional one.
1434 if (tuple_fraction >= 1.0)
1436 if (limit_fraction >= 1.0)
1438 /* both absolute, so add them together */
1439 tuple_fraction += limit_fraction;
1443 /* caller absolute, limit fractional; use limit */
1444 tuple_fraction = limit_fraction;
1449 if (limit_fraction >= 1.0)
1451 /* caller fractional, limit absolute; use caller's value */
1455 /* both fractional, so add them together */
1456 tuple_fraction += limit_fraction;
1457 if (tuple_fraction >= 1.0)
1458 tuple_fraction = 0.0; /* assume fetch all */
1463 return tuple_fraction;
1467 * extract_grouping_ops - make an array of the equality operator OIDs
1468 * for the GROUP BY clause
1471 extract_grouping_ops(List *groupClause)
1473 int numCols = list_length(groupClause);
1475 Oid *groupOperators;
1478 groupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
1480 foreach(glitem, groupClause)
1482 GroupClause *groupcl = (GroupClause *) lfirst(glitem);
1484 groupOperators[colno] = get_equality_op_for_ordering_op(groupcl->sortop);
1485 if (!OidIsValid(groupOperators[colno])) /* shouldn't happen */
1486 elog(ERROR, "could not find equality operator for ordering operator %u",
1491 return groupOperators;
1495 * choose_hashed_grouping - should we use hashed grouping?
1498 choose_hashed_grouping(PlannerInfo *root,
1499 double tuple_fraction, double limit_tuples,
1500 Path *cheapest_path, Path *sorted_path,
1501 Oid *groupOperators, double dNumGroups,
1502 AggClauseCounts *agg_counts)
1504 int numGroupCols = list_length(root->parse->groupClause);
1505 double cheapest_path_rows;
1506 int cheapest_path_width;
1508 List *current_pathkeys;
1514 * Check can't-do-it conditions, including whether the grouping operators
1515 * are hashjoinable. (We assume hashing is OK if they are marked
1516 * oprcanhash. If there isn't actually a supporting hash function, the
1517 * executor will complain at runtime.)
1519 * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1520 * (Doing so would imply storing *all* the input values in the hash table,
1521 * which seems like a certain loser.)
1523 if (!enable_hashagg)
1525 if (agg_counts->numDistinctAggs != 0)
1527 for (i = 0; i < numGroupCols; i++)
1529 if (!op_hashjoinable(groupOperators[i]))
1534 * Don't do it if it doesn't look like the hashtable will fit into
1537 * Beware here of the possibility that cheapest_path->parent is NULL. This
1538 * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
1540 if (cheapest_path->parent)
1542 cheapest_path_rows = cheapest_path->parent->rows;
1543 cheapest_path_width = cheapest_path->parent->width;
1547 cheapest_path_rows = 1; /* assume non-set result */
1548 cheapest_path_width = 100; /* arbitrary */
1551 /* Estimate per-hash-entry space at tuple width... */
1552 hashentrysize = MAXALIGN(cheapest_path_width) + MAXALIGN(sizeof(MinimalTupleData));
1553 /* plus space for pass-by-ref transition values... */
1554 hashentrysize += agg_counts->transitionSpace;
1555 /* plus the per-hash-entry overhead */
1556 hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1558 if (hashentrysize * dNumGroups > work_mem * 1024L)
1562 * See if the estimated cost is no more than doing it the other way. While
1563 * avoiding the need for sorted input is usually a win, the fact that the
1564 * output won't be sorted may be a loss; so we need to do an actual cost
1567 * We need to consider cheapest_path + hashagg [+ final sort] versus
1568 * either cheapest_path [+ sort] + group or agg [+ final sort] or
1569 * presorted_path + group or agg [+ final sort] where brackets indicate a
1570 * step that may not be needed. We assume query_planner() will have
1571 * returned a presorted path only if it's a winner compared to
1572 * cheapest_path for this purpose.
1574 * These path variables are dummies that just hold cost fields; we don't
1575 * make actual Paths for these steps.
1577 cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1578 numGroupCols, dNumGroups,
1579 cheapest_path->startup_cost, cheapest_path->total_cost,
1580 cheapest_path_rows);
1581 /* Result of hashed agg is always unsorted */
1582 if (root->sort_pathkeys)
1583 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
1584 dNumGroups, cheapest_path_width, limit_tuples);
1588 sorted_p.startup_cost = sorted_path->startup_cost;
1589 sorted_p.total_cost = sorted_path->total_cost;
1590 current_pathkeys = sorted_path->pathkeys;
1594 sorted_p.startup_cost = cheapest_path->startup_cost;
1595 sorted_p.total_cost = cheapest_path->total_cost;
1596 current_pathkeys = cheapest_path->pathkeys;
1598 if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1600 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
1601 cheapest_path_rows, cheapest_path_width, -1.0);
1602 current_pathkeys = root->group_pathkeys;
1605 if (root->parse->hasAggs)
1606 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1607 numGroupCols, dNumGroups,
1608 sorted_p.startup_cost, sorted_p.total_cost,
1609 cheapest_path_rows);
1611 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1612 sorted_p.startup_cost, sorted_p.total_cost,
1613 cheapest_path_rows);
1614 /* The Agg or Group node will preserve ordering */
1615 if (root->sort_pathkeys &&
1616 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1617 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
1618 dNumGroups, cheapest_path_width, limit_tuples);
1621 * Now make the decision using the top-level tuple fraction. First we
1622 * have to convert an absolute count (LIMIT) into fractional form.
1624 if (tuple_fraction >= 1.0)
1625 tuple_fraction /= dNumGroups;
1627 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1628 tuple_fraction) < 0)
1630 /* Hashed is cheaper, so use it */
1637 * make_subplanTargetList
1638 * Generate appropriate target list when grouping is required.
1640 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1641 * above the result of query_planner, we typically want to pass a different
1642 * target list to query_planner than the outer plan nodes should have.
1643 * This routine generates the correct target list for the subplan.
1645 * The initial target list passed from the parser already contains entries
1646 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1647 * for variables used only in HAVING clauses; so we need to add those
1648 * variables to the subplan target list. Also, we flatten all expressions
1649 * except GROUP BY items into their component variables; the other expressions
1650 * will be computed by the inserted nodes rather than by the subplan.
1651 * For example, given a query like
1652 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1653 * we want to pass this targetlist to the subplan:
1655 * where the a+b target will be used by the Sort/Group steps, and the
1656 * other targets will be used for computing the final results. (In the
1657 * above example we could theoretically suppress the a and b targets and
1658 * pass down only c,d,a+b, but it's not really worth the trouble to
1659 * eliminate simple var references from the subplan. We will avoid doing
1660 * the extra computation to recompute a+b at the outer level; see
1661 * fix_upper_expr() in setrefs.c.)
1663 * If we are grouping or aggregating, *and* there are no non-Var grouping
1664 * expressions, then the returned tlist is effectively dummy; we do not
1665 * need to force it to be evaluated, because all the Vars it contains
1666 * should be present in the output of query_planner anyway.
1668 * 'tlist' is the query's target list.
1669 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1670 * expressions (if there are any) in the subplan's target list.
1671 * 'need_tlist_eval' is set true if we really need to evaluate the
1674 * The result is the targetlist to be passed to the subplan.
1678 make_subplanTargetList(PlannerInfo *root,
1680 AttrNumber **groupColIdx,
1681 bool *need_tlist_eval)
1683 Query *parse = root->parse;
1688 *groupColIdx = NULL;
1691 * If we're not grouping or aggregating, there's nothing to do here;
1692 * query_planner should receive the unmodified target list.
1694 if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1696 *need_tlist_eval = true;
1701 * Otherwise, start with a "flattened" tlist (having just the vars
1702 * mentioned in the targetlist and HAVING qual --- but not upper- level
1703 * Vars; they will be replaced by Params later on).
1705 sub_tlist = flatten_tlist(tlist);
1706 extravars = pull_var_clause(parse->havingQual, false);
1707 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1708 list_free(extravars);
1709 *need_tlist_eval = false; /* only eval if not flat tlist */
1712 * If grouping, create sub_tlist entries for all GROUP BY expressions
1713 * (GROUP BY items that are simple Vars should be in the list already),
1714 * and make an array showing where the group columns are in the sub_tlist.
1716 numCols = list_length(parse->groupClause);
1720 AttrNumber *grpColIdx;
1723 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1724 *groupColIdx = grpColIdx;
1726 foreach(gl, parse->groupClause)
1728 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1729 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1730 TargetEntry *te = NULL;
1733 /* Find or make a matching sub_tlist entry */
1734 foreach(sl, sub_tlist)
1736 te = (TargetEntry *) lfirst(sl);
1737 if (equal(groupexpr, te->expr))
1742 te = makeTargetEntry((Expr *) groupexpr,
1743 list_length(sub_tlist) + 1,
1746 sub_tlist = lappend(sub_tlist, te);
1747 *need_tlist_eval = true; /* it's not flat anymore */
1750 /* and save its resno */
1751 grpColIdx[keyno++] = te->resno;
1759 * locate_grouping_columns
1760 * Locate grouping columns in the tlist chosen by query_planner.
1762 * This is only needed if we don't use the sub_tlist chosen by
1763 * make_subplanTargetList. We have to forget the column indexes found
1764 * by that routine and re-locate the grouping vars in the real sub_tlist.
1767 locate_grouping_columns(PlannerInfo *root,
1770 AttrNumber *groupColIdx)
1776 * No work unless grouping.
1778 if (!root->parse->groupClause)
1780 Assert(groupColIdx == NULL);
1783 Assert(groupColIdx != NULL);
1785 foreach(gl, root->parse->groupClause)
1787 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1788 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1789 TargetEntry *te = NULL;
1792 foreach(sl, sub_tlist)
1794 te = (TargetEntry *) lfirst(sl);
1795 if (equal(groupexpr, te->expr))
1799 elog(ERROR, "failed to locate grouping columns");
1801 groupColIdx[keyno++] = te->resno;
1806 * postprocess_setop_tlist
1807 * Fix up targetlist returned by plan_set_operations().
1809 * We need to transpose sort key info from the orig_tlist into new_tlist.
1810 * NOTE: this would not be good enough if we supported resjunk sort keys
1811 * for results of set operations --- then, we'd need to project a whole
1812 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1813 * find any resjunk columns in orig_tlist.
1816 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1819 ListCell *orig_tlist_item = list_head(orig_tlist);
1821 foreach(l, new_tlist)
1823 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1824 TargetEntry *orig_tle;
1826 /* ignore resjunk columns in setop result */
1827 if (new_tle->resjunk)
1830 Assert(orig_tlist_item != NULL);
1831 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1832 orig_tlist_item = lnext(orig_tlist_item);
1833 if (orig_tle->resjunk) /* should not happen */
1834 elog(ERROR, "resjunk output columns are not implemented");
1835 Assert(new_tle->resno == orig_tle->resno);
1836 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1838 if (orig_tlist_item != NULL)
1839 elog(ERROR, "resjunk output columns are not implemented");