1 /*-------------------------------------------------------------------------
4 * The query optimizer external interface.
6 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/optimizer/plan/planner.c,v 1.98 2000/12/14 22:30:43 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;
137 /* Set up for a new level of subquery */
139 PlannerInitPlan = NIL;
141 #ifdef ENABLE_KEY_SET_QUERY
142 /* this should go away sometime soon */
143 transformKeySetQuery(parse);
147 * Check to see if any subqueries in the rangetable can be merged into
150 parse->jointree = (FromExpr *)
151 pull_up_subqueries(parse, (Node *) parse->jointree);
153 * If so, we may have created opportunities to simplify the jointree.
155 parse->jointree = (FromExpr *)
156 preprocess_jointree(parse, (Node *) parse->jointree);
159 * A HAVING clause without aggregates is equivalent to a WHERE clause
160 * (except it can only refer to grouped fields). If there are no aggs
161 * anywhere in the query, then we don't want to create an Agg plan
162 * node, so merge the HAVING condition into WHERE. (We used to
163 * consider this an error condition, but it seems to be legal SQL.)
165 if (parse->havingQual != NULL && !parse->hasAggs)
167 parse->jointree->quals = make_and_qual(parse->jointree->quals,
169 parse->havingQual = NULL;
173 * Do expression preprocessing on targetlist and quals.
175 parse->targetList = (List *)
176 preprocess_expression(parse, (Node *) parse->targetList,
179 preprocess_qual_conditions(parse, (Node *) parse->jointree);
181 parse->havingQual = preprocess_expression(parse, parse->havingQual,
185 * Do the main planning. If we have an inherited target relation,
186 * that needs special processing, else go straight to grouping_planner.
188 if (parse->resultRelation &&
189 (lst = expand_inherted_rtentry(parse, parse->resultRelation)) != NIL)
190 plan = inheritance_planner(parse, lst);
192 plan = grouping_planner(parse, tuple_fraction);
195 * If any subplans were generated, or if we're inside a subplan,
196 * build subPlan, extParam and locParam lists for plan nodes.
198 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
200 (void) SS_finalize_plan(plan);
202 * At the moment, SS_finalize_plan doesn't handle initPlans
203 * and so we assign them to the topmost plan node.
205 plan->initPlan = PlannerInitPlan;
206 /* Must add the initPlans' extParams to the topmost node's, too */
207 foreach(lst, plan->initPlan)
209 SubPlan *subplan = (SubPlan *) lfirst(lst);
211 plan->extParam = set_unioni(plan->extParam,
212 subplan->plan->extParam);
216 /* Return to outer subquery context */
218 PlannerInitPlan = saved_initplan;
219 /* we do NOT restore PlannerPlanId; that's not an oversight! */
226 * Look for subqueries in the rangetable that can be pulled up into
227 * the parent query. If the subquery has no special features like
228 * grouping/aggregation then we can merge it into the parent's jointree.
230 * A tricky aspect of this code is that if we pull up a subquery we have
231 * to replace Vars that reference the subquery's outputs throughout the
232 * parent query, including quals attached to jointree nodes above the one
233 * we are currently processing! We handle this by being careful not to
234 * change the jointree structure while recursing: no nodes other than
235 * subquery RangeTblRef entries will be replaced. Also, we can't turn
236 * ResolveNew loose on the whole jointree, because it'll return a mutated
237 * copy of the tree; we have to invoke it just on the quals, instead.
240 pull_up_subqueries(Query *parse, Node *jtnode)
244 if (IsA(jtnode, RangeTblRef))
246 int varno = ((RangeTblRef *) jtnode)->rtindex;
247 RangeTblEntry *rte = rt_fetch(varno, parse->rtable);
248 Query *subquery = rte->subquery;
251 * Is this a subquery RTE, and if so, is the subquery simple enough
252 * to pull up? (If not, do nothing at this node.)
254 if (subquery && is_simple_subquery(subquery))
262 * First, recursively pull up the subquery's subqueries,
263 * so that this routine's processing is complete for its
264 * jointree and rangetable.
266 subquery->jointree = (FromExpr *)
267 pull_up_subqueries(subquery, (Node *) subquery->jointree);
269 * Append the subquery's rangetable to mine (currently,
270 * no adjustments will be needed in the subquery's rtable).
272 rtoffset = length(parse->rtable);
273 parse->rtable = nconc(parse->rtable, subquery->rtable);
275 * Make copies of the subquery's jointree and targetlist
276 * with varnos adjusted to match the merged rangetable.
278 subjointree = copyObject(subquery->jointree);
279 OffsetVarNodes(subjointree, rtoffset, 0);
280 subtlist = copyObject(subquery->targetList);
281 OffsetVarNodes((Node *) subtlist, rtoffset, 0);
283 * Replace all of the top query's references to the subquery's
284 * outputs with copies of the adjusted subtlist items, being
285 * careful not to replace any of the jointree structure.
287 parse->targetList = (List *)
288 ResolveNew((Node *) parse->targetList,
289 varno, 0, subtlist, CMD_SELECT, 0);
290 resolvenew_in_jointree((Node *) parse->jointree, varno, subtlist);
292 ResolveNew(parse->havingQual,
293 varno, 0, subtlist, CMD_SELECT, 0);
295 * Pull up any FOR UPDATE markers, too.
297 foreach(l, subquery->rowMarks)
299 int submark = lfirsti(l);
301 parse->rowMarks = lappendi(parse->rowMarks,
305 * Miscellaneous housekeeping.
307 parse->hasSubLinks |= subquery->hasSubLinks;
308 /* subquery won't be pulled up if it hasAggs, so no work there */
311 * Return the adjusted subquery jointree to replace the
312 * RangeTblRef entry in my jointree.
317 else if (IsA(jtnode, FromExpr))
319 FromExpr *f = (FromExpr *) jtnode;
322 foreach(l, f->fromlist)
324 lfirst(l) = pull_up_subqueries(parse, lfirst(l));
327 else if (IsA(jtnode, JoinExpr))
329 JoinExpr *j = (JoinExpr *) jtnode;
331 j->larg = pull_up_subqueries(parse, j->larg);
332 j->rarg = pull_up_subqueries(parse, j->rarg);
335 elog(ERROR, "pull_up_subqueries: unexpected node type %d",
342 * Check a subquery in the range table to see if it's simple enough
343 * to pull up into the parent query.
346 is_simple_subquery(Query *subquery)
349 * Let's just make sure it's a valid subselect ...
351 if (!IsA(subquery, Query) ||
352 subquery->commandType != CMD_SELECT ||
353 subquery->resultRelation != 0 ||
354 subquery->into != NULL ||
356 elog(ERROR, "is_simple_subquery: subquery is bogus");
358 * Can't currently pull up a query with setops.
359 * Maybe after querytree redesign...
361 if (subquery->setOperations)
364 * Can't pull up a subquery involving grouping, aggregation, sorting,
367 if (subquery->hasAggs ||
368 subquery->groupClause ||
369 subquery->havingQual ||
370 subquery->sortClause ||
371 subquery->distinctClause ||
372 subquery->limitOffset ||
373 subquery->limitCount)
376 * Hack: don't try to pull up a subquery with an empty jointree.
377 * query_planner() will correctly generate a Result plan for a
378 * jointree that's totally empty, but I don't think the right things
379 * happen if an empty FromExpr appears lower down in a jointree.
380 * Not worth working hard on this, just to collapse SubqueryScan/Result
383 if (subquery->jointree->fromlist == NIL)
390 * Helper routine for pull_up_subqueries: do ResolveNew on every expression
391 * in the jointree, without changing the jointree structure itself. Ugly,
392 * but there's no other way...
395 resolvenew_in_jointree(Node *jtnode, int varno, List *subtlist)
399 if (IsA(jtnode, RangeTblRef))
401 /* nothing to do here */
403 else if (IsA(jtnode, FromExpr))
405 FromExpr *f = (FromExpr *) jtnode;
408 foreach(l, f->fromlist)
409 resolvenew_in_jointree(lfirst(l), varno, subtlist);
410 f->quals = ResolveNew(f->quals,
411 varno, 0, subtlist, CMD_SELECT, 0);
413 else if (IsA(jtnode, JoinExpr))
415 JoinExpr *j = (JoinExpr *) jtnode;
417 resolvenew_in_jointree(j->larg, varno, subtlist);
418 resolvenew_in_jointree(j->rarg, varno, subtlist);
419 j->quals = ResolveNew(j->quals,
420 varno, 0, subtlist, CMD_SELECT, 0);
421 /* We don't bother to update the colvars list, since it won't be
426 elog(ERROR, "resolvenew_in_jointree: unexpected node type %d",
431 * preprocess_jointree
432 * Attempt to simplify a query's jointree.
434 * If we succeed in pulling up a subquery then we might form a jointree
435 * in which a FromExpr is a direct child of another FromExpr. In that
436 * case we can consider collapsing the two FromExprs into one. This is
437 * an optional conversion, since the planner will work correctly either
438 * way. But we may find a better plan (at the cost of more planning time)
439 * if we merge the two nodes.
441 * NOTE: don't try to do this in the same jointree scan that does subquery
442 * pullup! Since we're changing the jointree structure here, that wouldn't
443 * work reliably --- see comments for pull_up_subqueries().
446 preprocess_jointree(Query *parse, Node *jtnode)
450 if (IsA(jtnode, RangeTblRef))
452 /* nothing to do here... */
454 else if (IsA(jtnode, FromExpr))
456 FromExpr *f = (FromExpr *) jtnode;
460 foreach(l, f->fromlist)
462 Node *child = (Node *) lfirst(l);
464 /* Recursively simplify the child... */
465 child = preprocess_jointree(parse, child);
466 /* Now, is it a FromExpr? */
467 if (child && IsA(child, FromExpr))
470 * Yes, so do we want to merge it into parent? Always do so
471 * if child has just one element (since that doesn't make the
472 * parent's list any longer). Otherwise we have to be careful
473 * about the increase in planning time caused by combining the
474 * two join search spaces into one. Our heuristic is to merge
475 * if the merge will produce a join list no longer than
476 * GEQO_RELS/2. (Perhaps need an additional user parameter?)
478 FromExpr *subf = (FromExpr *) child;
479 int childlen = length(subf->fromlist);
480 int myothers = length(newlist) + length(lnext(l));
482 if (childlen <= 1 || (childlen+myothers) <= geqo_rels/2)
484 newlist = nconc(newlist, subf->fromlist);
485 f->quals = make_and_qual(f->quals, subf->quals);
488 newlist = lappend(newlist, child);
491 newlist = lappend(newlist, child);
493 f->fromlist = newlist;
495 else if (IsA(jtnode, JoinExpr))
497 JoinExpr *j = (JoinExpr *) jtnode;
499 /* Can't usefully change the JoinExpr, but recurse on children */
500 j->larg = preprocess_jointree(parse, j->larg);
501 j->rarg = preprocess_jointree(parse, j->rarg);
504 elog(ERROR, "preprocess_jointree: unexpected node type %d",
510 * preprocess_expression
511 * Do subquery_planner's preprocessing work for an expression,
512 * which can be a targetlist, a WHERE clause (including JOIN/ON
513 * conditions), or a HAVING clause.
516 preprocess_expression(Query *parse, Node *expr, int kind)
519 * Simplify constant expressions.
521 * Note that at this point quals have not yet been converted to
522 * implicit-AND form, so we can apply eval_const_expressions directly.
523 * Also note that we need to do this before SS_process_sublinks,
524 * because that routine inserts bogus "Const" nodes.
526 expr = eval_const_expressions(expr);
529 * If it's a qual or havingQual, canonicalize it, and convert it
530 * to implicit-AND format.
532 * XXX Is there any value in re-applying eval_const_expressions after
535 if (kind != EXPRKIND_TARGET)
537 expr = (Node *) canonicalize_qual((Expr *) expr, true);
539 #ifdef OPTIMIZER_DEBUG
540 printf("After canonicalize_qual()\n");
545 if (parse->hasSubLinks)
547 /* Expand SubLinks to SubPlans */
548 expr = SS_process_sublinks(expr);
550 if (kind != EXPRKIND_WHERE &&
551 (parse->groupClause != NIL || parse->hasAggs))
554 * Check for ungrouped variables passed to subplans. Note we
555 * do NOT do this for subplans in WHERE (or JOIN/ON); it's legal
556 * there because WHERE is evaluated pre-GROUP.
558 * An interesting fine point: if subquery_planner reassigned a
559 * HAVING qual into WHERE, then we will accept references to
560 * ungrouped vars from subplans in the HAVING qual. This is not
561 * entirely consistent, but it doesn't seem particularly
564 check_subplans_for_ungrouped_vars(expr, parse);
568 /* Replace uplevel vars with Param nodes */
569 if (PlannerQueryLevel > 1)
570 expr = SS_replace_correlation_vars(expr);
576 * preprocess_qual_conditions
577 * Recursively scan the query's jointree and do subquery_planner's
578 * preprocessing work on each qual condition found therein.
581 preprocess_qual_conditions(Query *parse, Node *jtnode)
585 if (IsA(jtnode, RangeTblRef))
587 /* nothing to do here */
589 else if (IsA(jtnode, FromExpr))
591 FromExpr *f = (FromExpr *) jtnode;
594 foreach(l, f->fromlist)
595 preprocess_qual_conditions(parse, lfirst(l));
597 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_WHERE);
599 else if (IsA(jtnode, JoinExpr))
601 JoinExpr *j = (JoinExpr *) jtnode;
603 preprocess_qual_conditions(parse, j->larg);
604 preprocess_qual_conditions(parse, j->rarg);
606 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_WHERE);
609 elog(ERROR, "preprocess_qual_conditions: unexpected node type %d",
613 /*--------------------
614 * inheritance_planner
615 * Generate a plan in the case where the result relation is an
618 * We have to handle this case differently from cases where a source
619 * relation is an inheritance set. Source inheritance is expanded at
620 * the bottom of the plan tree (see allpaths.c), but target inheritance
621 * has to be expanded at the top. The reason is that for UPDATE, each
622 * target relation needs a different targetlist matching its own column
623 * set. (This is not so critical for DELETE, but for simplicity we treat
624 * inherited DELETE the same way.) Fortunately, the UPDATE/DELETE target
625 * can never be the nullable side of an outer join, so it's OK to generate
628 * parse is the querytree produced by the parser & rewriter.
629 * inheritlist is an integer list of RT indexes for the result relation set.
631 * Returns a query plan.
632 *--------------------
635 inheritance_planner(Query *parse, List *inheritlist)
637 int parentRTindex = parse->resultRelation;
638 Oid parentOID = getrelid(parentRTindex, parse->rtable);
639 List *subplans = NIL;
643 foreach(l, inheritlist)
645 int childRTindex = lfirsti(l);
646 Oid childOID = getrelid(childRTindex, parse->rtable);
650 /* Generate modified query with this rel as target */
651 subquery = (Query *) adjust_inherited_attrs((Node *) parse,
652 parentRTindex, parentOID,
653 childRTindex, childOID);
655 subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */);
656 subplans = lappend(subplans, subplan);
657 /* Save preprocessed tlist from first rel for use in Append */
659 tlist = subplan->targetlist;
662 /* Save the target-relations list for the executor, too */
663 parse->resultRelations = inheritlist;
665 return (Plan *) make_append(subplans, true, tlist);
668 /*--------------------
670 * Perform planning steps related to grouping, aggregation, etc.
671 * This primarily means adding top-level processing to the basic
672 * query plan produced by query_planner.
674 * parse is the querytree produced by the parser & rewriter.
675 * tuple_fraction is the fraction of tuples we expect will be retrieved
677 * tuple_fraction is interpreted as follows:
678 * < 0: determine fraction by inspection of query (normal case)
679 * 0: expect all tuples to be retrieved
680 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
681 * from the plan to be retrieved
682 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
683 * expected to be retrieved (ie, a LIMIT specification)
684 * The normal case is to pass -1, but some callers pass values >= 0 to
685 * override this routine's determination of the appropriate fraction.
687 * Returns a query plan.
688 *--------------------
691 grouping_planner(Query *parse, double tuple_fraction)
693 List *tlist = parse->targetList;
695 List *current_pathkeys;
696 List *group_pathkeys;
698 AttrNumber *groupColIdx = NULL;
700 if (parse->setOperations)
703 * Construct the plan for set operations. The result will not
704 * need any work except perhaps a top-level sort and/or LIMIT.
706 result_plan = plan_set_operations(parse);
709 * We should not need to call preprocess_targetlist, since we must
710 * be in a SELECT query node. Instead, use the targetlist
711 * returned by plan_set_operations (since this tells whether it
712 * returned any resjunk columns!), and transfer any sort key
713 * information from the original tlist.
715 Assert(parse->commandType == CMD_SELECT);
717 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
720 * Can't handle FOR UPDATE here (parser should have checked already,
721 * but let's make sure).
724 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
727 * We set current_pathkeys NIL indicating we do not know sort
728 * order. This is correct when the top set operation is UNION ALL,
729 * since the appended-together results are unsorted even if the
730 * subplans were sorted. For other set operations we could be
731 * smarter --- room for future improvement!
733 current_pathkeys = NIL;
736 * Calculate pathkeys that represent grouping/ordering
737 * requirements (grouping should always be null, but...)
739 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
741 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
748 /* Preprocess targetlist in case we are inside an INSERT/UPDATE. */
749 tlist = preprocess_targetlist(tlist,
751 parse->resultRelation,
755 * Add TID targets for rels selected FOR UPDATE (should this be
756 * done in preprocess_targetlist?). The executor uses the TID
757 * to know which rows to lock, much as for UPDATE or DELETE.
764 * We've got trouble if the FOR UPDATE appears inside grouping,
765 * since grouping renders a reference to individual tuple CTIDs
766 * invalid. This is also checked at parse time, but that's
767 * insufficient because of rule substitution, query pullup, etc.
769 CheckSelectForUpdate(parse);
771 /* Currently the executor only supports FOR UPDATE at top level */
772 if (PlannerQueryLevel > 1)
773 elog(ERROR, "SELECT FOR UPDATE is not allowed in subselects");
775 foreach(l, parse->rowMarks)
777 Index rti = lfirsti(l);
783 resname = (char *) palloc(32);
784 sprintf(resname, "ctid%u", rti);
785 resdom = makeResdom(length(tlist) + 1,
792 SelfItemPointerAttributeNumber,
797 ctid = makeTargetEntry(resdom, (Node *) var);
798 tlist = lappend(tlist, ctid);
803 * Generate appropriate target list for subplan; may be different
804 * from tlist if grouping or aggregation is needed.
806 sub_tlist = make_subplanTargetList(parse, tlist, &groupColIdx);
809 * Calculate pathkeys that represent grouping/ordering
812 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
814 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
818 * Figure out whether we need a sorted result from query_planner.
820 * If we have a GROUP BY clause, then we want a result sorted
821 * properly for grouping. Otherwise, if there is an ORDER BY
822 * clause, we want to sort by the ORDER BY clause. (Note: if we
823 * have both, and ORDER BY is a superset of GROUP BY, it would be
824 * tempting to request sort by ORDER BY --- but that might just
825 * leave us failing to exploit an available sort order at all.
826 * Needs more thought...)
828 if (parse->groupClause)
829 parse->query_pathkeys = group_pathkeys;
830 else if (parse->sortClause)
831 parse->query_pathkeys = sort_pathkeys;
833 parse->query_pathkeys = NIL;
836 * Figure out whether we expect to retrieve all the tuples that
837 * the plan can generate, or to stop early due to a LIMIT or other
838 * factors. If the caller passed a value >= 0, believe that
839 * value, else do our own examination of the query context.
841 if (tuple_fraction < 0.0)
843 /* Initial assumption is we need all the tuples */
844 tuple_fraction = 0.0;
847 * Check for a LIMIT clause.
849 if (parse->limitCount != NULL)
851 if (IsA(parse->limitCount, Const))
853 Const *limitc = (Const *) parse->limitCount;
854 int32 count = DatumGetInt32(limitc->constvalue);
857 * A NULL-constant LIMIT represents "LIMIT ALL",
858 * which we treat the same as no limit (ie,
859 * expect to retrieve all the tuples).
861 if (!limitc->constisnull && count > 0)
863 tuple_fraction = (double) count;
864 /* We must also consider the OFFSET, if present */
865 if (parse->limitOffset != NULL)
867 if (IsA(parse->limitOffset, Const))
871 limitc = (Const *) parse->limitOffset;
872 offset = DatumGetInt32(limitc->constvalue);
873 if (!limitc->constisnull && offset > 0)
874 tuple_fraction += (double) offset;
878 /* It's an expression ... punt ... */
879 tuple_fraction = 0.10;
887 * COUNT is an expression ... don't know exactly what the
888 * limit will be, but for lack of a better idea assume
889 * 10% of the plan's result is wanted.
891 tuple_fraction = 0.10;
896 * If no LIMIT, check for retrieve-into-portal, ie DECLARE CURSOR.
898 * We have no real idea how many tuples the user will ultimately
899 * FETCH from a cursor, but it seems a good bet that he
900 * doesn't want 'em all. Optimize for 10% retrieval (you
901 * gotta better number?)
903 else if (parse->isPortal)
904 tuple_fraction = 0.10;
908 * Adjust tuple_fraction if we see that we are going to apply
909 * grouping/aggregation/etc. This is not overridable by the
910 * caller, since it reflects plan actions that this routine will
911 * certainly take, not assumptions about context.
913 if (parse->groupClause)
917 * In GROUP BY mode, we have the little problem that we don't
918 * really know how many input tuples will be needed to make a
919 * group, so we can't translate an output LIMIT count into an
920 * input count. For lack of a better idea, assume 25% of the
921 * input data will be processed if there is any output limit.
922 * However, if the caller gave us a fraction rather than an
923 * absolute count, we can keep using that fraction (which
924 * amounts to assuming that all the groups are about the same
927 if (tuple_fraction >= 1.0)
928 tuple_fraction = 0.25;
931 * If both GROUP BY and ORDER BY are specified, we will need
932 * two levels of sort --- and, therefore, certainly need to
933 * read all the input tuples --- unless ORDER BY is a subset
934 * of GROUP BY. (We have not yet canonicalized the pathkeys,
935 * so must use the slower noncanonical comparison method.)
937 if (parse->groupClause && parse->sortClause &&
938 !noncanonical_pathkeys_contained_in(sort_pathkeys,
940 tuple_fraction = 0.0;
942 else if (parse->hasAggs)
946 * Ungrouped aggregate will certainly want all the input
949 tuple_fraction = 0.0;
951 else if (parse->distinctClause)
955 * SELECT DISTINCT, like GROUP, will absorb an unpredictable
956 * number of input tuples per output tuple. Handle the same
959 if (tuple_fraction >= 1.0)
960 tuple_fraction = 0.25;
963 /* Generate the basic plan for this Query */
964 result_plan = query_planner(parse,
969 * query_planner returns actual sort order (which is not
970 * necessarily what we requested) in query_pathkeys.
972 current_pathkeys = parse->query_pathkeys;
976 * We couldn't canonicalize group_pathkeys and sort_pathkeys before
977 * running query_planner(), so do it now.
979 group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
980 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
983 * If we have a GROUP BY clause, insert a group node (plus the
984 * appropriate sort node, if necessary).
986 if (parse->groupClause)
993 * Decide whether how many tuples per group the Group node needs
994 * to return. (Needs only one tuple per group if no aggregate is
995 * present. Otherwise, need every tuple from the group to do the
996 * aggregation.) Note tuplePerGroup is named backwards :-(
998 tuplePerGroup = parse->hasAggs;
1001 * If there are aggregates then the Group node should just return
1002 * the same set of vars as the subplan did (but we can exclude any
1003 * GROUP BY expressions). If there are no aggregates then the
1004 * Group node had better compute the final tlist.
1007 group_tlist = flatten_tlist(result_plan->targetlist);
1009 group_tlist = tlist;
1012 * Figure out whether the path result is already ordered the way
1013 * we need it --- if so, no need for an explicit sort step.
1015 if (pathkeys_contained_in(group_pathkeys, current_pathkeys))
1017 is_sorted = true; /* no sort needed now */
1018 /* current_pathkeys remains unchanged */
1024 * We will need to do an explicit sort by the GROUP BY clause.
1025 * make_groupplan will do the work, but set current_pathkeys
1026 * to indicate the resulting order.
1029 current_pathkeys = group_pathkeys;
1032 result_plan = make_groupplan(group_tlist,
1041 * If aggregate is present, insert the Agg node
1043 * HAVING clause, if any, becomes qual of the Agg node
1047 result_plan = (Plan *) make_agg(tlist,
1048 (List *) parse->havingQual,
1050 /* Note: Agg does not affect any existing sort order of the tuples */
1054 * If we were not able to make the plan come out in the right order,
1055 * add an explicit sort step.
1057 if (parse->sortClause)
1059 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1060 result_plan = make_sortplan(tlist, result_plan,
1065 * If there is a DISTINCT clause, add the UNIQUE node.
1067 if (parse->distinctClause)
1069 result_plan = (Plan *) make_unique(tlist, result_plan,
1070 parse->distinctClause);
1074 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1076 if (parse->limitOffset || parse->limitCount)
1078 result_plan = (Plan *) make_limit(tlist, result_plan,
1087 * make_subplanTargetList
1088 * Generate appropriate target list when grouping is required.
1090 * When grouping_planner inserts Aggregate and/or Group plan nodes above
1091 * the result of query_planner, we typically want to pass a different
1092 * target list to query_planner than the outer plan nodes should have.
1093 * This routine generates the correct target list for the subplan.
1095 * The initial target list passed from the parser already contains entries
1096 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1097 * for variables used only in HAVING clauses; so we need to add those
1098 * variables to the subplan target list. Also, if we are doing either
1099 * grouping or aggregation, we flatten all expressions except GROUP BY items
1100 * into their component variables; the other expressions will be computed by
1101 * the inserted nodes rather than by the subplan. For example,
1102 * given a query like
1103 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1104 * we want to pass this targetlist to the subplan:
1106 * where the a+b target will be used by the Sort/Group steps, and the
1107 * other targets will be used for computing the final results. (In the
1108 * above example we could theoretically suppress the a and b targets and
1109 * use only a+b, but it's not really worth the trouble.)
1111 * 'parse' is the query being processed.
1112 * 'tlist' is the query's target list.
1113 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1114 * expressions (if there are any) in the subplan's target list.
1116 * The result is the targetlist to be passed to the subplan.
1120 make_subplanTargetList(Query *parse,
1122 AttrNumber **groupColIdx)
1128 *groupColIdx = NULL;
1131 * If we're not grouping or aggregating, nothing to do here;
1132 * query_planner should receive the unmodified target list.
1134 if (!parse->hasAggs && !parse->groupClause && !parse->havingQual)
1138 * Otherwise, start with a "flattened" tlist (having just the vars
1139 * mentioned in the targetlist and HAVING qual --- but not upper-
1140 * level Vars; they will be replaced by Params later on).
1142 sub_tlist = flatten_tlist(tlist);
1143 extravars = pull_var_clause(parse->havingQual, false);
1144 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1145 freeList(extravars);
1148 * If grouping, create sub_tlist entries for all GROUP BY expressions
1149 * (GROUP BY items that are simple Vars should be in the list
1150 * already), and make an array showing where the group columns are in
1153 numCols = length(parse->groupClause);
1157 AttrNumber *grpColIdx;
1160 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1161 *groupColIdx = grpColIdx;
1163 foreach(gl, parse->groupClause)
1165 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1166 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1167 TargetEntry *te = NULL;
1170 /* Find or make a matching sub_tlist entry */
1171 foreach(sl, sub_tlist)
1173 te = (TargetEntry *) lfirst(sl);
1174 if (equal(groupexpr, te->expr))
1179 te = makeTargetEntry(makeResdom(length(sub_tlist) + 1,
1180 exprType(groupexpr),
1181 exprTypmod(groupexpr),
1185 sub_tlist = lappend(sub_tlist, te);
1188 /* and save its resno */
1189 grpColIdx[keyno++] = te->resdom->resno;
1198 * Add a Group node for GROUP BY processing.
1199 * If we couldn't make the subplan produce presorted output for grouping,
1200 * first add an explicit Sort node.
1203 make_groupplan(List *group_tlist,
1206 AttrNumber *grpColIdx,
1210 int numCols = length(groupClause);
1216 * The Sort node always just takes a copy of the subplan's tlist
1217 * plus ordering information. (This might seem inefficient if the
1218 * subplan contains complex GROUP BY expressions, but in fact Sort
1219 * does not evaluate its targetlist --- it only outputs the same
1220 * tuples in a new order. So the expressions we might be copying
1221 * are just dummies with no extra execution cost.)
1223 List *sort_tlist = new_unsorted_tlist(subplan->targetlist);
1227 foreach(gl, groupClause)
1229 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1230 TargetEntry *te = nth(grpColIdx[keyno] - 1, sort_tlist);
1231 Resdom *resdom = te->resdom;
1234 * Check for the possibility of duplicate group-by clauses ---
1235 * the parser should have removed 'em, but the Sort executor
1236 * will get terribly confused if any get through!
1238 if (resdom->reskey == 0)
1240 /* OK, insert the ordering info needed by the executor. */
1241 resdom->reskey = ++keyno;
1242 resdom->reskeyop = get_opcode(grpcl->sortop);
1248 subplan = (Plan *) make_sort(sort_tlist, subplan, keyno);
1251 return (Plan *) make_group(group_tlist, tuplePerGroup, numCols,
1252 grpColIdx, subplan);
1257 * Add a Sort node to implement an explicit ORDER BY clause.
1260 make_sortplan(List *tlist, Plan *plannode, List *sortcls)
1267 * First make a copy of the tlist so that we don't corrupt the
1270 sort_tlist = new_unsorted_tlist(tlist);
1274 SortClause *sortcl = (SortClause *) lfirst(i);
1275 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sort_tlist);
1276 Resdom *resdom = tle->resdom;
1279 * Check for the possibility of duplicate order-by clauses --- the
1280 * parser should have removed 'em, but the executor will get
1281 * terribly confused if any get through!
1283 if (resdom->reskey == 0)
1285 /* OK, insert the ordering info needed by the executor. */
1286 resdom->reskey = ++keyno;
1287 resdom->reskeyop = get_opcode(sortcl->sortop);
1293 return (Plan *) make_sort(sort_tlist, plannode, keyno);
1297 * postprocess_setop_tlist
1298 * Fix up targetlist returned by plan_set_operations().
1300 * We need to transpose sort key info from the orig_tlist into new_tlist.
1301 * NOTE: this would not be good enough if we supported resjunk sort keys
1302 * for results of set operations --- then, we'd need to project a whole
1303 * new tlist to evaluate the resjunk columns. For now, just elog if we
1304 * find any resjunk columns in orig_tlist.
1307 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1311 foreach(l, new_tlist)
1313 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1314 TargetEntry *orig_tle;
1316 /* ignore resjunk columns in setop result */
1317 if (new_tle->resdom->resjunk)
1320 Assert(orig_tlist != NIL);
1321 orig_tle = (TargetEntry *) lfirst(orig_tlist);
1322 orig_tlist = lnext(orig_tlist);
1323 if (orig_tle->resdom->resjunk)
1324 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");
1325 Assert(new_tle->resdom->resno == orig_tle->resdom->resno);
1326 Assert(new_tle->resdom->restype == orig_tle->resdom->restype);
1327 new_tle->resdom->ressortgroupref = orig_tle->resdom->ressortgroupref;
1329 if (orig_tlist != NIL)
1330 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");