1 /*-------------------------------------------------------------------------
4 * The query optimizer external interface.
6 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/planner.c,v 1.120 2002/06/13 15:10:25 tgl Exp $
13 *-------------------------------------------------------------------------
18 #include "catalog/pg_type.h"
19 #include "nodes/makefuncs.h"
20 #ifdef OPTIMIZER_DEBUG
21 #include "nodes/print.h"
23 #include "optimizer/clauses.h"
24 #include "optimizer/paths.h"
25 #include "optimizer/planmain.h"
26 #include "optimizer/planner.h"
27 #include "optimizer/prep.h"
28 #include "optimizer/subselect.h"
29 #include "optimizer/tlist.h"
30 #include "optimizer/var.h"
31 #include "parser/analyze.h"
32 #include "parser/parsetree.h"
33 #include "parser/parse_expr.h"
34 #include "rewrite/rewriteManip.h"
35 #include "utils/lsyscache.h"
38 /* Expression kind codes for preprocess_expression */
39 #define EXPRKIND_TARGET 0
40 #define EXPRKIND_WHERE 1
41 #define EXPRKIND_HAVING 2
44 static Node *pull_up_subqueries(Query *parse, Node *jtnode,
45 bool below_outer_join);
46 static bool is_simple_subquery(Query *subquery);
47 static bool has_nullable_targetlist(Query *subquery);
48 static void resolvenew_in_jointree(Node *jtnode, int varno, List *subtlist);
49 static Node *preprocess_jointree(Query *parse, Node *jtnode);
50 static Node *preprocess_expression(Query *parse, Node *expr, int kind);
51 static void preprocess_qual_conditions(Query *parse, Node *jtnode);
52 static Plan *inheritance_planner(Query *parse, List *inheritlist);
53 static Plan *grouping_planner(Query *parse, double tuple_fraction);
54 static List *make_subplanTargetList(Query *parse, List *tlist,
55 AttrNumber **groupColIdx);
56 static Plan *make_groupplan(Query *parse,
57 List *group_tlist, bool tuplePerGroup,
58 List *groupClause, AttrNumber *grpColIdx,
59 bool is_presorted, Plan *subplan);
60 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
63 /*****************************************************************************
65 * Query optimizer entry point
67 *****************************************************************************/
72 Index save_PlannerQueryLevel;
73 List *save_PlannerParamVar;
76 * The planner can be called recursively (an example is when
77 * eval_const_expressions tries to pre-evaluate an SQL function). So,
78 * these global state variables must be saved and restored.
80 * These vars cannot be moved into the Query structure since their whole
81 * purpose is communication across multiple sub-Queries.
83 * Note we do NOT save and restore PlannerPlanId: it exists to assign
84 * unique IDs to SubPlan nodes, and we want those IDs to be unique for
85 * the life of a backend. Also, PlannerInitPlan is saved/restored in
86 * subquery_planner, not here.
88 save_PlannerQueryLevel = PlannerQueryLevel;
89 save_PlannerParamVar = PlannerParamVar;
91 /* Initialize state for handling outer-level references and params */
92 PlannerQueryLevel = 0; /* will be 1 in top-level subquery_planner */
93 PlannerParamVar = NIL;
95 /* primary planning entry point (may recurse for subqueries) */
96 result_plan = subquery_planner(parse, -1.0 /* default case */ );
98 Assert(PlannerQueryLevel == 0);
100 /* executor wants to know total number of Params used overall */
101 result_plan->nParamExec = length(PlannerParamVar);
103 /* final cleanup of the plan */
104 set_plan_references(result_plan, parse->rtable);
106 /* restore state for outer planner, if any */
107 PlannerQueryLevel = save_PlannerQueryLevel;
108 PlannerParamVar = save_PlannerParamVar;
114 /*--------------------
116 * Invokes the planner on a subquery. We recurse to here for each
117 * sub-SELECT found in the query tree.
119 * parse is the querytree produced by the parser & rewriter.
120 * tuple_fraction is the fraction of tuples we expect will be retrieved.
121 * tuple_fraction is interpreted as explained for grouping_planner, below.
123 * Basically, this routine does the stuff that should only be done once
124 * per Query object. It then calls grouping_planner. At one time,
125 * grouping_planner could be invoked recursively on the same Query object;
126 * that's not currently true, but we keep the separation between the two
127 * routines anyway, in case we need it again someday.
129 * subquery_planner will be called recursively to handle sub-Query nodes
130 * found within the query's expressions and rangetable.
132 * Returns a query plan.
133 *--------------------
136 subquery_planner(Query *parse, double tuple_fraction)
138 List *saved_initplan = PlannerInitPlan;
139 int saved_planid = PlannerPlanId;
144 /* Set up for a new level of subquery */
146 PlannerInitPlan = NIL;
148 #ifdef ENABLE_KEY_SET_QUERY
149 /* this should go away sometime soon */
150 transformKeySetQuery(parse);
154 * Check to see if any subqueries in the rangetable can be merged into
157 parse->jointree = (FromExpr *)
158 pull_up_subqueries(parse, (Node *) parse->jointree, false);
161 * If so, we may have created opportunities to simplify the jointree.
163 parse->jointree = (FromExpr *)
164 preprocess_jointree(parse, (Node *) parse->jointree);
167 * Do expression preprocessing on targetlist and quals.
169 parse->targetList = (List *)
170 preprocess_expression(parse, (Node *) parse->targetList,
173 preprocess_qual_conditions(parse, (Node *) parse->jointree);
175 parse->havingQual = preprocess_expression(parse, parse->havingQual,
178 /* Also need to preprocess expressions for function RTEs */
179 foreach(lst, parse->rtable)
181 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lst);
183 if (rte->rtekind == RTE_FUNCTION)
184 rte->funcexpr = preprocess_expression(parse, rte->funcexpr,
186 /* These are not targetlist items, but close enough... */
190 * Check for ungrouped variables passed to subplans in targetlist and
191 * HAVING clause (but not in WHERE or JOIN/ON clauses, since those are
192 * evaluated before grouping). We can't do this any earlier because
193 * we must use the preprocessed targetlist for comparisons of grouped
196 if (parse->hasSubLinks &&
197 (parse->groupClause != NIL || parse->hasAggs))
198 check_subplans_for_ungrouped_vars(parse);
201 * A HAVING clause without aggregates is equivalent to a WHERE clause
202 * (except it can only refer to grouped fields). Transfer any
203 * agg-free clauses of the HAVING qual into WHERE. This may seem like
204 * wasting cycles to cater to stupidly-written queries, but there are
205 * other reasons for doing it. Firstly, if the query contains no aggs
206 * at all, then we aren't going to generate an Agg plan node, and so
207 * there'll be no place to execute HAVING conditions; without this
208 * transfer, we'd lose the HAVING condition entirely, which is wrong.
209 * Secondly, when we push down a qual condition into a sub-query, it's
210 * easiest to push the qual into HAVING always, in case it contains
211 * aggs, and then let this code sort it out.
213 * Note that both havingQual and parse->jointree->quals are in
214 * implicitly-ANDed-list form at this point, even though they are
215 * declared as Node *. Also note that contain_agg_clause does not
216 * recurse into sub-selects, which is exactly what we need here.
219 foreach(lst, (List *) parse->havingQual)
221 Node *havingclause = (Node *) lfirst(lst);
223 if (contain_agg_clause(havingclause))
224 newHaving = lappend(newHaving, havingclause);
226 parse->jointree->quals = (Node *)
227 lappend((List *) parse->jointree->quals, havingclause);
229 parse->havingQual = (Node *) newHaving;
232 * Do the main planning. If we have an inherited target relation,
233 * that needs special processing, else go straight to
236 if (parse->resultRelation &&
237 (lst = expand_inherted_rtentry(parse, parse->resultRelation, false))
239 plan = inheritance_planner(parse, lst);
241 plan = grouping_planner(parse, tuple_fraction);
244 * If any subplans were generated, or if we're inside a subplan, build
245 * subPlan, extParam and locParam lists for plan nodes.
247 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
249 (void) SS_finalize_plan(plan, parse->rtable);
252 * At the moment, SS_finalize_plan doesn't handle initPlans and so
253 * we assign them to the topmost plan node.
255 plan->initPlan = PlannerInitPlan;
256 /* Must add the initPlans' extParams to the topmost node's, too */
257 foreach(lst, plan->initPlan)
259 SubPlan *subplan = (SubPlan *) lfirst(lst);
261 plan->extParam = set_unioni(plan->extParam,
262 subplan->plan->extParam);
266 /* Return to outer subquery context */
268 PlannerInitPlan = saved_initplan;
269 /* we do NOT restore PlannerPlanId; that's not an oversight! */
276 * Look for subqueries in the rangetable that can be pulled up into
277 * the parent query. If the subquery has no special features like
278 * grouping/aggregation then we can merge it into the parent's jointree.
280 * below_outer_join is true if this jointree node is within the nullable
281 * side of an outer join. This restricts what we can do.
283 * A tricky aspect of this code is that if we pull up a subquery we have
284 * to replace Vars that reference the subquery's outputs throughout the
285 * parent query, including quals attached to jointree nodes above the one
286 * we are currently processing! We handle this by being careful not to
287 * change the jointree structure while recursing: no nodes other than
288 * subquery RangeTblRef entries will be replaced. Also, we can't turn
289 * ResolveNew loose on the whole jointree, because it'll return a mutated
290 * copy of the tree; we have to invoke it just on the quals, instead.
293 pull_up_subqueries(Query *parse, Node *jtnode, bool below_outer_join)
297 if (IsA(jtnode, RangeTblRef))
299 int varno = ((RangeTblRef *) jtnode)->rtindex;
300 RangeTblEntry *rte = rt_fetch(varno, parse->rtable);
301 Query *subquery = rte->subquery;
304 * Is this a subquery RTE, and if so, is the subquery simple
305 * enough to pull up? (If not, do nothing at this node.)
307 * If we are inside an outer join, only pull up subqueries whose
308 * targetlists are nullable --- otherwise substituting their tlist
309 * entries for upper Var references would do the wrong thing
310 * (the results wouldn't become NULL when they're supposed to).
311 * XXX This could be improved by generating pseudo-variables for
312 * such expressions; we'd have to figure out how to get the pseudo-
313 * variables evaluated at the right place in the modified plan tree.
316 * Note: even if the subquery itself is simple enough, we can't pull
317 * it up if there is a reference to its whole tuple result. Perhaps
318 * a pseudo-variable is the answer here too.
320 if (rte->rtekind == RTE_SUBQUERY && is_simple_subquery(subquery) &&
321 (!below_outer_join || has_nullable_targetlist(subquery)) &&
322 !contain_whole_tuple_var((Node *) parse, varno, 0))
329 * First, recursively pull up the subquery's subqueries, so
330 * that this routine's processing is complete for its jointree
331 * and rangetable. NB: if the same subquery is referenced
332 * from multiple jointree items (which can't happen normally,
333 * but might after rule rewriting), then we will invoke this
334 * processing multiple times on that subquery. OK because
335 * nothing will happen after the first time. We do have to be
336 * careful to copy everything we pull up, however, or risk
337 * having chunks of structure multiply linked.
339 subquery->jointree = (FromExpr *)
340 pull_up_subqueries(subquery, (Node *) subquery->jointree,
344 * Now make a modifiable copy of the subquery that we can
345 * run OffsetVarNodes on.
347 subquery = copyObject(subquery);
350 * Adjust varnos in subquery so that we can append its
351 * rangetable to upper query's.
353 rtoffset = length(parse->rtable);
354 OffsetVarNodes((Node *) subquery, rtoffset, 0);
357 * Replace all of the top query's references to the subquery's
358 * outputs with copies of the adjusted subtlist items, being
359 * careful not to replace any of the jointree structure.
360 * (This'd be a lot cleaner if we could use query_tree_mutator.)
362 subtlist = subquery->targetList;
363 parse->targetList = (List *)
364 ResolveNew((Node *) parse->targetList,
365 varno, 0, subtlist, CMD_SELECT, 0);
366 resolvenew_in_jointree((Node *) parse->jointree, varno, subtlist);
367 Assert(parse->setOperations == NULL);
369 ResolveNew(parse->havingQual,
370 varno, 0, subtlist, CMD_SELECT, 0);
372 foreach(rt, parse->rtable)
374 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
376 if (rte->rtekind == RTE_JOIN)
377 rte->joinaliasvars = (List *)
378 ResolveNew((Node *) rte->joinaliasvars,
379 varno, 0, subtlist, CMD_SELECT, 0);
383 * Now append the adjusted rtable entries to upper query.
384 * (We hold off until after fixing the upper rtable entries;
385 * no point in running that code on the subquery ones too.)
387 parse->rtable = nconc(parse->rtable, subquery->rtable);
390 * Pull up any FOR UPDATE markers, too. (OffsetVarNodes
391 * already adjusted the marker values, so just nconc the list.)
393 parse->rowMarks = nconc(parse->rowMarks, subquery->rowMarks);
396 * Miscellaneous housekeeping.
398 parse->hasSubLinks |= subquery->hasSubLinks;
399 /* subquery won't be pulled up if it hasAggs, so no work there */
402 * Return the adjusted subquery jointree to replace the
403 * RangeTblRef entry in my jointree.
405 return (Node *) subquery->jointree;
408 else if (IsA(jtnode, FromExpr))
410 FromExpr *f = (FromExpr *) jtnode;
413 foreach(l, f->fromlist)
414 lfirst(l) = pull_up_subqueries(parse, lfirst(l),
417 else if (IsA(jtnode, JoinExpr))
419 JoinExpr *j = (JoinExpr *) jtnode;
421 /* Recurse, being careful to tell myself when inside outer join */
425 j->larg = pull_up_subqueries(parse, j->larg,
427 j->rarg = pull_up_subqueries(parse, j->rarg,
431 j->larg = pull_up_subqueries(parse, j->larg,
433 j->rarg = pull_up_subqueries(parse, j->rarg,
437 j->larg = pull_up_subqueries(parse, j->larg,
439 j->rarg = pull_up_subqueries(parse, j->rarg,
443 j->larg = pull_up_subqueries(parse, j->larg,
445 j->rarg = pull_up_subqueries(parse, j->rarg,
451 * This is where we fail if upper levels of planner
452 * haven't rewritten UNION JOIN as an Append ...
454 elog(ERROR, "UNION JOIN is not implemented yet");
457 elog(ERROR, "pull_up_subqueries: unexpected join type %d",
463 elog(ERROR, "pull_up_subqueries: unexpected node type %d",
470 * Check a subquery in the range table to see if it's simple enough
471 * to pull up into the parent query.
474 is_simple_subquery(Query *subquery)
477 * Let's just make sure it's a valid subselect ...
479 if (!IsA(subquery, Query) ||
480 subquery->commandType != CMD_SELECT ||
481 subquery->resultRelation != 0 ||
482 subquery->into != NULL ||
484 elog(ERROR, "is_simple_subquery: subquery is bogus");
487 * Can't currently pull up a query with setops. Maybe after querytree
490 if (subquery->setOperations)
494 * Can't pull up a subquery involving grouping, aggregation, sorting,
497 if (subquery->hasAggs ||
498 subquery->groupClause ||
499 subquery->havingQual ||
500 subquery->sortClause ||
501 subquery->distinctClause ||
502 subquery->limitOffset ||
503 subquery->limitCount)
507 * Don't pull up a subquery that has any set-returning functions in
508 * its targetlist. Otherwise we might well wind up inserting
509 * set-returning functions into places where they mustn't go,
510 * such as quals of higher queries.
512 if (expression_returns_set((Node *) subquery->targetList))
516 * Hack: don't try to pull up a subquery with an empty jointree.
517 * query_planner() will correctly generate a Result plan for a
518 * jointree that's totally empty, but I don't think the right things
519 * happen if an empty FromExpr appears lower down in a jointree. Not
520 * worth working hard on this, just to collapse SubqueryScan/Result
523 if (subquery->jointree->fromlist == NIL)
530 * has_nullable_targetlist
531 * Check a subquery in the range table to see if all the non-junk
532 * targetlist items are simple variables (and, hence, will correctly
533 * go to NULL when examined above the point of an outer join).
535 * A possible future extension is to accept strict functions of simple
536 * variables, eg, "x + 1".
539 has_nullable_targetlist(Query *subquery)
543 foreach(l, subquery->targetList)
545 TargetEntry *tle = (TargetEntry *) lfirst(l);
547 /* ignore resjunk columns */
548 if (tle->resdom->resjunk)
551 /* Okay if tlist item is a simple Var */
552 if (tle->expr && IsA(tle->expr, Var))
561 * Helper routine for pull_up_subqueries: do ResolveNew on every expression
562 * in the jointree, without changing the jointree structure itself. Ugly,
563 * but there's no other way...
566 resolvenew_in_jointree(Node *jtnode, int varno, List *subtlist)
570 if (IsA(jtnode, RangeTblRef))
572 /* nothing to do here */
574 else if (IsA(jtnode, FromExpr))
576 FromExpr *f = (FromExpr *) jtnode;
579 foreach(l, f->fromlist)
580 resolvenew_in_jointree(lfirst(l), varno, subtlist);
581 f->quals = ResolveNew(f->quals,
582 varno, 0, subtlist, CMD_SELECT, 0);
584 else if (IsA(jtnode, JoinExpr))
586 JoinExpr *j = (JoinExpr *) jtnode;
588 resolvenew_in_jointree(j->larg, varno, subtlist);
589 resolvenew_in_jointree(j->rarg, varno, subtlist);
590 j->quals = ResolveNew(j->quals,
591 varno, 0, subtlist, CMD_SELECT, 0);
594 * We don't bother to update the colvars list, since it won't be
599 elog(ERROR, "resolvenew_in_jointree: unexpected node type %d",
604 * preprocess_jointree
605 * Attempt to simplify a query's jointree.
607 * If we succeed in pulling up a subquery then we might form a jointree
608 * in which a FromExpr is a direct child of another FromExpr. In that
609 * case we can consider collapsing the two FromExprs into one. This is
610 * an optional conversion, since the planner will work correctly either
611 * way. But we may find a better plan (at the cost of more planning time)
612 * if we merge the two nodes.
614 * NOTE: don't try to do this in the same jointree scan that does subquery
615 * pullup! Since we're changing the jointree structure here, that wouldn't
616 * work reliably --- see comments for pull_up_subqueries().
619 preprocess_jointree(Query *parse, Node *jtnode)
623 if (IsA(jtnode, RangeTblRef))
625 /* nothing to do here... */
627 else if (IsA(jtnode, FromExpr))
629 FromExpr *f = (FromExpr *) jtnode;
633 foreach(l, f->fromlist)
635 Node *child = (Node *) lfirst(l);
637 /* Recursively simplify the child... */
638 child = preprocess_jointree(parse, child);
639 /* Now, is it a FromExpr? */
640 if (child && IsA(child, FromExpr))
643 * Yes, so do we want to merge it into parent? Always do
644 * so if child has just one element (since that doesn't
645 * make the parent's list any longer). Otherwise we have
646 * to be careful about the increase in planning time
647 * caused by combining the two join search spaces into
648 * one. Our heuristic is to merge if the merge will
649 * produce a join list no longer than GEQO_RELS/2.
650 * (Perhaps need an additional user parameter?)
652 FromExpr *subf = (FromExpr *) child;
653 int childlen = length(subf->fromlist);
654 int myothers = length(newlist) + length(lnext(l));
656 if (childlen <= 1 || (childlen + myothers) <= geqo_rels / 2)
658 newlist = nconc(newlist, subf->fromlist);
659 f->quals = make_and_qual(subf->quals, f->quals);
662 newlist = lappend(newlist, child);
665 newlist = lappend(newlist, child);
667 f->fromlist = newlist;
669 else if (IsA(jtnode, JoinExpr))
671 JoinExpr *j = (JoinExpr *) jtnode;
673 /* Can't usefully change the JoinExpr, but recurse on children */
674 j->larg = preprocess_jointree(parse, j->larg);
675 j->rarg = preprocess_jointree(parse, j->rarg);
678 elog(ERROR, "preprocess_jointree: unexpected node type %d",
684 * preprocess_expression
685 * Do subquery_planner's preprocessing work for an expression,
686 * which can be a targetlist, a WHERE clause (including JOIN/ON
687 * conditions), or a HAVING clause.
690 preprocess_expression(Query *parse, Node *expr, int kind)
696 * Simplify constant expressions.
698 * Note that at this point quals have not yet been converted to
699 * implicit-AND form, so we can apply eval_const_expressions directly.
700 * Also note that we need to do this before SS_process_sublinks,
701 * because that routine inserts bogus "Const" nodes.
703 expr = eval_const_expressions(expr);
706 * If it's a qual or havingQual, canonicalize it, and convert it to
707 * implicit-AND format.
709 * XXX Is there any value in re-applying eval_const_expressions after
712 if (kind != EXPRKIND_TARGET)
714 expr = (Node *) canonicalize_qual((Expr *) expr, true);
716 #ifdef OPTIMIZER_DEBUG
717 printf("After canonicalize_qual()\n");
722 /* Expand SubLinks to SubPlans */
723 if (parse->hasSubLinks)
724 expr = SS_process_sublinks(expr);
726 /* Replace uplevel vars with Param nodes */
727 if (PlannerQueryLevel > 1)
728 expr = SS_replace_correlation_vars(expr);
731 * If the query has any join RTEs, try to replace join alias variables
732 * with base-relation variables, to allow quals to be pushed down.
733 * We must do this after sublink processing, since it does not recurse
736 * The flattening pass is expensive enough that it seems worthwhile to
737 * scan the rangetable to see if we can avoid it.
739 has_join_rtes = false;
740 foreach(rt, parse->rtable)
742 RangeTblEntry *rte = lfirst(rt);
744 if (rte->rtekind == RTE_JOIN)
746 has_join_rtes = true;
751 expr = flatten_join_alias_vars(expr, parse->rtable, false);
757 * preprocess_qual_conditions
758 * Recursively scan the query's jointree and do subquery_planner's
759 * preprocessing work on each qual condition found therein.
762 preprocess_qual_conditions(Query *parse, Node *jtnode)
766 if (IsA(jtnode, RangeTblRef))
768 /* nothing to do here */
770 else if (IsA(jtnode, FromExpr))
772 FromExpr *f = (FromExpr *) jtnode;
775 foreach(l, f->fromlist)
776 preprocess_qual_conditions(parse, lfirst(l));
778 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_WHERE);
780 else if (IsA(jtnode, JoinExpr))
782 JoinExpr *j = (JoinExpr *) jtnode;
784 preprocess_qual_conditions(parse, j->larg);
785 preprocess_qual_conditions(parse, j->rarg);
787 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_WHERE);
790 elog(ERROR, "preprocess_qual_conditions: unexpected node type %d",
794 /*--------------------
795 * inheritance_planner
796 * Generate a plan in the case where the result relation is an
799 * We have to handle this case differently from cases where a source
800 * relation is an inheritance set. Source inheritance is expanded at
801 * the bottom of the plan tree (see allpaths.c), but target inheritance
802 * has to be expanded at the top. The reason is that for UPDATE, each
803 * target relation needs a different targetlist matching its own column
804 * set. (This is not so critical for DELETE, but for simplicity we treat
805 * inherited DELETE the same way.) Fortunately, the UPDATE/DELETE target
806 * can never be the nullable side of an outer join, so it's OK to generate
809 * parse is the querytree produced by the parser & rewriter.
810 * inheritlist is an integer list of RT indexes for the result relation set.
812 * Returns a query plan.
813 *--------------------
816 inheritance_planner(Query *parse, List *inheritlist)
818 int parentRTindex = parse->resultRelation;
819 Oid parentOID = getrelid(parentRTindex, parse->rtable);
820 List *subplans = NIL;
824 foreach(l, inheritlist)
826 int childRTindex = lfirsti(l);
827 Oid childOID = getrelid(childRTindex, parse->rtable);
831 /* Generate modified query with this rel as target */
832 subquery = (Query *) adjust_inherited_attrs((Node *) parse,
833 parentRTindex, parentOID,
834 childRTindex, childOID);
836 subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */ );
837 subplans = lappend(subplans, subplan);
838 /* Save preprocessed tlist from first rel for use in Append */
840 tlist = subplan->targetlist;
843 /* Save the target-relations list for the executor, too */
844 parse->resultRelations = inheritlist;
846 return (Plan *) make_append(subplans, true, tlist);
849 /*--------------------
851 * Perform planning steps related to grouping, aggregation, etc.
852 * This primarily means adding top-level processing to the basic
853 * query plan produced by query_planner.
855 * parse is the querytree produced by the parser & rewriter.
856 * tuple_fraction is the fraction of tuples we expect will be retrieved
858 * tuple_fraction is interpreted as follows:
859 * < 0: determine fraction by inspection of query (normal case)
860 * 0: expect all tuples to be retrieved
861 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
862 * from the plan to be retrieved
863 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
864 * expected to be retrieved (ie, a LIMIT specification)
865 * The normal case is to pass -1, but some callers pass values >= 0 to
866 * override this routine's determination of the appropriate fraction.
868 * Returns a query plan.
869 *--------------------
872 grouping_planner(Query *parse, double tuple_fraction)
874 List *tlist = parse->targetList;
876 List *current_pathkeys;
877 List *group_pathkeys;
879 AttrNumber *groupColIdx = NULL;
881 if (parse->setOperations)
884 * Construct the plan for set operations. The result will not
885 * need any work except perhaps a top-level sort and/or LIMIT.
887 result_plan = plan_set_operations(parse);
890 * We should not need to call preprocess_targetlist, since we must
891 * be in a SELECT query node. Instead, use the targetlist
892 * returned by plan_set_operations (since this tells whether it
893 * returned any resjunk columns!), and transfer any sort key
894 * information from the original tlist.
896 Assert(parse->commandType == CMD_SELECT);
898 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
901 * Can't handle FOR UPDATE here (parser should have checked
902 * already, but let's make sure).
905 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
908 * We set current_pathkeys NIL indicating we do not know sort
909 * order. This is correct when the top set operation is UNION
910 * ALL, since the appended-together results are unsorted even if
911 * the subplans were sorted. For other set operations we could be
912 * smarter --- room for future improvement!
914 current_pathkeys = NIL;
917 * Calculate pathkeys that represent grouping/ordering
918 * requirements (grouping should always be null, but...)
920 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
922 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
929 /* Preprocess targetlist in case we are inside an INSERT/UPDATE. */
930 tlist = preprocess_targetlist(tlist,
932 parse->resultRelation,
936 * Add TID targets for rels selected FOR UPDATE (should this be
937 * done in preprocess_targetlist?). The executor uses the TID to
938 * know which rows to lock, much as for UPDATE or DELETE.
945 * We've got trouble if the FOR UPDATE appears inside
946 * grouping, since grouping renders a reference to individual
947 * tuple CTIDs invalid. This is also checked at parse time,
948 * but that's insufficient because of rule substitution, query
951 CheckSelectForUpdate(parse);
954 * Currently the executor only supports FOR UPDATE at top
957 if (PlannerQueryLevel > 1)
958 elog(ERROR, "SELECT FOR UPDATE is not allowed in subselects");
960 foreach(l, parse->rowMarks)
962 Index rti = lfirsti(l);
968 resname = (char *) palloc(32);
969 sprintf(resname, "ctid%u", rti);
970 resdom = makeResdom(length(tlist) + 1,
977 SelfItemPointerAttributeNumber,
982 ctid = makeTargetEntry(resdom, (Node *) var);
983 tlist = lappend(tlist, ctid);
988 * Generate appropriate target list for subplan; may be different
989 * from tlist if grouping or aggregation is needed.
991 sub_tlist = make_subplanTargetList(parse, tlist, &groupColIdx);
994 * Calculate pathkeys that represent grouping/ordering
997 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
999 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
1003 * Figure out whether we need a sorted result from query_planner.
1005 * If we have a GROUP BY clause, then we want a result sorted
1006 * properly for grouping. Otherwise, if there is an ORDER BY
1007 * clause, we want to sort by the ORDER BY clause. (Note: if we
1008 * have both, and ORDER BY is a superset of GROUP BY, it would be
1009 * tempting to request sort by ORDER BY --- but that might just
1010 * leave us failing to exploit an available sort order at all.
1011 * Needs more thought...)
1013 if (parse->groupClause)
1014 parse->query_pathkeys = group_pathkeys;
1015 else if (parse->sortClause)
1016 parse->query_pathkeys = sort_pathkeys;
1018 parse->query_pathkeys = NIL;
1021 * Figure out whether we expect to retrieve all the tuples that
1022 * the plan can generate, or to stop early due to outside factors
1023 * such as a cursor. If the caller passed a value >= 0, believe
1024 * that value, else do our own examination of the query context.
1026 if (tuple_fraction < 0.0)
1028 /* Initial assumption is we need all the tuples */
1029 tuple_fraction = 0.0;
1032 * Check for retrieve-into-portal, ie DECLARE CURSOR.
1034 * We have no real idea how many tuples the user will ultimately
1035 * FETCH from a cursor, but it seems a good bet that he
1036 * doesn't want 'em all. Optimize for 10% retrieval (you
1037 * gotta better number? Should this be a SETtable parameter?)
1039 if (parse->isPortal)
1040 tuple_fraction = 0.10;
1044 * Adjust tuple_fraction if we see that we are going to apply
1045 * limiting/grouping/aggregation/etc. This is not overridable by
1046 * the caller, since it reflects plan actions that this routine
1047 * will certainly take, not assumptions about context.
1049 if (parse->limitCount != NULL)
1052 * A LIMIT clause limits the absolute number of tuples
1053 * returned. However, if it's not a constant LIMIT then we
1054 * have to punt; for lack of a better idea, assume 10% of the
1055 * plan's result is wanted.
1057 double limit_fraction = 0.0;
1059 if (IsA(parse->limitCount, Const))
1061 Const *limitc = (Const *) parse->limitCount;
1062 int32 count = DatumGetInt32(limitc->constvalue);
1065 * A NULL-constant LIMIT represents "LIMIT ALL", which we
1066 * treat the same as no limit (ie, expect to retrieve all
1069 if (!limitc->constisnull && count > 0)
1071 limit_fraction = (double) count;
1072 /* We must also consider the OFFSET, if present */
1073 if (parse->limitOffset != NULL)
1075 if (IsA(parse->limitOffset, Const))
1079 limitc = (Const *) parse->limitOffset;
1080 offset = DatumGetInt32(limitc->constvalue);
1081 if (!limitc->constisnull && offset > 0)
1082 limit_fraction += (double) offset;
1086 /* OFFSET is an expression ... punt ... */
1087 limit_fraction = 0.10;
1094 /* LIMIT is an expression ... punt ... */
1095 limit_fraction = 0.10;
1098 if (limit_fraction > 0.0)
1101 * If we have absolute limits from both caller and LIMIT,
1102 * use the smaller value; if one is fractional and the
1103 * other absolute, treat the fraction as a fraction of the
1104 * absolute value; else we can multiply the two fractions
1107 if (tuple_fraction >= 1.0)
1109 if (limit_fraction >= 1.0)
1112 tuple_fraction = Min(tuple_fraction, limit_fraction);
1116 /* caller absolute, limit fractional */
1117 tuple_fraction *= limit_fraction;
1118 if (tuple_fraction < 1.0)
1119 tuple_fraction = 1.0;
1122 else if (tuple_fraction > 0.0)
1124 if (limit_fraction >= 1.0)
1126 /* caller fractional, limit absolute */
1127 tuple_fraction *= limit_fraction;
1128 if (tuple_fraction < 1.0)
1129 tuple_fraction = 1.0;
1133 /* both fractional */
1134 tuple_fraction *= limit_fraction;
1139 /* no info from caller, just use limit */
1140 tuple_fraction = limit_fraction;
1145 if (parse->groupClause)
1148 * In GROUP BY mode, we have the little problem that we don't
1149 * really know how many input tuples will be needed to make a
1150 * group, so we can't translate an output LIMIT count into an
1151 * input count. For lack of a better idea, assume 25% of the
1152 * input data will be processed if there is any output limit.
1153 * However, if the caller gave us a fraction rather than an
1154 * absolute count, we can keep using that fraction (which
1155 * amounts to assuming that all the groups are about the same
1158 if (tuple_fraction >= 1.0)
1159 tuple_fraction = 0.25;
1162 * If both GROUP BY and ORDER BY are specified, we will need
1163 * two levels of sort --- and, therefore, certainly need to
1164 * read all the input tuples --- unless ORDER BY is a subset
1165 * of GROUP BY. (We have not yet canonicalized the pathkeys,
1166 * so must use the slower noncanonical comparison method.)
1168 if (parse->groupClause && parse->sortClause &&
1169 !noncanonical_pathkeys_contained_in(sort_pathkeys,
1171 tuple_fraction = 0.0;
1173 else if (parse->hasAggs)
1176 * Ungrouped aggregate will certainly want all the input
1179 tuple_fraction = 0.0;
1181 else if (parse->distinctClause)
1184 * SELECT DISTINCT, like GROUP, will absorb an unpredictable
1185 * number of input tuples per output tuple. Handle the same
1188 if (tuple_fraction >= 1.0)
1189 tuple_fraction = 0.25;
1192 /* Generate the basic plan for this Query */
1193 result_plan = query_planner(parse,
1198 * query_planner returns actual sort order (which is not
1199 * necessarily what we requested) in query_pathkeys.
1201 current_pathkeys = parse->query_pathkeys;
1205 * We couldn't canonicalize group_pathkeys and sort_pathkeys before
1206 * running query_planner(), so do it now.
1208 group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
1209 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
1212 * If we have a GROUP BY clause, insert a group node (plus the
1213 * appropriate sort node, if necessary).
1215 if (parse->groupClause)
1222 * Decide whether how many tuples per group the Group node needs
1223 * to return. (Needs only one tuple per group if no aggregate is
1224 * present. Otherwise, need every tuple from the group to do the
1225 * aggregation.) Note tuplePerGroup is named backwards :-(
1227 tuplePerGroup = parse->hasAggs;
1230 * If there are aggregates then the Group node should just return
1231 * the same set of vars as the subplan did. If there are no aggs
1232 * then the Group node had better compute the final tlist.
1235 group_tlist = new_unsorted_tlist(result_plan->targetlist);
1237 group_tlist = tlist;
1240 * Figure out whether the path result is already ordered the way
1241 * we need it --- if so, no need for an explicit sort step.
1243 if (pathkeys_contained_in(group_pathkeys, current_pathkeys))
1245 is_sorted = true; /* no sort needed now */
1246 /* current_pathkeys remains unchanged */
1251 * We will need to do an explicit sort by the GROUP BY clause.
1252 * make_groupplan will do the work, but set current_pathkeys
1253 * to indicate the resulting order.
1256 current_pathkeys = group_pathkeys;
1259 result_plan = make_groupplan(parse,
1269 * If aggregate is present, insert the Agg node
1271 * HAVING clause, if any, becomes qual of the Agg node
1275 result_plan = (Plan *) make_agg(tlist,
1276 (List *) parse->havingQual,
1278 /* Note: Agg does not affect any existing sort order of the tuples */
1282 /* If there are no Aggs, we shouldn't have any HAVING qual anymore */
1283 Assert(parse->havingQual == NULL);
1287 * If we were not able to make the plan come out in the right order,
1288 * add an explicit sort step.
1290 if (parse->sortClause)
1292 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1293 result_plan = make_sortplan(parse, tlist, result_plan,
1298 * If there is a DISTINCT clause, add the UNIQUE node.
1300 if (parse->distinctClause)
1302 result_plan = (Plan *) make_unique(tlist, result_plan,
1303 parse->distinctClause);
1307 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1309 if (parse->limitOffset || parse->limitCount)
1311 result_plan = (Plan *) make_limit(tlist, result_plan,
1320 * make_subplanTargetList
1321 * Generate appropriate target list when grouping is required.
1323 * When grouping_planner inserts Aggregate and/or Group plan nodes above
1324 * the result of query_planner, we typically want to pass a different
1325 * target list to query_planner than the outer plan nodes should have.
1326 * This routine generates the correct target list for the subplan.
1328 * The initial target list passed from the parser already contains entries
1329 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1330 * for variables used only in HAVING clauses; so we need to add those
1331 * variables to the subplan target list. Also, if we are doing either
1332 * grouping or aggregation, we flatten all expressions except GROUP BY items
1333 * into their component variables; the other expressions will be computed by
1334 * the inserted nodes rather than by the subplan. For example,
1335 * given a query like
1336 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1337 * we want to pass this targetlist to the subplan:
1339 * where the a+b target will be used by the Sort/Group steps, and the
1340 * other targets will be used for computing the final results. (In the
1341 * above example we could theoretically suppress the a and b targets and
1342 * pass down only c,d,a+b, but it's not really worth the trouble to
1343 * eliminate simple var references from the subplan. We will avoid doing
1344 * the extra computation to recompute a+b at the outer level; see
1345 * replace_vars_with_subplan_refs() in setrefs.c.)
1347 * 'parse' is the query being processed.
1348 * 'tlist' is the query's target list.
1349 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1350 * expressions (if there are any) in the subplan's target list.
1352 * The result is the targetlist to be passed to the subplan.
1356 make_subplanTargetList(Query *parse,
1358 AttrNumber **groupColIdx)
1364 *groupColIdx = NULL;
1367 * If we're not grouping or aggregating, nothing to do here;
1368 * query_planner should receive the unmodified target list.
1370 if (!parse->hasAggs && !parse->groupClause && !parse->havingQual)
1374 * Otherwise, start with a "flattened" tlist (having just the vars
1375 * mentioned in the targetlist and HAVING qual --- but not upper-
1376 * level Vars; they will be replaced by Params later on).
1378 sub_tlist = flatten_tlist(tlist);
1379 extravars = pull_var_clause(parse->havingQual, false);
1380 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1381 freeList(extravars);
1384 * If grouping, create sub_tlist entries for all GROUP BY expressions
1385 * (GROUP BY items that are simple Vars should be in the list
1386 * already), and make an array showing where the group columns are in
1389 numCols = length(parse->groupClause);
1393 AttrNumber *grpColIdx;
1396 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1397 *groupColIdx = grpColIdx;
1399 foreach(gl, parse->groupClause)
1401 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1402 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1403 TargetEntry *te = NULL;
1406 /* Find or make a matching sub_tlist entry */
1407 foreach(sl, sub_tlist)
1409 te = (TargetEntry *) lfirst(sl);
1410 if (equal(groupexpr, te->expr))
1415 te = makeTargetEntry(makeResdom(length(sub_tlist) + 1,
1416 exprType(groupexpr),
1417 exprTypmod(groupexpr),
1421 sub_tlist = lappend(sub_tlist, te);
1424 /* and save its resno */
1425 grpColIdx[keyno++] = te->resdom->resno;
1434 * Add a Group node for GROUP BY processing.
1435 * If we couldn't make the subplan produce presorted output for grouping,
1436 * first add an explicit Sort node.
1439 make_groupplan(Query *parse,
1443 AttrNumber *grpColIdx,
1447 int numCols = length(groupClause);
1452 * The Sort node always just takes a copy of the subplan's tlist
1453 * plus ordering information. (This might seem inefficient if the
1454 * subplan contains complex GROUP BY expressions, but in fact Sort
1455 * does not evaluate its targetlist --- it only outputs the same
1456 * tuples in a new order. So the expressions we might be copying
1457 * are just dummies with no extra execution cost.)
1459 List *sort_tlist = new_unsorted_tlist(subplan->targetlist);
1463 foreach(gl, groupClause)
1465 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1466 TargetEntry *te = nth(grpColIdx[keyno] - 1, sort_tlist);
1467 Resdom *resdom = te->resdom;
1470 * Check for the possibility of duplicate group-by clauses ---
1471 * the parser should have removed 'em, but the Sort executor
1472 * will get terribly confused if any get through!
1474 if (resdom->reskey == 0)
1476 /* OK, insert the ordering info needed by the executor. */
1477 resdom->reskey = ++keyno;
1478 resdom->reskeyop = grpcl->sortop;
1484 subplan = (Plan *) make_sort(parse, sort_tlist, subplan, keyno);
1487 return (Plan *) make_group(group_tlist, tuplePerGroup, numCols,
1488 grpColIdx, subplan);
1493 * Add a Sort node to implement an explicit ORDER BY clause.
1496 make_sortplan(Query *parse, List *tlist, Plan *plannode, List *sortcls)
1503 * First make a copy of the tlist so that we don't corrupt the
1506 sort_tlist = new_unsorted_tlist(tlist);
1510 SortClause *sortcl = (SortClause *) lfirst(i);
1511 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sort_tlist);
1512 Resdom *resdom = tle->resdom;
1515 * Check for the possibility of duplicate order-by clauses --- the
1516 * parser should have removed 'em, but the executor will get
1517 * terribly confused if any get through!
1519 if (resdom->reskey == 0)
1521 /* OK, insert the ordering info needed by the executor. */
1522 resdom->reskey = ++keyno;
1523 resdom->reskeyop = sortcl->sortop;
1529 return (Plan *) make_sort(parse, sort_tlist, plannode, keyno);
1533 * postprocess_setop_tlist
1534 * Fix up targetlist returned by plan_set_operations().
1536 * We need to transpose sort key info from the orig_tlist into new_tlist.
1537 * NOTE: this would not be good enough if we supported resjunk sort keys
1538 * for results of set operations --- then, we'd need to project a whole
1539 * new tlist to evaluate the resjunk columns. For now, just elog if we
1540 * find any resjunk columns in orig_tlist.
1543 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1547 foreach(l, new_tlist)
1549 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1550 TargetEntry *orig_tle;
1552 /* ignore resjunk columns in setop result */
1553 if (new_tle->resdom->resjunk)
1556 Assert(orig_tlist != NIL);
1557 orig_tle = (TargetEntry *) lfirst(orig_tlist);
1558 orig_tlist = lnext(orig_tlist);
1559 if (orig_tle->resdom->resjunk)
1560 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");
1561 Assert(new_tle->resdom->resno == orig_tle->resdom->resno);
1562 Assert(new_tle->resdom->restype == orig_tle->resdom->restype);
1563 new_tle->resdom->ressortgroupref = orig_tle->resdom->ressortgroupref;
1565 if (orig_tlist != NIL)
1566 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");