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.95 2000/11/09 02:46:16 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/parsetree.h"
29 #include "parser/parse_expr.h"
30 #include "rewrite/rewriteManip.h"
31 #include "utils/lsyscache.h"
34 /* Expression kind codes for preprocess_expression */
35 #define EXPRKIND_TARGET 0
36 #define EXPRKIND_WHERE 1
37 #define EXPRKIND_HAVING 2
40 static Node *pull_up_subqueries(Query *parse, Node *jtnode);
41 static bool is_simple_subquery(Query *subquery);
42 static void resolvenew_in_jointree(Node *jtnode, int varno, List *subtlist);
43 static Node *preprocess_jointree(Query *parse, Node *jtnode);
44 static Node *preprocess_expression(Query *parse, Node *expr, int kind);
45 static void preprocess_qual_conditions(Query *parse, Node *jtnode);
46 static List *make_subplanTargetList(Query *parse, List *tlist,
47 AttrNumber **groupColIdx);
48 static Plan *make_groupplan(List *group_tlist, bool tuplePerGroup,
49 List *groupClause, AttrNumber *grpColIdx,
50 bool is_presorted, Plan *subplan);
51 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
54 /*****************************************************************************
56 * Query optimizer entry point
58 *****************************************************************************/
63 Index save_PlannerQueryLevel;
64 List *save_PlannerParamVar;
67 * The planner can be called recursively (an example is when
68 * eval_const_expressions tries to simplify an SQL function).
69 * So, these global state variables must be saved and restored.
71 * These vars cannot be moved into the Query structure since their
72 * whole purpose is communication across multiple sub-Queries.
74 * Note we do NOT save and restore PlannerPlanId: it exists to assign
75 * unique IDs to SubPlan nodes, and we want those IDs to be unique
76 * for the life of a backend. Also, PlannerInitPlan is saved/restored
77 * in subquery_planner, not here.
79 save_PlannerQueryLevel = PlannerQueryLevel;
80 save_PlannerParamVar = PlannerParamVar;
82 /* Initialize state for handling outer-level references and params */
83 PlannerQueryLevel = 0; /* will be 1 in top-level subquery_planner */
84 PlannerParamVar = NIL;
86 /* primary planning entry point (may recurse for subqueries) */
87 result_plan = subquery_planner(parse, -1.0 /* default case */ );
89 Assert(PlannerQueryLevel == 0);
91 /* executor wants to know total number of Params used overall */
92 result_plan->nParamExec = length(PlannerParamVar);
94 /* final cleanup of the plan */
95 set_plan_references(result_plan);
97 /* restore state for outer planner, if any */
98 PlannerQueryLevel = save_PlannerQueryLevel;
99 PlannerParamVar = save_PlannerParamVar;
105 /*--------------------
107 * Invokes the planner on a subquery. We recurse to here for each
108 * sub-SELECT found in the query tree.
110 * parse is the querytree produced by the parser & rewriter.
111 * tuple_fraction is the fraction of tuples we expect will be retrieved.
112 * tuple_fraction is interpreted as explained for union_planner, below.
114 * Basically, this routine does the stuff that should only be done once
115 * per Query object. It then calls union_planner, which may be called
116 * recursively on the same Query node in order to handle inheritance.
117 * subquery_planner will be called recursively to handle sub-Query nodes
118 * found within the query's expressions and rangetable.
120 * Returns a query plan.
121 *--------------------
124 subquery_planner(Query *parse, double tuple_fraction)
126 List *saved_initplan = PlannerInitPlan;
127 int saved_planid = PlannerPlanId;
131 /* Set up for a new level of subquery */
133 PlannerInitPlan = NIL;
135 #ifdef ENABLE_KEY_SET_QUERY
136 /* this should go away sometime soon */
137 transformKeySetQuery(parse);
141 * Check to see if any subqueries in the rangetable can be merged into
144 parse->jointree = (FromExpr *)
145 pull_up_subqueries(parse, (Node *) parse->jointree);
147 * If so, we may have created opportunities to simplify the jointree.
149 parse->jointree = (FromExpr *)
150 preprocess_jointree(parse, (Node *) parse->jointree);
153 * A HAVING clause without aggregates is equivalent to a WHERE clause
154 * (except it can only refer to grouped fields). If there are no aggs
155 * anywhere in the query, then we don't want to create an Agg plan
156 * node, so merge the HAVING condition into WHERE. (We used to
157 * consider this an error condition, but it seems to be legal SQL.)
159 if (parse->havingQual != NULL && !parse->hasAggs)
161 parse->jointree->quals = make_and_qual(parse->jointree->quals,
163 parse->havingQual = NULL;
167 * Do 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,
179 * Do the main planning (potentially recursive for inheritance)
181 plan = union_planner(parse, tuple_fraction);
184 * XXX should any more of union_planner's activity be moved here?
186 * That would take careful study of the interactions with prepunion.c,
187 * but I suspect it would pay off in simplicity and avoidance of
192 * If any subplans were generated, or if we're inside a subplan,
193 * build subPlan, extParam and locParam lists for plan nodes.
195 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
197 (void) SS_finalize_plan(plan);
199 * At the moment, SS_finalize_plan doesn't handle initPlans
200 * and so we assign them to the topmost plan node.
202 plan->initPlan = PlannerInitPlan;
203 /* Must add the initPlans' extParams to the topmost node's, too */
204 foreach(lst, plan->initPlan)
206 SubPlan *subplan = (SubPlan *) lfirst(lst);
208 plan->extParam = set_unioni(plan->extParam,
209 subplan->plan->extParam);
213 /* Return to outer subquery context */
215 PlannerInitPlan = saved_initplan;
216 /* we do NOT restore PlannerPlanId; that's not an oversight! */
223 * Look for subqueries in the rangetable that can be pulled up into
224 * the parent query. If the subquery has no special features like
225 * grouping/aggregation then we can merge it into the parent's jointree.
227 * A tricky aspect of this code is that if we pull up a subquery we have
228 * to replace Vars that reference the subquery's outputs throughout the
229 * parent query, including quals attached to jointree nodes above the one
230 * we are currently processing! We handle this by being careful not to
231 * change the jointree structure while recursing: no nodes other than
232 * subquery RangeTblRef entries will be replaced. Also, we can't turn
233 * ResolveNew loose on the whole jointree, because it'll return a mutated
234 * copy of the tree; we have to invoke it just on the quals, instead.
237 pull_up_subqueries(Query *parse, Node *jtnode)
241 if (IsA(jtnode, RangeTblRef))
243 int varno = ((RangeTblRef *) jtnode)->rtindex;
244 RangeTblEntry *rte = rt_fetch(varno, parse->rtable);
245 Query *subquery = rte->subquery;
248 * Is this a subquery RTE, and if so, is the subquery simple enough
249 * to pull up? (If not, do nothing at this node.)
251 if (subquery && is_simple_subquery(subquery))
258 * First, recursively pull up the subquery's subqueries,
259 * so that this routine's processing is complete for its
260 * jointree and rangetable.
262 subquery->jointree = (FromExpr *)
263 pull_up_subqueries(subquery, (Node *) subquery->jointree);
265 * Append the subquery's rangetable to mine (currently,
266 * no adjustments will be needed in the subquery's rtable).
268 rtoffset = length(parse->rtable);
269 parse->rtable = nconc(parse->rtable, subquery->rtable);
271 * Make copies of the subquery's jointree and targetlist
272 * with varnos adjusted to match the merged rangetable.
274 subjointree = copyObject(subquery->jointree);
275 OffsetVarNodes(subjointree, rtoffset, 0);
276 subtlist = copyObject(subquery->targetList);
277 OffsetVarNodes((Node *) subtlist, rtoffset, 0);
279 * Replace all of the top query's references to the subquery's
280 * outputs with copies of the adjusted subtlist items, being
281 * careful not to replace any of the jointree structure.
283 parse->targetList = (List *)
284 ResolveNew((Node *) parse->targetList,
285 varno, 0, subtlist, CMD_SELECT, 0);
286 resolvenew_in_jointree((Node *) parse->jointree, varno, subtlist);
288 ResolveNew(parse->havingQual,
289 varno, 0, subtlist, CMD_SELECT, 0);
291 * Miscellaneous housekeeping.
293 parse->hasSubLinks |= subquery->hasSubLinks;
295 * Return the adjusted subquery jointree to replace the
296 * RangeTblRef entry in my jointree.
301 else if (IsA(jtnode, FromExpr))
303 FromExpr *f = (FromExpr *) jtnode;
306 foreach(l, f->fromlist)
308 lfirst(l) = pull_up_subqueries(parse, lfirst(l));
311 else if (IsA(jtnode, JoinExpr))
313 JoinExpr *j = (JoinExpr *) jtnode;
315 j->larg = pull_up_subqueries(parse, j->larg);
316 j->rarg = pull_up_subqueries(parse, j->rarg);
319 elog(ERROR, "pull_up_subqueries: unexpected node type %d",
326 * Check a subquery in the range table to see if it's simple enough
327 * to pull up into the parent query.
330 is_simple_subquery(Query *subquery)
333 * Let's just make sure it's a valid subselect ...
335 if (!IsA(subquery, Query) ||
336 subquery->commandType != CMD_SELECT ||
337 subquery->resultRelation != 0 ||
338 subquery->into != NULL ||
340 elog(ERROR, "is_simple_subquery: subquery is bogus");
342 * Also check for currently-unsupported features.
344 if (subquery->rowMarks)
345 elog(ERROR, "FOR UPDATE is not supported in subselects");
347 * Can't currently pull up a query with setops.
348 * Maybe after querytree redesign...
350 if (subquery->setOperations)
353 * Can't pull up a subquery involving grouping, aggregation, sorting,
356 if (subquery->hasAggs ||
357 subquery->groupClause ||
358 subquery->havingQual ||
359 subquery->sortClause ||
360 subquery->distinctClause ||
361 subquery->limitOffset ||
362 subquery->limitCount)
365 * Hack: don't try to pull up a subquery with an empty jointree.
366 * query_planner() will correctly generate a Result plan for a
367 * jointree that's totally empty, but I don't think the right things
368 * happen if an empty FromExpr appears lower down in a jointree.
369 * Not worth working hard on this, just to collapse SubqueryScan/Result
372 if (subquery->jointree->fromlist == NIL)
379 * Helper routine for pull_up_subqueries: do ResolveNew on every expression
380 * in the jointree, without changing the jointree structure itself. Ugly,
381 * but there's no other way...
384 resolvenew_in_jointree(Node *jtnode, int varno, List *subtlist)
388 if (IsA(jtnode, RangeTblRef))
390 /* nothing to do here */
392 else if (IsA(jtnode, FromExpr))
394 FromExpr *f = (FromExpr *) jtnode;
397 foreach(l, f->fromlist)
398 resolvenew_in_jointree(lfirst(l), varno, subtlist);
399 f->quals = ResolveNew(f->quals,
400 varno, 0, subtlist, CMD_SELECT, 0);
402 else if (IsA(jtnode, JoinExpr))
404 JoinExpr *j = (JoinExpr *) jtnode;
406 resolvenew_in_jointree(j->larg, varno, subtlist);
407 resolvenew_in_jointree(j->rarg, varno, subtlist);
408 j->quals = ResolveNew(j->quals,
409 varno, 0, subtlist, CMD_SELECT, 0);
410 /* We don't bother to update the colvars list, since it won't be
415 elog(ERROR, "resolvenew_in_jointree: unexpected node type %d",
420 * preprocess_jointree
421 * Attempt to simplify a query's jointree.
423 * If we succeed in pulling up a subquery then we might form a jointree
424 * in which a FromExpr is a direct child of another FromExpr. In that
425 * case we can consider collapsing the two FromExprs into one. This is
426 * an optional conversion, since the planner will work correctly either
427 * way. But we may find a better plan (at the cost of more planning time)
428 * if we merge the two nodes.
430 * NOTE: don't try to do this in the same jointree scan that does subquery
431 * pullup! Since we're changing the jointree structure here, that wouldn't
432 * work reliably --- see comments for pull_up_subqueries().
435 preprocess_jointree(Query *parse, Node *jtnode)
439 if (IsA(jtnode, RangeTblRef))
441 /* nothing to do here... */
443 else if (IsA(jtnode, FromExpr))
445 FromExpr *f = (FromExpr *) jtnode;
449 foreach(l, f->fromlist)
451 Node *child = (Node *) lfirst(l);
453 /* Recursively simplify the child... */
454 child = preprocess_jointree(parse, child);
455 /* Now, is it a FromExpr? */
456 if (child && IsA(child, FromExpr))
459 * Yes, so do we want to merge it into parent? Always do so
460 * if child has just one element (since that doesn't make the
461 * parent's list any longer). Otherwise we have to be careful
462 * about the increase in planning time caused by combining the
463 * two join search spaces into one. Our heuristic is to merge
464 * if the merge will produce a join list no longer than
465 * GEQO_RELS/2. (Perhaps need an additional user parameter?)
467 FromExpr *subf = (FromExpr *) child;
468 int childlen = length(subf->fromlist);
469 int myothers = length(newlist) + length(lnext(l));
471 if (childlen <= 1 || (childlen+myothers) <= geqo_rels/2)
473 newlist = nconc(newlist, subf->fromlist);
474 f->quals = make_and_qual(f->quals, subf->quals);
477 newlist = lappend(newlist, child);
480 newlist = lappend(newlist, child);
482 f->fromlist = newlist;
484 else if (IsA(jtnode, JoinExpr))
486 JoinExpr *j = (JoinExpr *) jtnode;
488 /* Can't usefully change the JoinExpr, but recurse on children */
489 j->larg = preprocess_jointree(parse, j->larg);
490 j->rarg = preprocess_jointree(parse, j->rarg);
493 elog(ERROR, "preprocess_jointree: unexpected node type %d",
499 * preprocess_expression
500 * Do subquery_planner's preprocessing work for an expression,
501 * which can be a targetlist, a WHERE clause (including JOIN/ON
502 * conditions), or a HAVING clause.
505 preprocess_expression(Query *parse, Node *expr, int kind)
508 * Simplify constant expressions.
510 * Note that at this point quals have not yet been converted to
511 * implicit-AND form, so we can apply eval_const_expressions directly.
512 * Also note that we need to do this before SS_process_sublinks,
513 * because that routine inserts bogus "Const" nodes.
515 expr = eval_const_expressions(expr);
518 * If it's a qual or havingQual, canonicalize it, and convert it
519 * to implicit-AND format.
521 * XXX Is there any value in re-applying eval_const_expressions after
524 if (kind != EXPRKIND_TARGET)
526 expr = (Node *) canonicalize_qual((Expr *) expr, true);
528 #ifdef OPTIMIZER_DEBUG
529 printf("After canonicalize_qual()\n");
534 if (parse->hasSubLinks)
536 /* Expand SubLinks to SubPlans */
537 expr = SS_process_sublinks(expr);
539 if (kind != EXPRKIND_WHERE &&
540 (parse->groupClause != NIL || parse->hasAggs))
543 * Check for ungrouped variables passed to subplans. Note we
544 * do NOT do this for subplans in WHERE (or JOIN/ON); it's legal
545 * there because WHERE is evaluated pre-GROUP.
547 * An interesting fine point: if subquery_planner reassigned a
548 * HAVING qual into WHERE, then we will accept references to
549 * ungrouped vars from subplans in the HAVING qual. This is not
550 * entirely consistent, but it doesn't seem particularly
553 check_subplans_for_ungrouped_vars(expr, parse);
557 /* Replace uplevel vars with Param nodes */
558 if (PlannerQueryLevel > 1)
559 expr = SS_replace_correlation_vars(expr);
565 * preprocess_qual_conditions
566 * Recursively scan the query's jointree and do subquery_planner's
567 * preprocessing work on each qual condition found therein.
570 preprocess_qual_conditions(Query *parse, Node *jtnode)
574 if (IsA(jtnode, RangeTblRef))
576 /* nothing to do here */
578 else if (IsA(jtnode, FromExpr))
580 FromExpr *f = (FromExpr *) jtnode;
583 foreach(l, f->fromlist)
584 preprocess_qual_conditions(parse, lfirst(l));
586 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_WHERE);
588 else if (IsA(jtnode, JoinExpr))
590 JoinExpr *j = (JoinExpr *) jtnode;
592 preprocess_qual_conditions(parse, j->larg);
593 preprocess_qual_conditions(parse, j->rarg);
595 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_WHERE);
598 elog(ERROR, "preprocess_qual_conditions: unexpected node type %d",
602 /*--------------------
604 * Invokes the planner on union-type queries (both set operations and
605 * appends produced by inheritance), recursing if necessary to get them
606 * all, then processes normal plans.
608 * parse is the querytree produced by the parser & rewriter.
609 * tuple_fraction is the fraction of tuples we expect will be retrieved
611 * tuple_fraction is interpreted as follows:
612 * < 0: determine fraction by inspection of query (normal case)
613 * 0: expect all tuples to be retrieved
614 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
615 * from the plan to be retrieved
616 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
617 * expected to be retrieved (ie, a LIMIT specification)
618 * The normal case is to pass -1, but some callers pass values >= 0 to
619 * override this routine's determination of the appropriate fraction.
621 * Returns a query plan.
622 *--------------------
625 union_planner(Query *parse,
626 double tuple_fraction)
628 List *tlist = parse->targetList;
629 Plan *result_plan = (Plan *) NULL;
630 AttrNumber *groupColIdx = NULL;
631 List *current_pathkeys = NIL;
632 List *group_pathkeys;
637 if (parse->setOperations)
640 * Construct the plan for set operations. The result will not
641 * need any work except perhaps a top-level sort and/or LIMIT.
643 result_plan = plan_set_operations(parse);
646 * We should not need to call preprocess_targetlist, since we must
647 * be in a SELECT query node. Instead, use the targetlist
648 * returned by plan_set_operations (since this tells whether it
649 * returned any resjunk columns!), and transfer any sort key
650 * information from the original tlist.
652 Assert(parse->commandType == CMD_SELECT);
654 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
657 * We leave current_pathkeys NIL indicating we do not know sort
658 * order. This is correct when the top set operation is UNION ALL,
659 * since the appended-together results are unsorted even if the
660 * subplans were sorted. For other set operations we could be
661 * smarter --- future improvement!
665 * Calculate pathkeys that represent grouping/ordering
666 * requirements (grouping should always be null, but...)
668 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
670 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
673 else if (find_inheritable_rt_entry(parse->rtable,
674 &rt_index, &inheritors))
679 * Generate appropriate target list for subplan; may be different
680 * from tlist if grouping or aggregation is needed.
682 sub_tlist = make_subplanTargetList(parse, tlist, &groupColIdx);
685 * Recursively plan the subqueries needed for inheritance
687 result_plan = plan_inherit_queries(parse, sub_tlist,
688 rt_index, inheritors);
691 * Fix up outer target list. NOTE: unlike the case for
692 * non-inherited query, we pass the unfixed tlist to subplans,
693 * which do their own fixing. But we still want to fix the outer
694 * target list afterwards. I *think* this is correct --- doing the
695 * fix before recursing is definitely wrong, because
696 * preprocess_targetlist() will do the wrong thing if invoked
697 * twice on the same list. Maybe that is a bug? tgl 6/6/99
699 tlist = preprocess_targetlist(tlist,
701 parse->resultRelation,
705 elog(ERROR, "SELECT FOR UPDATE is not supported for inherit queries");
708 * We leave current_pathkeys NIL indicating we do not know sort
709 * order of the Append-ed results.
713 * Calculate pathkeys that represent grouping/ordering
716 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
718 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
725 /* Preprocess targetlist in case we are inside an INSERT/UPDATE. */
726 tlist = preprocess_targetlist(tlist,
728 parse->resultRelation,
732 * Add TID targets for rels selected FOR UPDATE (should this be
733 * done in preprocess_targetlist?). The executor uses the TID
734 * to know which rows to lock, much as for UPDATE or DELETE.
740 foreach(l, parse->rowMarks)
742 Index rti = lfirsti(l);
748 resname = (char *) palloc(32);
749 sprintf(resname, "ctid%u", rti);
750 resdom = makeResdom(length(tlist) + 1,
757 SelfItemPointerAttributeNumber,
762 ctid = makeTargetEntry(resdom, (Node *) var);
763 tlist = lappend(tlist, ctid);
768 * Generate appropriate target list for subplan; may be different
769 * from tlist if grouping or aggregation is needed.
771 sub_tlist = make_subplanTargetList(parse, tlist, &groupColIdx);
774 * Calculate pathkeys that represent grouping/ordering
777 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
779 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
783 * Figure out whether we need a sorted result from query_planner.
785 * If we have a GROUP BY clause, then we want a result sorted
786 * properly for grouping. Otherwise, if there is an ORDER BY
787 * clause, we want to sort by the ORDER BY clause. (Note: if we
788 * have both, and ORDER BY is a superset of GROUP BY, it would be
789 * tempting to request sort by ORDER BY --- but that might just
790 * leave us failing to exploit an available sort order at all.
791 * Needs more thought...)
793 if (parse->groupClause)
794 parse->query_pathkeys = group_pathkeys;
795 else if (parse->sortClause)
796 parse->query_pathkeys = sort_pathkeys;
798 parse->query_pathkeys = NIL;
801 * Figure out whether we expect to retrieve all the tuples that
802 * the plan can generate, or to stop early due to a LIMIT or other
803 * factors. If the caller passed a value >= 0, believe that
804 * value, else do our own examination of the query context.
806 if (tuple_fraction < 0.0)
808 /* Initial assumption is we need all the tuples */
809 tuple_fraction = 0.0;
812 * Check for a LIMIT clause.
814 if (parse->limitCount != NULL)
816 if (IsA(parse->limitCount, Const))
818 Const *limitc = (Const *) parse->limitCount;
819 int32 count = DatumGetInt32(limitc->constvalue);
822 * A NULL-constant LIMIT represents "LIMIT ALL",
823 * which we treat the same as no limit (ie,
824 * expect to retrieve all the tuples).
826 if (!limitc->constisnull && count > 0)
828 tuple_fraction = (double) count;
829 /* We must also consider the OFFSET, if present */
830 if (parse->limitOffset != NULL)
832 if (IsA(parse->limitOffset, Const))
836 limitc = (Const *) parse->limitOffset;
837 offset = DatumGetInt32(limitc->constvalue);
838 if (!limitc->constisnull && offset > 0)
839 tuple_fraction += (double) offset;
843 /* It's an expression ... punt ... */
844 tuple_fraction = 0.10;
852 * COUNT is an expression ... don't know exactly what the
853 * limit will be, but for lack of a better idea assume
854 * 10% of the plan's result is wanted.
856 tuple_fraction = 0.10;
861 * If no LIMIT, check for retrieve-into-portal, ie DECLARE CURSOR.
863 * We have no real idea how many tuples the user will ultimately
864 * FETCH from a cursor, but it seems a good bet that he
865 * doesn't want 'em all. Optimize for 10% retrieval (you
866 * gotta better number?)
868 else if (parse->isPortal)
869 tuple_fraction = 0.10;
873 * Adjust tuple_fraction if we see that we are going to apply
874 * grouping/aggregation/etc. This is not overridable by the
875 * caller, since it reflects plan actions that this routine will
876 * certainly take, not assumptions about context.
878 if (parse->groupClause)
882 * In GROUP BY mode, we have the little problem that we don't
883 * really know how many input tuples will be needed to make a
884 * group, so we can't translate an output LIMIT count into an
885 * input count. For lack of a better idea, assume 25% of the
886 * input data will be processed if there is any output limit.
887 * However, if the caller gave us a fraction rather than an
888 * absolute count, we can keep using that fraction (which
889 * amounts to assuming that all the groups are about the same
892 if (tuple_fraction >= 1.0)
893 tuple_fraction = 0.25;
896 * If both GROUP BY and ORDER BY are specified, we will need
897 * two levels of sort --- and, therefore, certainly need to
898 * read all the input tuples --- unless ORDER BY is a subset
899 * of GROUP BY. (Although we are comparing non-canonicalized
900 * pathkeys here, it should be OK since they will both contain
901 * only single-element sublists at this point. See
904 if (parse->groupClause && parse->sortClause &&
905 !pathkeys_contained_in(sort_pathkeys, group_pathkeys))
906 tuple_fraction = 0.0;
908 else if (parse->hasAggs)
912 * Ungrouped aggregate will certainly want all the input
915 tuple_fraction = 0.0;
917 else if (parse->distinctClause)
921 * SELECT DISTINCT, like GROUP, will absorb an unpredictable
922 * number of input tuples per output tuple. Handle the same
925 if (tuple_fraction >= 1.0)
926 tuple_fraction = 0.25;
929 /* Generate the basic plan for this Query */
930 result_plan = query_planner(parse,
935 * query_planner returns actual sort order (which is not
936 * necessarily what we requested) in query_pathkeys.
938 current_pathkeys = parse->query_pathkeys;
941 /* query_planner returns NULL if it thinks plan is bogus */
943 elog(ERROR, "union_planner: failed to create plan");
946 * We couldn't canonicalize group_pathkeys and sort_pathkeys before
947 * running query_planner(), so do it now.
949 group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
950 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
953 * If we have a GROUP BY clause, insert a group node (plus the
954 * appropriate sort node, if necessary).
956 if (parse->groupClause)
963 * Decide whether how many tuples per group the Group node needs
964 * to return. (Needs only one tuple per group if no aggregate is
965 * present. Otherwise, need every tuple from the group to do the
966 * aggregation.) Note tuplePerGroup is named backwards :-(
968 tuplePerGroup = parse->hasAggs;
971 * If there are aggregates then the Group node should just return
972 * the same set of vars as the subplan did (but we can exclude any
973 * GROUP BY expressions). If there are no aggregates then the
974 * Group node had better compute the final tlist.
977 group_tlist = flatten_tlist(result_plan->targetlist);
982 * Figure out whether the path result is already ordered the way
983 * we need it --- if so, no need for an explicit sort step.
985 if (pathkeys_contained_in(group_pathkeys, current_pathkeys))
987 is_sorted = true; /* no sort needed now */
988 /* current_pathkeys remains unchanged */
994 * We will need to do an explicit sort by the GROUP BY clause.
995 * make_groupplan will do the work, but set current_pathkeys
996 * to indicate the resulting order.
999 current_pathkeys = group_pathkeys;
1002 result_plan = make_groupplan(group_tlist,
1011 * If aggregate is present, insert the Agg node
1013 * HAVING clause, if any, becomes qual of the Agg node
1017 result_plan = (Plan *) make_agg(tlist,
1018 (List *) parse->havingQual,
1020 /* Note: Agg does not affect any existing sort order of the tuples */
1024 * If we were not able to make the plan come out in the right order,
1025 * add an explicit sort step.
1027 if (parse->sortClause)
1029 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1030 result_plan = make_sortplan(tlist, result_plan,
1035 * If there is a DISTINCT clause, add the UNIQUE node.
1037 if (parse->distinctClause)
1039 result_plan = (Plan *) make_unique(tlist, result_plan,
1040 parse->distinctClause);
1044 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1046 if (parse->limitOffset || parse->limitCount)
1048 result_plan = (Plan *) make_limit(tlist, result_plan,
1057 * make_subplanTargetList
1058 * Generate appropriate target list when grouping is required.
1060 * When union_planner inserts Aggregate and/or Group plan nodes above
1061 * the result of query_planner, we typically want to pass a different
1062 * target list to query_planner than the outer plan nodes should have.
1063 * This routine generates the correct target list for the subplan.
1065 * The initial target list passed from the parser already contains entries
1066 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1067 * for variables used only in HAVING clauses; so we need to add those
1068 * variables to the subplan target list. Also, if we are doing either
1069 * grouping or aggregation, we flatten all expressions except GROUP BY items
1070 * into their component variables; the other expressions will be computed by
1071 * the inserted nodes rather than by the subplan. For example,
1072 * given a query like
1073 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1074 * we want to pass this targetlist to the subplan:
1076 * where the a+b target will be used by the Sort/Group steps, and the
1077 * other targets will be used for computing the final results. (In the
1078 * above example we could theoretically suppress the a and b targets and
1079 * use only a+b, but it's not really worth the trouble.)
1081 * 'parse' is the query being processed.
1082 * 'tlist' is the query's target list.
1083 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1084 * expressions (if there are any) in the subplan's target list.
1086 * The result is the targetlist to be passed to the subplan.
1090 make_subplanTargetList(Query *parse,
1092 AttrNumber **groupColIdx)
1098 *groupColIdx = NULL;
1101 * If we're not grouping or aggregating, nothing to do here;
1102 * query_planner should receive the unmodified target list.
1104 if (!parse->hasAggs && !parse->groupClause && !parse->havingQual)
1108 * Otherwise, start with a "flattened" tlist (having just the vars
1109 * mentioned in the targetlist and HAVING qual --- but not upper-
1110 * level Vars; they will be replaced by Params later on).
1112 sub_tlist = flatten_tlist(tlist);
1113 extravars = pull_var_clause(parse->havingQual, false);
1114 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1115 freeList(extravars);
1118 * If grouping, create sub_tlist entries for all GROUP BY expressions
1119 * (GROUP BY items that are simple Vars should be in the list
1120 * already), and make an array showing where the group columns are in
1123 numCols = length(parse->groupClause);
1127 AttrNumber *grpColIdx;
1130 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1131 *groupColIdx = grpColIdx;
1133 foreach(gl, parse->groupClause)
1135 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1136 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1137 TargetEntry *te = NULL;
1140 /* Find or make a matching sub_tlist entry */
1141 foreach(sl, sub_tlist)
1143 te = (TargetEntry *) lfirst(sl);
1144 if (equal(groupexpr, te->expr))
1149 te = makeTargetEntry(makeResdom(length(sub_tlist) + 1,
1150 exprType(groupexpr),
1151 exprTypmod(groupexpr),
1155 sub_tlist = lappend(sub_tlist, te);
1158 /* and save its resno */
1159 grpColIdx[keyno++] = te->resdom->resno;
1168 * Add a Group node for GROUP BY processing.
1169 * If we couldn't make the subplan produce presorted output for grouping,
1170 * first add an explicit Sort node.
1173 make_groupplan(List *group_tlist,
1176 AttrNumber *grpColIdx,
1180 int numCols = length(groupClause);
1186 * The Sort node always just takes a copy of the subplan's tlist
1187 * plus ordering information. (This might seem inefficient if the
1188 * subplan contains complex GROUP BY expressions, but in fact Sort
1189 * does not evaluate its targetlist --- it only outputs the same
1190 * tuples in a new order. So the expressions we might be copying
1191 * are just dummies with no extra execution cost.)
1193 List *sort_tlist = new_unsorted_tlist(subplan->targetlist);
1197 foreach(gl, groupClause)
1199 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1200 TargetEntry *te = nth(grpColIdx[keyno] - 1, sort_tlist);
1201 Resdom *resdom = te->resdom;
1204 * Check for the possibility of duplicate group-by clauses ---
1205 * the parser should have removed 'em, but the Sort executor
1206 * will get terribly confused if any get through!
1208 if (resdom->reskey == 0)
1210 /* OK, insert the ordering info needed by the executor. */
1211 resdom->reskey = ++keyno;
1212 resdom->reskeyop = get_opcode(grpcl->sortop);
1218 subplan = (Plan *) make_sort(sort_tlist, subplan, keyno);
1221 return (Plan *) make_group(group_tlist, tuplePerGroup, numCols,
1222 grpColIdx, subplan);
1227 * Add a Sort node to implement an explicit ORDER BY clause.
1230 make_sortplan(List *tlist, Plan *plannode, List *sortcls)
1237 * First make a copy of the tlist so that we don't corrupt the
1240 sort_tlist = new_unsorted_tlist(tlist);
1244 SortClause *sortcl = (SortClause *) lfirst(i);
1245 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sort_tlist);
1246 Resdom *resdom = tle->resdom;
1249 * Check for the possibility of duplicate order-by clauses --- the
1250 * parser should have removed 'em, but the executor will get
1251 * terribly confused if any get through!
1253 if (resdom->reskey == 0)
1255 /* OK, insert the ordering info needed by the executor. */
1256 resdom->reskey = ++keyno;
1257 resdom->reskeyop = get_opcode(sortcl->sortop);
1263 return (Plan *) make_sort(sort_tlist, plannode, keyno);
1267 * postprocess_setop_tlist
1268 * Fix up targetlist returned by plan_set_operations().
1270 * We need to transpose sort key info from the orig_tlist into new_tlist.
1271 * NOTE: this would not be good enough if we supported resjunk sort keys
1272 * for results of set operations --- then, we'd need to project a whole
1273 * new tlist to evaluate the resjunk columns. For now, just elog if we
1274 * find any resjunk columns in orig_tlist.
1277 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1281 foreach(l, new_tlist)
1283 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1284 TargetEntry *orig_tle;
1286 /* ignore resjunk columns in setop result */
1287 if (new_tle->resdom->resjunk)
1290 Assert(orig_tlist != NIL);
1291 orig_tle = (TargetEntry *) lfirst(orig_tlist);
1292 orig_tlist = lnext(orig_tlist);
1293 if (orig_tle->resdom->resjunk)
1294 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");
1295 Assert(new_tle->resdom->resno == orig_tle->resdom->resno);
1296 Assert(new_tle->resdom->restype == orig_tle->resdom->restype);
1297 new_tle->resdom->ressortgroupref = orig_tle->resdom->ressortgroupref;
1299 if (orig_tlist != NIL)
1300 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");