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.101 2001/01/27 04:42:32 tgl Exp $
13 *-------------------------------------------------------------------------
18 #include "catalog/pg_type.h"
19 #include "nodes/makefuncs.h"
20 #include "optimizer/clauses.h"
21 #include "optimizer/paths.h"
22 #include "optimizer/planmain.h"
23 #include "optimizer/planner.h"
24 #include "optimizer/prep.h"
25 #include "optimizer/subselect.h"
26 #include "optimizer/tlist.h"
27 #include "optimizer/var.h"
28 #include "parser/analyze.h"
29 #include "parser/parsetree.h"
30 #include "parser/parse_expr.h"
31 #include "rewrite/rewriteManip.h"
32 #include "utils/lsyscache.h"
35 /* Expression kind codes for preprocess_expression */
36 #define EXPRKIND_TARGET 0
37 #define EXPRKIND_WHERE 1
38 #define EXPRKIND_HAVING 2
41 static Node *pull_up_subqueries(Query *parse, Node *jtnode);
42 static bool is_simple_subquery(Query *subquery);
43 static void resolvenew_in_jointree(Node *jtnode, int varno, List *subtlist);
44 static Node *preprocess_jointree(Query *parse, Node *jtnode);
45 static Node *preprocess_expression(Query *parse, Node *expr, int kind);
46 static void preprocess_qual_conditions(Query *parse, Node *jtnode);
47 static Plan *inheritance_planner(Query *parse, List *inheritlist);
48 static Plan *grouping_planner(Query *parse, double tuple_fraction);
49 static List *make_subplanTargetList(Query *parse, List *tlist,
50 AttrNumber **groupColIdx);
51 static Plan *make_groupplan(List *group_tlist, bool tuplePerGroup,
52 List *groupClause, AttrNumber *grpColIdx,
53 bool is_presorted, Plan *subplan);
54 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
57 /*****************************************************************************
59 * Query optimizer entry point
61 *****************************************************************************/
66 Index save_PlannerQueryLevel;
67 List *save_PlannerParamVar;
70 * The planner can be called recursively (an example is when
71 * eval_const_expressions tries to pre-evaluate an SQL function).
72 * So, these global state variables must be saved and restored.
74 * These vars cannot be moved into the Query structure since their
75 * whole purpose is communication across multiple sub-Queries.
77 * Note we do NOT save and restore PlannerPlanId: it exists to assign
78 * unique IDs to SubPlan nodes, and we want those IDs to be unique
79 * for the life of a backend. Also, PlannerInitPlan is saved/restored
80 * in subquery_planner, not here.
82 save_PlannerQueryLevel = PlannerQueryLevel;
83 save_PlannerParamVar = PlannerParamVar;
85 /* Initialize state for handling outer-level references and params */
86 PlannerQueryLevel = 0; /* will be 1 in top-level subquery_planner */
87 PlannerParamVar = NIL;
89 /* primary planning entry point (may recurse for subqueries) */
90 result_plan = subquery_planner(parse, -1.0 /* default case */ );
92 Assert(PlannerQueryLevel == 0);
94 /* executor wants to know total number of Params used overall */
95 result_plan->nParamExec = length(PlannerParamVar);
97 /* final cleanup of the plan */
98 set_plan_references(result_plan);
100 /* restore state for outer planner, if any */
101 PlannerQueryLevel = save_PlannerQueryLevel;
102 PlannerParamVar = save_PlannerParamVar;
108 /*--------------------
110 * Invokes the planner on a subquery. We recurse to here for each
111 * sub-SELECT found in the query tree.
113 * parse is the querytree produced by the parser & rewriter.
114 * tuple_fraction is the fraction of tuples we expect will be retrieved.
115 * tuple_fraction is interpreted as explained for grouping_planner, below.
117 * Basically, this routine does the stuff that should only be done once
118 * per Query object. It then calls grouping_planner. At one time,
119 * grouping_planner could be invoked recursively on the same Query object;
120 * that's not currently true, but we keep the separation between the two
121 * routines anyway, in case we need it again someday.
123 * subquery_planner will be called recursively to handle sub-Query nodes
124 * found within the query's expressions and rangetable.
126 * Returns a query plan.
127 *--------------------
130 subquery_planner(Query *parse, double tuple_fraction)
132 List *saved_initplan = PlannerInitPlan;
133 int saved_planid = PlannerPlanId;
138 /* Set up for a new level of subquery */
140 PlannerInitPlan = NIL;
142 #ifdef ENABLE_KEY_SET_QUERY
143 /* this should go away sometime soon */
144 transformKeySetQuery(parse);
148 * Check to see if any subqueries in the rangetable can be merged into
151 parse->jointree = (FromExpr *)
152 pull_up_subqueries(parse, (Node *) parse->jointree);
154 * If so, we may have created opportunities to simplify the jointree.
156 parse->jointree = (FromExpr *)
157 preprocess_jointree(parse, (Node *) parse->jointree);
160 * Do expression preprocessing on targetlist and quals.
162 parse->targetList = (List *)
163 preprocess_expression(parse, (Node *) parse->targetList,
166 preprocess_qual_conditions(parse, (Node *) parse->jointree);
168 parse->havingQual = preprocess_expression(parse, parse->havingQual,
172 * A HAVING clause without aggregates is equivalent to a WHERE clause
173 * (except it can only refer to grouped fields). Transfer any agg-free
174 * clauses of the HAVING qual into WHERE. This may seem like wasting
175 * cycles to cater to stupidly-written queries, but there are other
176 * reasons for doing it. Firstly, if the query contains no aggs at all,
177 * then we aren't going to generate an Agg plan node, and so there'll be
178 * no place to execute HAVING conditions; without this transfer, we'd
179 * lose the HAVING condition entirely, which is wrong. Secondly, when
180 * we push down a qual condition into a sub-query, it's easiest to push
181 * the qual into HAVING always, in case it contains aggs, and then let
182 * this code sort it out.
184 * Note that both havingQual and parse->jointree->quals are in
185 * implicitly-ANDed-list form at this point, even though they are
186 * declared as Node *. Also note that contain_agg_clause does not
187 * recurse into sub-selects, which is exactly what we need here.
190 foreach(lst, (List *) parse->havingQual)
192 Node *havingclause = (Node *) lfirst(lst);
194 if (contain_agg_clause(havingclause))
195 newHaving = lappend(newHaving, havingclause);
197 parse->jointree->quals = (Node *)
198 lappend((List *) parse->jointree->quals, havingclause);
200 parse->havingQual = (Node *) newHaving;
203 * Do the main planning. If we have an inherited target relation,
204 * that needs special processing, else go straight to grouping_planner.
206 if (parse->resultRelation &&
207 (lst = expand_inherted_rtentry(parse, parse->resultRelation)) != NIL)
208 plan = inheritance_planner(parse, lst);
210 plan = grouping_planner(parse, tuple_fraction);
213 * If any subplans were generated, or if we're inside a subplan,
214 * build subPlan, extParam and locParam lists for plan nodes.
216 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
218 (void) SS_finalize_plan(plan);
220 * At the moment, SS_finalize_plan doesn't handle initPlans
221 * and so we assign them to the topmost plan node.
223 plan->initPlan = PlannerInitPlan;
224 /* Must add the initPlans' extParams to the topmost node's, too */
225 foreach(lst, plan->initPlan)
227 SubPlan *subplan = (SubPlan *) lfirst(lst);
229 plan->extParam = set_unioni(plan->extParam,
230 subplan->plan->extParam);
234 /* Return to outer subquery context */
236 PlannerInitPlan = saved_initplan;
237 /* we do NOT restore PlannerPlanId; that's not an oversight! */
244 * Look for subqueries in the rangetable that can be pulled up into
245 * the parent query. If the subquery has no special features like
246 * grouping/aggregation then we can merge it into the parent's jointree.
248 * A tricky aspect of this code is that if we pull up a subquery we have
249 * to replace Vars that reference the subquery's outputs throughout the
250 * parent query, including quals attached to jointree nodes above the one
251 * we are currently processing! We handle this by being careful not to
252 * change the jointree structure while recursing: no nodes other than
253 * subquery RangeTblRef entries will be replaced. Also, we can't turn
254 * ResolveNew loose on the whole jointree, because it'll return a mutated
255 * copy of the tree; we have to invoke it just on the quals, instead.
258 pull_up_subqueries(Query *parse, Node *jtnode)
262 if (IsA(jtnode, RangeTblRef))
264 int varno = ((RangeTblRef *) jtnode)->rtindex;
265 RangeTblEntry *rte = rt_fetch(varno, parse->rtable);
266 Query *subquery = rte->subquery;
269 * Is this a subquery RTE, and if so, is the subquery simple enough
270 * to pull up? (If not, do nothing at this node.)
272 if (subquery && is_simple_subquery(subquery))
280 * First, recursively pull up the subquery's subqueries,
281 * so that this routine's processing is complete for its
282 * jointree and rangetable. NB: if the same subquery is
283 * referenced from multiple jointree items (which can't happen
284 * normally, but might after rule rewriting), then we will invoke
285 * this processing multiple times on that subquery. OK because
286 * nothing will happen after the first time. We do have to be
287 * careful to copy everything we pull up, however, or risk
288 * having chunks of structure multiply linked.
290 subquery->jointree = (FromExpr *)
291 pull_up_subqueries(subquery, (Node *) subquery->jointree);
293 * Append the subquery's rangetable to mine (currently,
294 * no adjustments will be needed in the subquery's rtable).
296 rtoffset = length(parse->rtable);
297 parse->rtable = nconc(parse->rtable,
298 copyObject(subquery->rtable));
300 * Make copies of the subquery's jointree and targetlist
301 * with varnos adjusted to match the merged rangetable.
303 subjointree = copyObject(subquery->jointree);
304 OffsetVarNodes(subjointree, rtoffset, 0);
305 subtlist = copyObject(subquery->targetList);
306 OffsetVarNodes((Node *) subtlist, rtoffset, 0);
308 * Replace all of the top query's references to the subquery's
309 * outputs with copies of the adjusted subtlist items, being
310 * careful not to replace any of the jointree structure.
312 parse->targetList = (List *)
313 ResolveNew((Node *) parse->targetList,
314 varno, 0, subtlist, CMD_SELECT, 0);
315 resolvenew_in_jointree((Node *) parse->jointree, varno, subtlist);
317 ResolveNew(parse->havingQual,
318 varno, 0, subtlist, CMD_SELECT, 0);
320 * Pull up any FOR UPDATE markers, too.
322 foreach(l, subquery->rowMarks)
324 int submark = lfirsti(l);
326 parse->rowMarks = lappendi(parse->rowMarks,
330 * Miscellaneous housekeeping.
332 parse->hasSubLinks |= subquery->hasSubLinks;
333 /* subquery won't be pulled up if it hasAggs, so no work there */
336 * Return the adjusted subquery jointree to replace the
337 * RangeTblRef entry in my jointree.
342 else if (IsA(jtnode, FromExpr))
344 FromExpr *f = (FromExpr *) jtnode;
347 foreach(l, f->fromlist)
349 lfirst(l) = pull_up_subqueries(parse, lfirst(l));
352 else if (IsA(jtnode, JoinExpr))
354 JoinExpr *j = (JoinExpr *) jtnode;
356 j->larg = pull_up_subqueries(parse, j->larg);
357 j->rarg = pull_up_subqueries(parse, j->rarg);
360 elog(ERROR, "pull_up_subqueries: unexpected node type %d",
367 * Check a subquery in the range table to see if it's simple enough
368 * to pull up into the parent query.
371 is_simple_subquery(Query *subquery)
374 * Let's just make sure it's a valid subselect ...
376 if (!IsA(subquery, Query) ||
377 subquery->commandType != CMD_SELECT ||
378 subquery->resultRelation != 0 ||
379 subquery->into != NULL ||
381 elog(ERROR, "is_simple_subquery: subquery is bogus");
383 * Can't currently pull up a query with setops.
384 * Maybe after querytree redesign...
386 if (subquery->setOperations)
389 * Can't pull up a subquery involving grouping, aggregation, sorting,
392 if (subquery->hasAggs ||
393 subquery->groupClause ||
394 subquery->havingQual ||
395 subquery->sortClause ||
396 subquery->distinctClause ||
397 subquery->limitOffset ||
398 subquery->limitCount)
401 * Hack: don't try to pull up a subquery with an empty jointree.
402 * query_planner() will correctly generate a Result plan for a
403 * jointree that's totally empty, but I don't think the right things
404 * happen if an empty FromExpr appears lower down in a jointree.
405 * Not worth working hard on this, just to collapse SubqueryScan/Result
408 if (subquery->jointree->fromlist == NIL)
415 * Helper routine for pull_up_subqueries: do ResolveNew on every expression
416 * in the jointree, without changing the jointree structure itself. Ugly,
417 * but there's no other way...
420 resolvenew_in_jointree(Node *jtnode, int varno, List *subtlist)
424 if (IsA(jtnode, RangeTblRef))
426 /* nothing to do here */
428 else if (IsA(jtnode, FromExpr))
430 FromExpr *f = (FromExpr *) jtnode;
433 foreach(l, f->fromlist)
434 resolvenew_in_jointree(lfirst(l), varno, subtlist);
435 f->quals = ResolveNew(f->quals,
436 varno, 0, subtlist, CMD_SELECT, 0);
438 else if (IsA(jtnode, JoinExpr))
440 JoinExpr *j = (JoinExpr *) jtnode;
442 resolvenew_in_jointree(j->larg, varno, subtlist);
443 resolvenew_in_jointree(j->rarg, varno, subtlist);
444 j->quals = ResolveNew(j->quals,
445 varno, 0, subtlist, CMD_SELECT, 0);
446 /* We don't bother to update the colvars list, since it won't be
451 elog(ERROR, "resolvenew_in_jointree: unexpected node type %d",
456 * preprocess_jointree
457 * Attempt to simplify a query's jointree.
459 * If we succeed in pulling up a subquery then we might form a jointree
460 * in which a FromExpr is a direct child of another FromExpr. In that
461 * case we can consider collapsing the two FromExprs into one. This is
462 * an optional conversion, since the planner will work correctly either
463 * way. But we may find a better plan (at the cost of more planning time)
464 * if we merge the two nodes.
466 * NOTE: don't try to do this in the same jointree scan that does subquery
467 * pullup! Since we're changing the jointree structure here, that wouldn't
468 * work reliably --- see comments for pull_up_subqueries().
471 preprocess_jointree(Query *parse, Node *jtnode)
475 if (IsA(jtnode, RangeTblRef))
477 /* nothing to do here... */
479 else if (IsA(jtnode, FromExpr))
481 FromExpr *f = (FromExpr *) jtnode;
485 foreach(l, f->fromlist)
487 Node *child = (Node *) lfirst(l);
489 /* Recursively simplify the child... */
490 child = preprocess_jointree(parse, child);
491 /* Now, is it a FromExpr? */
492 if (child && IsA(child, FromExpr))
495 * Yes, so do we want to merge it into parent? Always do so
496 * if child has just one element (since that doesn't make the
497 * parent's list any longer). Otherwise we have to be careful
498 * about the increase in planning time caused by combining the
499 * two join search spaces into one. Our heuristic is to merge
500 * if the merge will produce a join list no longer than
501 * GEQO_RELS/2. (Perhaps need an additional user parameter?)
503 FromExpr *subf = (FromExpr *) child;
504 int childlen = length(subf->fromlist);
505 int myothers = length(newlist) + length(lnext(l));
507 if (childlen <= 1 || (childlen+myothers) <= geqo_rels/2)
509 newlist = nconc(newlist, subf->fromlist);
510 f->quals = make_and_qual(f->quals, subf->quals);
513 newlist = lappend(newlist, child);
516 newlist = lappend(newlist, child);
518 f->fromlist = newlist;
520 else if (IsA(jtnode, JoinExpr))
522 JoinExpr *j = (JoinExpr *) jtnode;
524 /* Can't usefully change the JoinExpr, but recurse on children */
525 j->larg = preprocess_jointree(parse, j->larg);
526 j->rarg = preprocess_jointree(parse, j->rarg);
529 elog(ERROR, "preprocess_jointree: unexpected node type %d",
535 * preprocess_expression
536 * Do subquery_planner's preprocessing work for an expression,
537 * which can be a targetlist, a WHERE clause (including JOIN/ON
538 * conditions), or a HAVING clause.
541 preprocess_expression(Query *parse, Node *expr, int kind)
544 * Simplify constant expressions.
546 * Note that at this point quals have not yet been converted to
547 * implicit-AND form, so we can apply eval_const_expressions directly.
548 * Also note that we need to do this before SS_process_sublinks,
549 * because that routine inserts bogus "Const" nodes.
551 expr = eval_const_expressions(expr);
554 * If it's a qual or havingQual, canonicalize it, and convert it
555 * to implicit-AND format.
557 * XXX Is there any value in re-applying eval_const_expressions after
560 if (kind != EXPRKIND_TARGET)
562 expr = (Node *) canonicalize_qual((Expr *) expr, true);
564 #ifdef OPTIMIZER_DEBUG
565 printf("After canonicalize_qual()\n");
570 if (parse->hasSubLinks)
572 /* Expand SubLinks to SubPlans */
573 expr = SS_process_sublinks(expr);
575 if (kind != EXPRKIND_WHERE &&
576 (parse->groupClause != NIL || parse->hasAggs))
579 * Check for ungrouped variables passed to subplans. Note we
580 * do NOT do this for subplans in WHERE (or JOIN/ON); it's legal
581 * there because WHERE is evaluated pre-GROUP.
583 check_subplans_for_ungrouped_vars(expr, parse);
587 /* Replace uplevel vars with Param nodes */
588 if (PlannerQueryLevel > 1)
589 expr = SS_replace_correlation_vars(expr);
595 * preprocess_qual_conditions
596 * Recursively scan the query's jointree and do subquery_planner's
597 * preprocessing work on each qual condition found therein.
600 preprocess_qual_conditions(Query *parse, Node *jtnode)
604 if (IsA(jtnode, RangeTblRef))
606 /* nothing to do here */
608 else if (IsA(jtnode, FromExpr))
610 FromExpr *f = (FromExpr *) jtnode;
613 foreach(l, f->fromlist)
614 preprocess_qual_conditions(parse, lfirst(l));
616 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_WHERE);
618 else if (IsA(jtnode, JoinExpr))
620 JoinExpr *j = (JoinExpr *) jtnode;
622 preprocess_qual_conditions(parse, j->larg);
623 preprocess_qual_conditions(parse, j->rarg);
625 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_WHERE);
628 elog(ERROR, "preprocess_qual_conditions: unexpected node type %d",
632 /*--------------------
633 * inheritance_planner
634 * Generate a plan in the case where the result relation is an
637 * We have to handle this case differently from cases where a source
638 * relation is an inheritance set. Source inheritance is expanded at
639 * the bottom of the plan tree (see allpaths.c), but target inheritance
640 * has to be expanded at the top. The reason is that for UPDATE, each
641 * target relation needs a different targetlist matching its own column
642 * set. (This is not so critical for DELETE, but for simplicity we treat
643 * inherited DELETE the same way.) Fortunately, the UPDATE/DELETE target
644 * can never be the nullable side of an outer join, so it's OK to generate
647 * parse is the querytree produced by the parser & rewriter.
648 * inheritlist is an integer list of RT indexes for the result relation set.
650 * Returns a query plan.
651 *--------------------
654 inheritance_planner(Query *parse, List *inheritlist)
656 int parentRTindex = parse->resultRelation;
657 Oid parentOID = getrelid(parentRTindex, parse->rtable);
658 List *subplans = NIL;
662 foreach(l, inheritlist)
664 int childRTindex = lfirsti(l);
665 Oid childOID = getrelid(childRTindex, parse->rtable);
669 /* Generate modified query with this rel as target */
670 subquery = (Query *) adjust_inherited_attrs((Node *) parse,
671 parentRTindex, parentOID,
672 childRTindex, childOID);
674 subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */);
675 subplans = lappend(subplans, subplan);
676 /* Save preprocessed tlist from first rel for use in Append */
678 tlist = subplan->targetlist;
681 /* Save the target-relations list for the executor, too */
682 parse->resultRelations = inheritlist;
684 return (Plan *) make_append(subplans, true, tlist);
687 /*--------------------
689 * Perform planning steps related to grouping, aggregation, etc.
690 * This primarily means adding top-level processing to the basic
691 * query plan produced by query_planner.
693 * parse is the querytree produced by the parser & rewriter.
694 * tuple_fraction is the fraction of tuples we expect will be retrieved
696 * tuple_fraction is interpreted as follows:
697 * < 0: determine fraction by inspection of query (normal case)
698 * 0: expect all tuples to be retrieved
699 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
700 * from the plan to be retrieved
701 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
702 * expected to be retrieved (ie, a LIMIT specification)
703 * The normal case is to pass -1, but some callers pass values >= 0 to
704 * override this routine's determination of the appropriate fraction.
706 * Returns a query plan.
707 *--------------------
710 grouping_planner(Query *parse, double tuple_fraction)
712 List *tlist = parse->targetList;
714 List *current_pathkeys;
715 List *group_pathkeys;
717 AttrNumber *groupColIdx = NULL;
719 if (parse->setOperations)
722 * Construct the plan for set operations. The result will not
723 * need any work except perhaps a top-level sort and/or LIMIT.
725 result_plan = plan_set_operations(parse);
728 * We should not need to call preprocess_targetlist, since we must
729 * be in a SELECT query node. Instead, use the targetlist
730 * returned by plan_set_operations (since this tells whether it
731 * returned any resjunk columns!), and transfer any sort key
732 * information from the original tlist.
734 Assert(parse->commandType == CMD_SELECT);
736 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
739 * Can't handle FOR UPDATE here (parser should have checked already,
740 * but let's make sure).
743 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
746 * We set current_pathkeys NIL indicating we do not know sort
747 * order. This is correct when the top set operation is UNION ALL,
748 * since the appended-together results are unsorted even if the
749 * subplans were sorted. For other set operations we could be
750 * smarter --- room for future improvement!
752 current_pathkeys = NIL;
755 * Calculate pathkeys that represent grouping/ordering
756 * requirements (grouping should always be null, but...)
758 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
760 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
767 /* Preprocess targetlist in case we are inside an INSERT/UPDATE. */
768 tlist = preprocess_targetlist(tlist,
770 parse->resultRelation,
774 * Add TID targets for rels selected FOR UPDATE (should this be
775 * done in preprocess_targetlist?). The executor uses the TID
776 * to know which rows to lock, much as for UPDATE or DELETE.
783 * We've got trouble if the FOR UPDATE appears inside grouping,
784 * since grouping renders a reference to individual tuple CTIDs
785 * invalid. This is also checked at parse time, but that's
786 * insufficient because of rule substitution, query pullup, etc.
788 CheckSelectForUpdate(parse);
790 /* Currently the executor only supports FOR UPDATE at top level */
791 if (PlannerQueryLevel > 1)
792 elog(ERROR, "SELECT FOR UPDATE is not allowed in subselects");
794 foreach(l, parse->rowMarks)
796 Index rti = lfirsti(l);
802 resname = (char *) palloc(32);
803 sprintf(resname, "ctid%u", rti);
804 resdom = makeResdom(length(tlist) + 1,
811 SelfItemPointerAttributeNumber,
816 ctid = makeTargetEntry(resdom, (Node *) var);
817 tlist = lappend(tlist, ctid);
822 * Generate appropriate target list for subplan; may be different
823 * from tlist if grouping or aggregation is needed.
825 sub_tlist = make_subplanTargetList(parse, tlist, &groupColIdx);
828 * Calculate pathkeys that represent grouping/ordering
831 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
833 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
837 * Figure out whether we need a sorted result from query_planner.
839 * If we have a GROUP BY clause, then we want a result sorted
840 * properly for grouping. Otherwise, if there is an ORDER BY
841 * clause, we want to sort by the ORDER BY clause. (Note: if we
842 * have both, and ORDER BY is a superset of GROUP BY, it would be
843 * tempting to request sort by ORDER BY --- but that might just
844 * leave us failing to exploit an available sort order at all.
845 * Needs more thought...)
847 if (parse->groupClause)
848 parse->query_pathkeys = group_pathkeys;
849 else if (parse->sortClause)
850 parse->query_pathkeys = sort_pathkeys;
852 parse->query_pathkeys = NIL;
855 * Figure out whether we expect to retrieve all the tuples that
856 * the plan can generate, or to stop early due to a LIMIT or other
857 * factors. If the caller passed a value >= 0, believe that
858 * value, else do our own examination of the query context.
860 if (tuple_fraction < 0.0)
862 /* Initial assumption is we need all the tuples */
863 tuple_fraction = 0.0;
866 * Check for a LIMIT clause.
868 if (parse->limitCount != NULL)
870 if (IsA(parse->limitCount, Const))
872 Const *limitc = (Const *) parse->limitCount;
873 int32 count = DatumGetInt32(limitc->constvalue);
876 * A NULL-constant LIMIT represents "LIMIT ALL",
877 * which we treat the same as no limit (ie,
878 * expect to retrieve all the tuples).
880 if (!limitc->constisnull && count > 0)
882 tuple_fraction = (double) count;
883 /* We must also consider the OFFSET, if present */
884 if (parse->limitOffset != NULL)
886 if (IsA(parse->limitOffset, Const))
890 limitc = (Const *) parse->limitOffset;
891 offset = DatumGetInt32(limitc->constvalue);
892 if (!limitc->constisnull && offset > 0)
893 tuple_fraction += (double) offset;
897 /* It's an expression ... punt ... */
898 tuple_fraction = 0.10;
906 * COUNT is an expression ... don't know exactly what the
907 * limit will be, but for lack of a better idea assume
908 * 10% of the plan's result is wanted.
910 tuple_fraction = 0.10;
915 * If no LIMIT, check for retrieve-into-portal, ie DECLARE CURSOR.
917 * We have no real idea how many tuples the user will ultimately
918 * FETCH from a cursor, but it seems a good bet that he
919 * doesn't want 'em all. Optimize for 10% retrieval (you
920 * gotta better number?)
922 else if (parse->isPortal)
923 tuple_fraction = 0.10;
927 * Adjust tuple_fraction if we see that we are going to apply
928 * grouping/aggregation/etc. This is not overridable by the
929 * caller, since it reflects plan actions that this routine will
930 * certainly take, not assumptions about context.
932 if (parse->groupClause)
936 * In GROUP BY mode, we have the little problem that we don't
937 * really know how many input tuples will be needed to make a
938 * group, so we can't translate an output LIMIT count into an
939 * input count. For lack of a better idea, assume 25% of the
940 * input data will be processed if there is any output limit.
941 * However, if the caller gave us a fraction rather than an
942 * absolute count, we can keep using that fraction (which
943 * amounts to assuming that all the groups are about the same
946 if (tuple_fraction >= 1.0)
947 tuple_fraction = 0.25;
950 * If both GROUP BY and ORDER BY are specified, we will need
951 * two levels of sort --- and, therefore, certainly need to
952 * read all the input tuples --- unless ORDER BY is a subset
953 * of GROUP BY. (We have not yet canonicalized the pathkeys,
954 * so must use the slower noncanonical comparison method.)
956 if (parse->groupClause && parse->sortClause &&
957 !noncanonical_pathkeys_contained_in(sort_pathkeys,
959 tuple_fraction = 0.0;
961 else if (parse->hasAggs)
965 * Ungrouped aggregate will certainly want all the input
968 tuple_fraction = 0.0;
970 else if (parse->distinctClause)
974 * SELECT DISTINCT, like GROUP, will absorb an unpredictable
975 * number of input tuples per output tuple. Handle the same
978 if (tuple_fraction >= 1.0)
979 tuple_fraction = 0.25;
982 /* Generate the basic plan for this Query */
983 result_plan = query_planner(parse,
988 * query_planner returns actual sort order (which is not
989 * necessarily what we requested) in query_pathkeys.
991 current_pathkeys = parse->query_pathkeys;
995 * We couldn't canonicalize group_pathkeys and sort_pathkeys before
996 * running query_planner(), so do it now.
998 group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
999 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
1002 * If we have a GROUP BY clause, insert a group node (plus the
1003 * appropriate sort node, if necessary).
1005 if (parse->groupClause)
1012 * Decide whether how many tuples per group the Group node needs
1013 * to return. (Needs only one tuple per group if no aggregate is
1014 * present. Otherwise, need every tuple from the group to do the
1015 * aggregation.) Note tuplePerGroup is named backwards :-(
1017 tuplePerGroup = parse->hasAggs;
1020 * If there are aggregates then the Group node should just return
1021 * the same set of vars as the subplan did (but we can exclude any
1022 * GROUP BY expressions). If there are no aggregates then the
1023 * Group node had better compute the final tlist.
1026 group_tlist = flatten_tlist(result_plan->targetlist);
1028 group_tlist = tlist;
1031 * Figure out whether the path result is already ordered the way
1032 * we need it --- if so, no need for an explicit sort step.
1034 if (pathkeys_contained_in(group_pathkeys, current_pathkeys))
1036 is_sorted = true; /* no sort needed now */
1037 /* current_pathkeys remains unchanged */
1043 * We will need to do an explicit sort by the GROUP BY clause.
1044 * make_groupplan will do the work, but set current_pathkeys
1045 * to indicate the resulting order.
1048 current_pathkeys = group_pathkeys;
1051 result_plan = make_groupplan(group_tlist,
1060 * If aggregate is present, insert the Agg node
1062 * HAVING clause, if any, becomes qual of the Agg node
1066 result_plan = (Plan *) make_agg(tlist,
1067 (List *) parse->havingQual,
1069 /* Note: Agg does not affect any existing sort order of the tuples */
1073 /* If there are no Aggs, we shouldn't have any HAVING qual anymore */
1074 Assert(parse->havingQual == NULL);
1078 * If we were not able to make the plan come out in the right order,
1079 * add an explicit sort step.
1081 if (parse->sortClause)
1083 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1084 result_plan = make_sortplan(tlist, result_plan,
1089 * If there is a DISTINCT clause, add the UNIQUE node.
1091 if (parse->distinctClause)
1093 result_plan = (Plan *) make_unique(tlist, result_plan,
1094 parse->distinctClause);
1098 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1100 if (parse->limitOffset || parse->limitCount)
1102 result_plan = (Plan *) make_limit(tlist, result_plan,
1111 * make_subplanTargetList
1112 * Generate appropriate target list when grouping is required.
1114 * When grouping_planner inserts Aggregate and/or Group plan nodes above
1115 * the result of query_planner, we typically want to pass a different
1116 * target list to query_planner than the outer plan nodes should have.
1117 * This routine generates the correct target list for the subplan.
1119 * The initial target list passed from the parser already contains entries
1120 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1121 * for variables used only in HAVING clauses; so we need to add those
1122 * variables to the subplan target list. Also, if we are doing either
1123 * grouping or aggregation, we flatten all expressions except GROUP BY items
1124 * into their component variables; the other expressions will be computed by
1125 * the inserted nodes rather than by the subplan. For example,
1126 * given a query like
1127 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1128 * we want to pass this targetlist to the subplan:
1130 * where the a+b target will be used by the Sort/Group steps, and the
1131 * other targets will be used for computing the final results. (In the
1132 * above example we could theoretically suppress the a and b targets and
1133 * use only a+b, but it's not really worth the trouble.)
1135 * 'parse' is the query being processed.
1136 * 'tlist' is the query's target list.
1137 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1138 * expressions (if there are any) in the subplan's target list.
1140 * The result is the targetlist to be passed to the subplan.
1144 make_subplanTargetList(Query *parse,
1146 AttrNumber **groupColIdx)
1152 *groupColIdx = NULL;
1155 * If we're not grouping or aggregating, nothing to do here;
1156 * query_planner should receive the unmodified target list.
1158 if (!parse->hasAggs && !parse->groupClause && !parse->havingQual)
1162 * Otherwise, start with a "flattened" tlist (having just the vars
1163 * mentioned in the targetlist and HAVING qual --- but not upper-
1164 * level Vars; they will be replaced by Params later on).
1166 sub_tlist = flatten_tlist(tlist);
1167 extravars = pull_var_clause(parse->havingQual, false);
1168 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1169 freeList(extravars);
1172 * If grouping, create sub_tlist entries for all GROUP BY expressions
1173 * (GROUP BY items that are simple Vars should be in the list
1174 * already), and make an array showing where the group columns are in
1177 numCols = length(parse->groupClause);
1181 AttrNumber *grpColIdx;
1184 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1185 *groupColIdx = grpColIdx;
1187 foreach(gl, parse->groupClause)
1189 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1190 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1191 TargetEntry *te = NULL;
1194 /* Find or make a matching sub_tlist entry */
1195 foreach(sl, sub_tlist)
1197 te = (TargetEntry *) lfirst(sl);
1198 if (equal(groupexpr, te->expr))
1203 te = makeTargetEntry(makeResdom(length(sub_tlist) + 1,
1204 exprType(groupexpr),
1205 exprTypmod(groupexpr),
1209 sub_tlist = lappend(sub_tlist, te);
1212 /* and save its resno */
1213 grpColIdx[keyno++] = te->resdom->resno;
1222 * Add a Group node for GROUP BY processing.
1223 * If we couldn't make the subplan produce presorted output for grouping,
1224 * first add an explicit Sort node.
1227 make_groupplan(List *group_tlist,
1230 AttrNumber *grpColIdx,
1234 int numCols = length(groupClause);
1240 * The Sort node always just takes a copy of the subplan's tlist
1241 * plus ordering information. (This might seem inefficient if the
1242 * subplan contains complex GROUP BY expressions, but in fact Sort
1243 * does not evaluate its targetlist --- it only outputs the same
1244 * tuples in a new order. So the expressions we might be copying
1245 * are just dummies with no extra execution cost.)
1247 List *sort_tlist = new_unsorted_tlist(subplan->targetlist);
1251 foreach(gl, groupClause)
1253 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1254 TargetEntry *te = nth(grpColIdx[keyno] - 1, sort_tlist);
1255 Resdom *resdom = te->resdom;
1258 * Check for the possibility of duplicate group-by clauses ---
1259 * the parser should have removed 'em, but the Sort executor
1260 * will get terribly confused if any get through!
1262 if (resdom->reskey == 0)
1264 /* OK, insert the ordering info needed by the executor. */
1265 resdom->reskey = ++keyno;
1266 resdom->reskeyop = get_opcode(grpcl->sortop);
1272 subplan = (Plan *) make_sort(sort_tlist, subplan, keyno);
1275 return (Plan *) make_group(group_tlist, tuplePerGroup, numCols,
1276 grpColIdx, subplan);
1281 * Add a Sort node to implement an explicit ORDER BY clause.
1284 make_sortplan(List *tlist, Plan *plannode, List *sortcls)
1291 * First make a copy of the tlist so that we don't corrupt the
1294 sort_tlist = new_unsorted_tlist(tlist);
1298 SortClause *sortcl = (SortClause *) lfirst(i);
1299 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sort_tlist);
1300 Resdom *resdom = tle->resdom;
1303 * Check for the possibility of duplicate order-by clauses --- the
1304 * parser should have removed 'em, but the executor will get
1305 * terribly confused if any get through!
1307 if (resdom->reskey == 0)
1309 /* OK, insert the ordering info needed by the executor. */
1310 resdom->reskey = ++keyno;
1311 resdom->reskeyop = get_opcode(sortcl->sortop);
1317 return (Plan *) make_sort(sort_tlist, plannode, keyno);
1321 * postprocess_setop_tlist
1322 * Fix up targetlist returned by plan_set_operations().
1324 * We need to transpose sort key info from the orig_tlist into new_tlist.
1325 * NOTE: this would not be good enough if we supported resjunk sort keys
1326 * for results of set operations --- then, we'd need to project a whole
1327 * new tlist to evaluate the resjunk columns. For now, just elog if we
1328 * find any resjunk columns in orig_tlist.
1331 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1335 foreach(l, new_tlist)
1337 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1338 TargetEntry *orig_tle;
1340 /* ignore resjunk columns in setop result */
1341 if (new_tle->resdom->resjunk)
1344 Assert(orig_tlist != NIL);
1345 orig_tle = (TargetEntry *) lfirst(orig_tlist);
1346 orig_tlist = lnext(orig_tlist);
1347 if (orig_tle->resdom->resjunk)
1348 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");
1349 Assert(new_tle->resdom->resno == orig_tle->resdom->resno);
1350 Assert(new_tle->resdom->restype == orig_tle->resdom->restype);
1351 new_tle->resdom->ressortgroupref = orig_tle->resdom->ressortgroupref;
1353 if (orig_tlist != NIL)
1354 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");