1 /*-------------------------------------------------------------------------
4 * The query optimizer external interface.
6 * Portions Copyright (c) 1996-2002, 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.138 2003/01/13 18:10:53 tgl Exp $
13 *-------------------------------------------------------------------------
20 #include "catalog/pg_operator.h"
21 #include "catalog/pg_type.h"
22 #include "miscadmin.h"
23 #include "nodes/makefuncs.h"
24 #ifdef OPTIMIZER_DEBUG
25 #include "nodes/print.h"
27 #include "optimizer/clauses.h"
28 #include "optimizer/cost.h"
29 #include "optimizer/pathnode.h"
30 #include "optimizer/paths.h"
31 #include "optimizer/planmain.h"
32 #include "optimizer/planner.h"
33 #include "optimizer/prep.h"
34 #include "optimizer/subselect.h"
35 #include "optimizer/tlist.h"
36 #include "optimizer/var.h"
37 #include "parser/analyze.h"
38 #include "parser/parsetree.h"
39 #include "parser/parse_expr.h"
40 #include "parser/parse_oper.h"
41 #include "rewrite/rewriteManip.h"
42 #include "utils/lsyscache.h"
43 #include "utils/selfuncs.h"
44 #include "utils/syscache.h"
47 /* Expression kind codes for preprocess_expression */
48 #define EXPRKIND_TARGET 0
49 #define EXPRKIND_WHERE 1
50 #define EXPRKIND_HAVING 2
53 static Node *pull_up_subqueries(Query *parse, Node *jtnode,
54 bool below_outer_join);
55 static bool is_simple_subquery(Query *subquery);
56 static bool has_nullable_targetlist(Query *subquery);
57 static void resolvenew_in_jointree(Node *jtnode, int varno, List *subtlist);
58 static Node *preprocess_jointree(Query *parse, Node *jtnode);
59 static Node *preprocess_expression(Query *parse, Node *expr, int kind);
60 static void preprocess_qual_conditions(Query *parse, Node *jtnode);
61 static Plan *inheritance_planner(Query *parse, List *inheritlist);
62 static Plan *grouping_planner(Query *parse, double tuple_fraction);
63 static bool hash_safe_grouping(Query *parse);
64 static List *make_subplanTargetList(Query *parse, List *tlist,
65 AttrNumber **groupColIdx);
66 static Plan *make_groupsortplan(Query *parse,
68 AttrNumber *grpColIdx,
70 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
73 /*****************************************************************************
75 * Query optimizer entry point
77 *****************************************************************************/
82 Index save_PlannerQueryLevel;
83 List *save_PlannerParamVar;
86 * The planner can be called recursively (an example is when
87 * eval_const_expressions tries to pre-evaluate an SQL function). So,
88 * these global state variables must be saved and restored.
90 * These vars cannot be moved into the Query structure since their whole
91 * purpose is communication across multiple sub-Queries.
93 * Note we do NOT save and restore PlannerPlanId: it exists to assign
94 * unique IDs to SubPlan nodes, and we want those IDs to be unique for
95 * the life of a backend. Also, PlannerInitPlan is saved/restored in
96 * subquery_planner, not here.
98 save_PlannerQueryLevel = PlannerQueryLevel;
99 save_PlannerParamVar = PlannerParamVar;
101 /* Initialize state for handling outer-level references and params */
102 PlannerQueryLevel = 0; /* will be 1 in top-level subquery_planner */
103 PlannerParamVar = NIL;
105 /* primary planning entry point (may recurse for subqueries) */
106 result_plan = subquery_planner(parse, -1.0 /* default case */ );
108 Assert(PlannerQueryLevel == 0);
110 /* executor wants to know total number of Params used overall */
111 result_plan->nParamExec = length(PlannerParamVar);
113 /* final cleanup of the plan */
114 set_plan_references(result_plan, parse->rtable);
116 /* restore state for outer planner, if any */
117 PlannerQueryLevel = save_PlannerQueryLevel;
118 PlannerParamVar = save_PlannerParamVar;
124 /*--------------------
126 * Invokes the planner on a subquery. We recurse to here for each
127 * sub-SELECT found in the query tree.
129 * parse is the querytree produced by the parser & rewriter.
130 * tuple_fraction is the fraction of tuples we expect will be retrieved.
131 * tuple_fraction is interpreted as explained for grouping_planner, below.
133 * Basically, this routine does the stuff that should only be done once
134 * per Query object. It then calls grouping_planner. At one time,
135 * grouping_planner could be invoked recursively on the same Query object;
136 * that's not currently true, but we keep the separation between the two
137 * routines anyway, in case we need it again someday.
139 * subquery_planner will be called recursively to handle sub-Query nodes
140 * found within the query's expressions and rangetable.
142 * Returns a query plan.
143 *--------------------
146 subquery_planner(Query *parse, double tuple_fraction)
148 List *saved_initplan = PlannerInitPlan;
149 int saved_planid = PlannerPlanId;
154 /* Set up for a new level of subquery */
156 PlannerInitPlan = NIL;
159 * Check to see if any subqueries in the rangetable can be merged into
162 parse->jointree = (FromExpr *)
163 pull_up_subqueries(parse, (Node *) parse->jointree, false);
166 * If so, we may have created opportunities to simplify the jointree.
168 parse->jointree = (FromExpr *)
169 preprocess_jointree(parse, (Node *) parse->jointree);
172 * Detect whether any rangetable entries are RTE_JOIN kind; if not,
173 * we can avoid the expense of doing flatten_join_alias_vars().
174 * This must be done after we have done pull_up_subqueries, of course.
176 parse->hasJoinRTEs = false;
177 foreach(lst, parse->rtable)
179 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lst);
181 if (rte->rtekind == RTE_JOIN)
183 parse->hasJoinRTEs = true;
189 * Do expression preprocessing on targetlist and quals.
191 parse->targetList = (List *)
192 preprocess_expression(parse, (Node *) parse->targetList,
195 preprocess_qual_conditions(parse, (Node *) parse->jointree);
197 parse->havingQual = preprocess_expression(parse, parse->havingQual,
200 /* Also need to preprocess expressions for function RTEs */
201 foreach(lst, parse->rtable)
203 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lst);
205 if (rte->rtekind == RTE_FUNCTION)
206 rte->funcexpr = preprocess_expression(parse, rte->funcexpr,
208 /* These are not targetlist items, but close enough... */
212 * Check for ungrouped variables passed to subplans in targetlist and
213 * HAVING clause (but not in WHERE or JOIN/ON clauses, since those are
214 * evaluated before grouping). We can't do this any earlier because
215 * we must use the preprocessed targetlist for comparisons of grouped
218 if (parse->hasSubLinks &&
219 (parse->groupClause != NIL || parse->hasAggs))
220 check_subplans_for_ungrouped_vars(parse);
223 * A HAVING clause without aggregates is equivalent to a WHERE clause
224 * (except it can only refer to grouped fields). Transfer any
225 * agg-free clauses of the HAVING qual into WHERE. This may seem like
226 * wasting cycles to cater to stupidly-written queries, but there are
227 * other reasons for doing it. Firstly, if the query contains no aggs
228 * at all, then we aren't going to generate an Agg plan node, and so
229 * there'll be no place to execute HAVING conditions; without this
230 * transfer, we'd lose the HAVING condition entirely, which is wrong.
231 * Secondly, when we push down a qual condition into a sub-query, it's
232 * easiest to push the qual into HAVING always, in case it contains
233 * aggs, and then let this code sort it out.
235 * Note that both havingQual and parse->jointree->quals are in
236 * implicitly-ANDed-list form at this point, even though they are
237 * declared as Node *. Also note that contain_agg_clause does not
238 * recurse into sub-selects, which is exactly what we need here.
241 foreach(lst, (List *) parse->havingQual)
243 Node *havingclause = (Node *) lfirst(lst);
245 if (contain_agg_clause(havingclause))
246 newHaving = lappend(newHaving, havingclause);
248 parse->jointree->quals = (Node *)
249 lappend((List *) parse->jointree->quals, havingclause);
251 parse->havingQual = (Node *) newHaving;
254 * Do the main planning. If we have an inherited target relation,
255 * that needs special processing, else go straight to
258 if (parse->resultRelation &&
259 (lst = expand_inherted_rtentry(parse, parse->resultRelation, false))
261 plan = inheritance_planner(parse, lst);
263 plan = grouping_planner(parse, tuple_fraction);
266 * If any subplans were generated, or if we're inside a subplan, build
267 * initPlan, extParam and locParam lists for plan nodes.
269 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
271 Cost initplan_cost = 0;
273 /* Prepare extParam/locParam data for all nodes in tree */
274 (void) SS_finalize_plan(plan, parse->rtable);
277 * SS_finalize_plan doesn't handle initPlans, so we have to manually
278 * attach them to the topmost plan node, and add their extParams to
279 * the topmost node's, too.
281 * We also add the total_cost of each initPlan to the startup cost
282 * of the top node. This is a conservative overestimate, since in
283 * fact each initPlan might be executed later than plan startup, or
286 plan->initPlan = PlannerInitPlan;
288 foreach(lst, plan->initPlan)
290 SubPlan *initplan = (SubPlan *) lfirst(lst);
292 plan->extParam = set_unioni(plan->extParam,
293 initplan->plan->extParam);
294 initplan_cost += initplan->plan->total_cost;
297 plan->startup_cost += initplan_cost;
298 plan->total_cost += initplan_cost;
301 /* Return to outer subquery context */
303 PlannerInitPlan = saved_initplan;
304 /* we do NOT restore PlannerPlanId; that's not an oversight! */
311 * Look for subqueries in the rangetable that can be pulled up into
312 * the parent query. If the subquery has no special features like
313 * grouping/aggregation then we can merge it into the parent's jointree.
315 * below_outer_join is true if this jointree node is within the nullable
316 * side of an outer join. This restricts what we can do.
318 * A tricky aspect of this code is that if we pull up a subquery we have
319 * to replace Vars that reference the subquery's outputs throughout the
320 * parent query, including quals attached to jointree nodes above the one
321 * we are currently processing! We handle this by being careful not to
322 * change the jointree structure while recursing: no nodes other than
323 * subquery RangeTblRef entries will be replaced. Also, we can't turn
324 * ResolveNew loose on the whole jointree, because it'll return a mutated
325 * copy of the tree; we have to invoke it just on the quals, instead.
328 pull_up_subqueries(Query *parse, Node *jtnode, bool below_outer_join)
332 if (IsA(jtnode, RangeTblRef))
334 int varno = ((RangeTblRef *) jtnode)->rtindex;
335 RangeTblEntry *rte = rt_fetch(varno, parse->rtable);
336 Query *subquery = rte->subquery;
339 * Is this a subquery RTE, and if so, is the subquery simple
340 * enough to pull up? (If not, do nothing at this node.)
342 * If we are inside an outer join, only pull up subqueries whose
343 * targetlists are nullable --- otherwise substituting their tlist
344 * entries for upper Var references would do the wrong thing (the
345 * results wouldn't become NULL when they're supposed to). XXX
346 * This could be improved by generating pseudo-variables for such
347 * expressions; we'd have to figure out how to get the pseudo-
348 * variables evaluated at the right place in the modified plan
349 * tree. Fix it someday.
351 * Note: even if the subquery itself is simple enough, we can't pull
352 * it up if there is a reference to its whole tuple result.
353 * Perhaps a pseudo-variable is the answer here too.
355 if (rte->rtekind == RTE_SUBQUERY && is_simple_subquery(subquery) &&
356 (!below_outer_join || has_nullable_targetlist(subquery)) &&
357 !contain_whole_tuple_var((Node *) parse, varno, 0))
364 * First, recursively pull up the subquery's subqueries, so
365 * that this routine's processing is complete for its jointree
366 * and rangetable. NB: if the same subquery is referenced
367 * from multiple jointree items (which can't happen normally,
368 * but might after rule rewriting), then we will invoke this
369 * processing multiple times on that subquery. OK because
370 * nothing will happen after the first time. We do have to be
371 * careful to copy everything we pull up, however, or risk
372 * having chunks of structure multiply linked.
374 * Note: 'false' is correct here even if we are within an outer
375 * join in the upper query; the lower query starts with a clean
376 * slate for outer-join semantics.
378 subquery->jointree = (FromExpr *)
379 pull_up_subqueries(subquery, (Node *) subquery->jointree,
383 * Now make a modifiable copy of the subquery that we can run
384 * OffsetVarNodes and IncrementVarSublevelsUp on.
386 subquery = copyObject(subquery);
389 * Adjust level-0 varnos in subquery so that we can append its
390 * rangetable to upper query's.
392 rtoffset = length(parse->rtable);
393 OffsetVarNodes((Node *) subquery, rtoffset, 0);
396 * Upper-level vars in subquery are now one level closer to their
397 * parent than before.
399 IncrementVarSublevelsUp((Node *) subquery, -1, 1);
402 * Replace all of the top query's references to the subquery's
403 * outputs with copies of the adjusted subtlist items, being
404 * careful not to replace any of the jointree structure.
405 * (This'd be a lot cleaner if we could use
406 * query_tree_mutator.)
408 subtlist = subquery->targetList;
409 parse->targetList = (List *)
410 ResolveNew((Node *) parse->targetList,
411 varno, 0, subtlist, CMD_SELECT, 0);
412 resolvenew_in_jointree((Node *) parse->jointree, varno, subtlist);
413 Assert(parse->setOperations == NULL);
415 ResolveNew(parse->havingQual,
416 varno, 0, subtlist, CMD_SELECT, 0);
418 foreach(rt, parse->rtable)
420 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
422 if (rte->rtekind == RTE_JOIN)
423 rte->joinaliasvars = (List *)
424 ResolveNew((Node *) rte->joinaliasvars,
425 varno, 0, subtlist, CMD_SELECT, 0);
429 * Now append the adjusted rtable entries to upper query. (We
430 * hold off until after fixing the upper rtable entries; no
431 * point in running that code on the subquery ones too.)
433 parse->rtable = nconc(parse->rtable, subquery->rtable);
436 * Pull up any FOR UPDATE markers, too. (OffsetVarNodes
437 * already adjusted the marker values, so just nconc the
440 parse->rowMarks = nconc(parse->rowMarks, subquery->rowMarks);
443 * Miscellaneous housekeeping.
445 parse->hasSubLinks |= subquery->hasSubLinks;
446 /* subquery won't be pulled up if it hasAggs, so no work there */
449 * Return the adjusted subquery jointree to replace the
450 * RangeTblRef entry in my jointree.
452 return (Node *) subquery->jointree;
455 else if (IsA(jtnode, FromExpr))
457 FromExpr *f = (FromExpr *) jtnode;
460 foreach(l, f->fromlist)
461 lfirst(l) = pull_up_subqueries(parse, lfirst(l),
464 else if (IsA(jtnode, JoinExpr))
466 JoinExpr *j = (JoinExpr *) jtnode;
468 /* Recurse, being careful to tell myself when inside outer join */
472 j->larg = pull_up_subqueries(parse, j->larg,
474 j->rarg = pull_up_subqueries(parse, j->rarg,
478 j->larg = pull_up_subqueries(parse, j->larg,
480 j->rarg = pull_up_subqueries(parse, j->rarg,
484 j->larg = pull_up_subqueries(parse, j->larg,
486 j->rarg = pull_up_subqueries(parse, j->rarg,
490 j->larg = pull_up_subqueries(parse, j->larg,
492 j->rarg = pull_up_subqueries(parse, j->rarg,
498 * This is where we fail if upper levels of planner
499 * haven't rewritten UNION JOIN as an Append ...
501 elog(ERROR, "UNION JOIN is not implemented yet");
504 elog(ERROR, "pull_up_subqueries: unexpected join type %d",
510 elog(ERROR, "pull_up_subqueries: unexpected node type %d",
517 * Check a subquery in the range table to see if it's simple enough
518 * to pull up into the parent query.
521 is_simple_subquery(Query *subquery)
524 * Let's just make sure it's a valid subselect ...
526 if (!IsA(subquery, Query) ||
527 subquery->commandType != CMD_SELECT ||
528 subquery->resultRelation != 0 ||
529 subquery->into != NULL ||
531 elog(ERROR, "is_simple_subquery: subquery is bogus");
534 * Can't currently pull up a query with setops. Maybe after querytree
537 if (subquery->setOperations)
541 * Can't pull up a subquery involving grouping, aggregation, sorting,
544 if (subquery->hasAggs ||
545 subquery->groupClause ||
546 subquery->havingQual ||
547 subquery->sortClause ||
548 subquery->distinctClause ||
549 subquery->limitOffset ||
550 subquery->limitCount)
554 * Don't pull up a subquery that has any set-returning functions in
555 * its targetlist. Otherwise we might well wind up inserting
556 * set-returning functions into places where they mustn't go, such as
557 * quals of higher queries.
559 if (expression_returns_set((Node *) subquery->targetList))
563 * Don't pull up a subquery that has any sublinks in its targetlist,
564 * either. As of PG 7.3 this creates problems because the pulled-up
565 * expressions may go into join alias lists, and the sublinks would
566 * not get fixed because we do flatten_join_alias_vars() too late.
567 * Eventually we should do a complete flatten_join_alias_vars as the
568 * first step of preprocess_expression, and then we could probably
569 * support this. (BUT: it might be a bad idea anyway, due to possibly
570 * causing multiple evaluations of an expensive sublink.)
572 if (subquery->hasSubLinks &&
573 contain_subplans((Node *) subquery->targetList))
577 * Hack: don't try to pull up a subquery with an empty jointree.
578 * query_planner() will correctly generate a Result plan for a
579 * jointree that's totally empty, but I don't think the right things
580 * happen if an empty FromExpr appears lower down in a jointree. Not
581 * worth working hard on this, just to collapse SubqueryScan/Result
584 if (subquery->jointree->fromlist == NIL)
591 * has_nullable_targetlist
592 * Check a subquery in the range table to see if all the non-junk
593 * targetlist items are simple variables (and, hence, will correctly
594 * go to NULL when examined above the point of an outer join).
596 * A possible future extension is to accept strict functions of simple
597 * variables, eg, "x + 1".
600 has_nullable_targetlist(Query *subquery)
604 foreach(l, subquery->targetList)
606 TargetEntry *tle = (TargetEntry *) lfirst(l);
608 /* ignore resjunk columns */
609 if (tle->resdom->resjunk)
612 /* Okay if tlist item is a simple Var */
613 if (tle->expr && IsA(tle->expr, Var))
622 * Helper routine for pull_up_subqueries: do ResolveNew on every expression
623 * in the jointree, without changing the jointree structure itself. Ugly,
624 * but there's no other way...
627 resolvenew_in_jointree(Node *jtnode, int varno, List *subtlist)
631 if (IsA(jtnode, RangeTblRef))
633 /* nothing to do here */
635 else if (IsA(jtnode, FromExpr))
637 FromExpr *f = (FromExpr *) jtnode;
640 foreach(l, f->fromlist)
641 resolvenew_in_jointree(lfirst(l), varno, subtlist);
642 f->quals = ResolveNew(f->quals,
643 varno, 0, subtlist, CMD_SELECT, 0);
645 else if (IsA(jtnode, JoinExpr))
647 JoinExpr *j = (JoinExpr *) jtnode;
649 resolvenew_in_jointree(j->larg, varno, subtlist);
650 resolvenew_in_jointree(j->rarg, varno, subtlist);
651 j->quals = ResolveNew(j->quals,
652 varno, 0, subtlist, CMD_SELECT, 0);
655 * We don't bother to update the colvars list, since it won't be
660 elog(ERROR, "resolvenew_in_jointree: unexpected node type %d",
665 * preprocess_jointree
666 * Attempt to simplify a query's jointree.
668 * If we succeed in pulling up a subquery then we might form a jointree
669 * in which a FromExpr is a direct child of another FromExpr. In that
670 * case we can consider collapsing the two FromExprs into one. This is
671 * an optional conversion, since the planner will work correctly either
672 * way. But we may find a better plan (at the cost of more planning time)
673 * if we merge the two nodes.
675 * NOTE: don't try to do this in the same jointree scan that does subquery
676 * pullup! Since we're changing the jointree structure here, that wouldn't
677 * work reliably --- see comments for pull_up_subqueries().
680 preprocess_jointree(Query *parse, Node *jtnode)
684 if (IsA(jtnode, RangeTblRef))
686 /* nothing to do here... */
688 else if (IsA(jtnode, FromExpr))
690 FromExpr *f = (FromExpr *) jtnode;
694 foreach(l, f->fromlist)
696 Node *child = (Node *) lfirst(l);
698 /* Recursively simplify the child... */
699 child = preprocess_jointree(parse, child);
700 /* Now, is it a FromExpr? */
701 if (child && IsA(child, FromExpr))
704 * Yes, so do we want to merge it into parent? Always do
705 * so if child has just one element (since that doesn't
706 * make the parent's list any longer). Otherwise we have
707 * to be careful about the increase in planning time
708 * caused by combining the two join search spaces into
709 * one. Our heuristic is to merge if the merge will
710 * produce a join list no longer than GEQO_RELS/2.
711 * (Perhaps need an additional user parameter?)
713 FromExpr *subf = (FromExpr *) child;
714 int childlen = length(subf->fromlist);
715 int myothers = length(newlist) + length(lnext(l));
717 if (childlen <= 1 || (childlen + myothers) <= geqo_rels / 2)
719 newlist = nconc(newlist, subf->fromlist);
720 f->quals = make_and_qual(subf->quals, f->quals);
723 newlist = lappend(newlist, child);
726 newlist = lappend(newlist, child);
728 f->fromlist = newlist;
730 else if (IsA(jtnode, JoinExpr))
732 JoinExpr *j = (JoinExpr *) jtnode;
734 /* Can't usefully change the JoinExpr, but recurse on children */
735 j->larg = preprocess_jointree(parse, j->larg);
736 j->rarg = preprocess_jointree(parse, j->rarg);
739 elog(ERROR, "preprocess_jointree: unexpected node type %d",
745 * preprocess_expression
746 * Do subquery_planner's preprocessing work for an expression,
747 * which can be a targetlist, a WHERE clause (including JOIN/ON
748 * conditions), or a HAVING clause.
751 preprocess_expression(Query *parse, Node *expr, int kind)
754 * Simplify constant expressions.
756 * Note that at this point quals have not yet been converted to
757 * implicit-AND form, so we can apply eval_const_expressions directly.
759 expr = eval_const_expressions(expr);
762 * If it's a qual or havingQual, canonicalize it, and convert it to
763 * implicit-AND format.
765 * XXX Is there any value in re-applying eval_const_expressions after
768 if (kind != EXPRKIND_TARGET)
770 expr = (Node *) canonicalize_qual((Expr *) expr, true);
772 #ifdef OPTIMIZER_DEBUG
773 printf("After canonicalize_qual()\n");
778 /* Expand SubLinks to SubPlans */
779 if (parse->hasSubLinks)
780 expr = SS_process_sublinks(expr, (kind != EXPRKIND_TARGET));
782 /* Replace uplevel vars with Param nodes */
783 if (PlannerQueryLevel > 1)
784 expr = SS_replace_correlation_vars(expr);
787 * If the query has any join RTEs, try to replace join alias variables
788 * with base-relation variables, to allow quals to be pushed down. We
789 * must do this after sublink processing, since it does not recurse
792 if (parse->hasJoinRTEs)
793 expr = flatten_join_alias_vars(expr, parse->rtable, false);
799 * preprocess_qual_conditions
800 * Recursively scan the query's jointree and do subquery_planner's
801 * preprocessing work on each qual condition found therein.
804 preprocess_qual_conditions(Query *parse, Node *jtnode)
808 if (IsA(jtnode, RangeTblRef))
810 /* nothing to do here */
812 else if (IsA(jtnode, FromExpr))
814 FromExpr *f = (FromExpr *) jtnode;
817 foreach(l, f->fromlist)
818 preprocess_qual_conditions(parse, lfirst(l));
820 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_WHERE);
822 else if (IsA(jtnode, JoinExpr))
824 JoinExpr *j = (JoinExpr *) jtnode;
826 preprocess_qual_conditions(parse, j->larg);
827 preprocess_qual_conditions(parse, j->rarg);
829 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_WHERE);
832 elog(ERROR, "preprocess_qual_conditions: unexpected node type %d",
836 /*--------------------
837 * inheritance_planner
838 * Generate a plan in the case where the result relation is an
841 * We have to handle this case differently from cases where a source
842 * relation is an inheritance set. Source inheritance is expanded at
843 * the bottom of the plan tree (see allpaths.c), but target inheritance
844 * has to be expanded at the top. The reason is that for UPDATE, each
845 * target relation needs a different targetlist matching its own column
846 * set. (This is not so critical for DELETE, but for simplicity we treat
847 * inherited DELETE the same way.) Fortunately, the UPDATE/DELETE target
848 * can never be the nullable side of an outer join, so it's OK to generate
851 * parse is the querytree produced by the parser & rewriter.
852 * inheritlist is an integer list of RT indexes for the result relation set.
854 * Returns a query plan.
855 *--------------------
858 inheritance_planner(Query *parse, List *inheritlist)
860 int parentRTindex = parse->resultRelation;
861 Oid parentOID = getrelid(parentRTindex, parse->rtable);
862 List *subplans = NIL;
866 foreach(l, inheritlist)
868 int childRTindex = lfirsti(l);
869 Oid childOID = getrelid(childRTindex, parse->rtable);
873 /* Generate modified query with this rel as target */
874 subquery = (Query *) adjust_inherited_attrs((Node *) parse,
875 parentRTindex, parentOID,
876 childRTindex, childOID);
878 subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */ );
879 subplans = lappend(subplans, subplan);
880 /* Save preprocessed tlist from first rel for use in Append */
882 tlist = subplan->targetlist;
885 /* Save the target-relations list for the executor, too */
886 parse->resultRelations = inheritlist;
888 return (Plan *) make_append(subplans, true, tlist);
891 /*--------------------
893 * Perform planning steps related to grouping, aggregation, etc.
894 * This primarily means adding top-level processing to the basic
895 * query plan produced by query_planner.
897 * parse is the querytree produced by the parser & rewriter.
898 * tuple_fraction is the fraction of tuples we expect will be retrieved
900 * tuple_fraction is interpreted as follows:
901 * < 0: determine fraction by inspection of query (normal case)
902 * 0: expect all tuples to be retrieved
903 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
904 * from the plan to be retrieved
905 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
906 * expected to be retrieved (ie, a LIMIT specification)
907 * The normal case is to pass -1, but some callers pass values >= 0 to
908 * override this routine's determination of the appropriate fraction.
910 * Returns a query plan.
911 *--------------------
914 grouping_planner(Query *parse, double tuple_fraction)
916 List *tlist = parse->targetList;
918 List *current_pathkeys;
921 if (parse->setOperations)
924 * Construct the plan for set operations. The result will not
925 * need any work except perhaps a top-level sort and/or LIMIT.
927 result_plan = plan_set_operations(parse);
930 * We should not need to call preprocess_targetlist, since we must
931 * be in a SELECT query node. Instead, use the targetlist
932 * returned by plan_set_operations (since this tells whether it
933 * returned any resjunk columns!), and transfer any sort key
934 * information from the original tlist.
936 Assert(parse->commandType == CMD_SELECT);
938 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
941 * Can't handle FOR UPDATE here (parser should have checked
942 * already, but let's make sure).
945 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
948 * We set current_pathkeys NIL indicating we do not know sort
949 * order. This is correct when the top set operation is UNION
950 * ALL, since the appended-together results are unsorted even if
951 * the subplans were sorted. For other set operations we could be
952 * smarter --- room for future improvement!
954 current_pathkeys = NIL;
957 * Calculate pathkeys that represent ordering requirements
959 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
961 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
965 /* No set operations, do regular planning */
967 List *group_pathkeys;
968 AttrNumber *groupColIdx = NULL;
970 double sub_tuple_fraction;
973 double dNumGroups = 0;
976 int numGroupCols = length(parse->groupClause);
977 bool use_hashed_grouping = false;
979 /* Preprocess targetlist in case we are inside an INSERT/UPDATE. */
980 tlist = preprocess_targetlist(tlist,
982 parse->resultRelation,
986 * Add TID targets for rels selected FOR UPDATE (should this be
987 * done in preprocess_targetlist?). The executor uses the TID to
988 * know which rows to lock, much as for UPDATE or DELETE.
995 * We've got trouble if the FOR UPDATE appears inside
996 * grouping, since grouping renders a reference to individual
997 * tuple CTIDs invalid. This is also checked at parse time,
998 * but that's insufficient because of rule substitution, query
1001 CheckSelectForUpdate(parse);
1004 * Currently the executor only supports FOR UPDATE at top
1007 if (PlannerQueryLevel > 1)
1008 elog(ERROR, "SELECT FOR UPDATE is not allowed in subselects");
1010 foreach(l, parse->rowMarks)
1012 Index rti = lfirsti(l);
1018 resname = (char *) palloc(32);
1019 snprintf(resname, 32, "ctid%u", rti);
1020 resdom = makeResdom(length(tlist) + 1,
1027 SelfItemPointerAttributeNumber,
1032 ctid = makeTargetEntry(resdom, (Expr *) var);
1033 tlist = lappend(tlist, ctid);
1038 * Generate appropriate target list for subplan; may be different
1039 * from tlist if grouping or aggregation is needed.
1041 sub_tlist = make_subplanTargetList(parse, tlist, &groupColIdx);
1044 * Calculate pathkeys that represent grouping/ordering
1047 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
1049 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
1053 * Will need actual number of aggregates for estimating costs.
1054 * Also, it's possible that optimization has eliminated all
1055 * aggregates, and we may as well check for that here.
1059 numAggs = length(pull_agg_clause((Node *) tlist)) +
1060 length(pull_agg_clause(parse->havingQual));
1062 parse->hasAggs = false;
1066 * Figure out whether we need a sorted result from query_planner.
1068 * If we have a GROUP BY clause, then we want a result sorted
1069 * properly for grouping. Otherwise, if there is an ORDER BY
1070 * clause, we want to sort by the ORDER BY clause. (Note: if we
1071 * have both, and ORDER BY is a superset of GROUP BY, it would be
1072 * tempting to request sort by ORDER BY --- but that might just
1073 * leave us failing to exploit an available sort order at all.
1074 * Needs more thought...)
1076 if (parse->groupClause)
1077 parse->query_pathkeys = group_pathkeys;
1078 else if (parse->sortClause)
1079 parse->query_pathkeys = sort_pathkeys;
1081 parse->query_pathkeys = NIL;
1084 * Figure out whether we expect to retrieve all the tuples that
1085 * the plan can generate, or to stop early due to outside factors
1086 * such as a cursor. If the caller passed a value >= 0, believe
1087 * that value, else do our own examination of the query context.
1089 if (tuple_fraction < 0.0)
1091 /* Initial assumption is we need all the tuples */
1092 tuple_fraction = 0.0;
1095 * Check for retrieve-into-portal, ie DECLARE CURSOR.
1097 * We have no real idea how many tuples the user will ultimately
1098 * FETCH from a cursor, but it seems a good bet that he
1099 * doesn't want 'em all. Optimize for 10% retrieval (you
1100 * gotta better number? Should this be a SETtable parameter?)
1102 if (parse->isPortal)
1103 tuple_fraction = 0.10;
1107 * Adjust tuple_fraction if we see that we are going to apply
1108 * limiting/grouping/aggregation/etc. This is not overridable by
1109 * the caller, since it reflects plan actions that this routine
1110 * will certainly take, not assumptions about context.
1112 if (parse->limitCount != NULL)
1115 * A LIMIT clause limits the absolute number of tuples
1116 * returned. However, if it's not a constant LIMIT then we
1117 * have to punt; for lack of a better idea, assume 10% of the
1118 * plan's result is wanted.
1120 double limit_fraction = 0.0;
1122 if (IsA(parse->limitCount, Const))
1124 Const *limitc = (Const *) parse->limitCount;
1125 int32 count = DatumGetInt32(limitc->constvalue);
1128 * A NULL-constant LIMIT represents "LIMIT ALL", which we
1129 * treat the same as no limit (ie, expect to retrieve all
1132 if (!limitc->constisnull && count > 0)
1134 limit_fraction = (double) count;
1135 /* We must also consider the OFFSET, if present */
1136 if (parse->limitOffset != NULL)
1138 if (IsA(parse->limitOffset, Const))
1142 limitc = (Const *) parse->limitOffset;
1143 offset = DatumGetInt32(limitc->constvalue);
1144 if (!limitc->constisnull && offset > 0)
1145 limit_fraction += (double) offset;
1149 /* OFFSET is an expression ... punt ... */
1150 limit_fraction = 0.10;
1157 /* LIMIT is an expression ... punt ... */
1158 limit_fraction = 0.10;
1161 if (limit_fraction > 0.0)
1164 * If we have absolute limits from both caller and LIMIT,
1165 * use the smaller value; if one is fractional and the
1166 * other absolute, treat the fraction as a fraction of the
1167 * absolute value; else we can multiply the two fractions
1170 if (tuple_fraction >= 1.0)
1172 if (limit_fraction >= 1.0)
1175 tuple_fraction = Min(tuple_fraction, limit_fraction);
1179 /* caller absolute, limit fractional */
1180 tuple_fraction *= limit_fraction;
1181 if (tuple_fraction < 1.0)
1182 tuple_fraction = 1.0;
1185 else if (tuple_fraction > 0.0)
1187 if (limit_fraction >= 1.0)
1189 /* caller fractional, limit absolute */
1190 tuple_fraction *= limit_fraction;
1191 if (tuple_fraction < 1.0)
1192 tuple_fraction = 1.0;
1196 /* both fractional */
1197 tuple_fraction *= limit_fraction;
1202 /* no info from caller, just use limit */
1203 tuple_fraction = limit_fraction;
1209 * With grouping or aggregation, the tuple fraction to pass to
1210 * query_planner() may be different from what it is at top level.
1212 sub_tuple_fraction = tuple_fraction;
1214 if (parse->groupClause)
1217 * In GROUP BY mode, we have the little problem that we don't
1218 * really know how many input tuples will be needed to make a
1219 * group, so we can't translate an output LIMIT count into an
1220 * input count. For lack of a better idea, assume 25% of the
1221 * input data will be processed if there is any output limit.
1222 * However, if the caller gave us a fraction rather than an
1223 * absolute count, we can keep using that fraction (which
1224 * amounts to assuming that all the groups are about the same
1227 if (sub_tuple_fraction >= 1.0)
1228 sub_tuple_fraction = 0.25;
1231 * If both GROUP BY and ORDER BY are specified, we will need
1232 * two levels of sort --- and, therefore, certainly need to
1233 * read all the input tuples --- unless ORDER BY is a subset
1234 * of GROUP BY. (We have not yet canonicalized the pathkeys,
1235 * so must use the slower noncanonical comparison method.)
1237 if (parse->groupClause && parse->sortClause &&
1238 !noncanonical_pathkeys_contained_in(sort_pathkeys,
1240 sub_tuple_fraction = 0.0;
1242 else if (parse->hasAggs)
1245 * Ungrouped aggregate will certainly want all the input
1248 sub_tuple_fraction = 0.0;
1250 else if (parse->distinctClause)
1253 * SELECT DISTINCT, like GROUP, will absorb an unpredictable
1254 * number of input tuples per output tuple. Handle the same
1257 if (sub_tuple_fraction >= 1.0)
1258 sub_tuple_fraction = 0.25;
1262 * Generate the best unsorted and presorted paths for this Query
1263 * (but note there may not be any presorted path).
1265 query_planner(parse, sub_tlist, sub_tuple_fraction,
1266 &cheapest_path, &sorted_path);
1269 * We couldn't canonicalize group_pathkeys and sort_pathkeys before
1270 * running query_planner(), so do it now.
1272 group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
1273 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
1276 * Consider whether we might want to use hashed grouping.
1278 if (parse->groupClause)
1281 * Always estimate the number of groups. We can't do this until
1282 * after running query_planner(), either.
1284 dNumGroups = estimate_num_groups(parse,
1286 cheapest_path->parent->rows);
1287 /* Also want it as a long int --- but 'ware overflow! */
1288 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
1291 * Check can't-do-it conditions, including whether the grouping
1292 * operators are hashjoinable.
1294 * Executor doesn't support hashed aggregation with DISTINCT
1295 * aggregates. (Doing so would imply storing *all* the input
1296 * values in the hash table, which seems like a certain loser.)
1298 if (!enable_hashagg || !hash_safe_grouping(parse))
1299 use_hashed_grouping = false;
1300 else if (parse->hasAggs &&
1301 (contain_distinct_agg_clause((Node *) tlist) ||
1302 contain_distinct_agg_clause(parse->havingQual)))
1303 use_hashed_grouping = false;
1307 * Use hashed grouping if (a) we think we can fit the
1308 * hashtable into SortMem, *and* (b) the estimated cost
1309 * is no more than doing it the other way. While avoiding
1310 * the need for sorted input is usually a win, the fact
1311 * that the output won't be sorted may be a loss; so we
1312 * need to do an actual cost comparison.
1314 * In most cases we have no good way to estimate the size of
1315 * the transition value needed by an aggregate; arbitrarily
1316 * assume it is 100 bytes. Also set the overhead per hashtable
1317 * entry at 64 bytes.
1319 int hashentrysize = cheapest_path->parent->width + 64 +
1322 if (hashentrysize * dNumGroups <= SortMem * 1024L)
1325 * Okay, do the cost comparison. We need to consider
1326 * cheapest_path + hashagg [+ final sort]
1328 * cheapest_path [+ sort] + group or agg [+ final sort]
1330 * presorted_path + group or agg [+ final sort]
1331 * where brackets indicate a step that may not be needed.
1332 * We assume query_planner() will have returned a
1333 * presorted path only if it's a winner compared to
1334 * cheapest_path for this purpose.
1336 * These path variables are dummies that just hold cost
1337 * fields; we don't make actual Paths for these steps.
1342 cost_agg(&hashed_p, parse,
1343 AGG_HASHED, numAggs,
1344 numGroupCols, dNumGroups,
1345 cheapest_path->startup_cost,
1346 cheapest_path->total_cost,
1347 cheapest_path->parent->rows);
1348 /* Result of hashed agg is always unsorted */
1350 cost_sort(&hashed_p, parse, sort_pathkeys,
1351 hashed_p.total_cost,
1353 cheapest_path->parent->width);
1357 sorted_p.startup_cost = sorted_path->startup_cost;
1358 sorted_p.total_cost = sorted_path->total_cost;
1359 current_pathkeys = sorted_path->pathkeys;
1363 sorted_p.startup_cost = cheapest_path->startup_cost;
1364 sorted_p.total_cost = cheapest_path->total_cost;
1365 current_pathkeys = cheapest_path->pathkeys;
1367 if (!pathkeys_contained_in(group_pathkeys,
1370 cost_sort(&sorted_p, parse, group_pathkeys,
1371 sorted_p.total_cost,
1372 cheapest_path->parent->rows,
1373 cheapest_path->parent->width);
1374 current_pathkeys = group_pathkeys;
1377 cost_agg(&sorted_p, parse,
1378 AGG_SORTED, numAggs,
1379 numGroupCols, dNumGroups,
1380 sorted_p.startup_cost,
1381 sorted_p.total_cost,
1382 cheapest_path->parent->rows);
1384 cost_group(&sorted_p, parse,
1385 numGroupCols, dNumGroups,
1386 sorted_p.startup_cost,
1387 sorted_p.total_cost,
1388 cheapest_path->parent->rows);
1389 /* The Agg or Group node will preserve ordering */
1390 if (sort_pathkeys &&
1391 !pathkeys_contained_in(sort_pathkeys,
1394 cost_sort(&sorted_p, parse, sort_pathkeys,
1395 sorted_p.total_cost,
1397 cheapest_path->parent->width);
1401 * Now make the decision using the top-level tuple
1402 * fraction. First we have to convert an absolute
1403 * count (LIMIT) into fractional form.
1405 if (tuple_fraction >= 1.0)
1406 tuple_fraction /= dNumGroups;
1408 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1409 tuple_fraction) <= 0)
1411 /* Hashed is cheaper, so use it */
1412 use_hashed_grouping = true;
1419 * Select the best path and create a plan to execute it.
1421 * If we are doing hashed grouping, we will always read all the
1422 * input tuples, so use the cheapest-total path. Otherwise,
1423 * trust query_planner's decision about which to use.
1425 if (sorted_path && !use_hashed_grouping)
1427 result_plan = create_plan(parse, sorted_path);
1428 current_pathkeys = sorted_path->pathkeys;
1432 result_plan = create_plan(parse, cheapest_path);
1433 current_pathkeys = cheapest_path->pathkeys;
1437 * create_plan() returns a plan with just a "flat" tlist of required
1438 * Vars. We want to insert the sub_tlist as the tlist of the top
1439 * plan node. If the top-level plan node is one that cannot do
1440 * expression evaluation, we must insert a Result node to project the
1442 * Currently, the only plan node we might see here that falls into
1443 * that category is Append.
1445 if (IsA(result_plan, Append))
1447 result_plan = (Plan *) make_result(sub_tlist, NULL, result_plan);
1452 * Otherwise, just replace the flat tlist with the desired tlist.
1454 result_plan->targetlist = sub_tlist;
1457 * Also, account for the cost of evaluation of the sub_tlist.
1459 * Up to now, we have only been dealing with "flat" tlists, containing
1460 * just Vars. So their evaluation cost is zero according to the
1461 * model used by cost_qual_eval() (or if you prefer, the cost is
1462 * factored into cpu_tuple_cost). Thus we can avoid accounting for
1463 * tlist cost throughout query_planner() and subroutines.
1464 * But now we've inserted a tlist that might contain actual operators,
1465 * sub-selects, etc --- so we'd better account for its cost.
1467 * Below this point, any tlist eval cost for added-on nodes should
1468 * be accounted for as we create those nodes. Presently, of the
1469 * node types we can add on, only Agg and Group project new tlists
1470 * (the rest just copy their input tuples) --- so make_agg() and
1471 * make_group() are responsible for computing the added cost.
1473 cost_qual_eval(&tlist_cost, sub_tlist);
1474 result_plan->startup_cost += tlist_cost.startup;
1475 result_plan->total_cost += tlist_cost.startup +
1476 tlist_cost.per_tuple * result_plan->plan_rows;
1479 * Insert AGG or GROUP node if needed, plus an explicit sort step
1482 * HAVING clause, if any, becomes qual of the Agg node
1484 if (use_hashed_grouping)
1486 /* Hashed aggregate plan --- no sort needed */
1487 result_plan = (Plan *) make_agg(parse,
1489 (List *) parse->havingQual,
1496 /* Hashed aggregation produces randomly-ordered results */
1497 current_pathkeys = NIL;
1499 else if (parse->hasAggs)
1501 /* Plain aggregate plan --- sort if needed */
1502 AggStrategy aggstrategy;
1504 if (parse->groupClause)
1506 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1508 result_plan = make_groupsortplan(parse,
1512 current_pathkeys = group_pathkeys;
1514 aggstrategy = AGG_SORTED;
1516 * The AGG node will not change the sort ordering of its
1517 * groups, so current_pathkeys describes the result too.
1522 aggstrategy = AGG_PLAIN;
1523 /* Result will be only one row anyway; no sort order */
1524 current_pathkeys = NIL;
1527 result_plan = (Plan *) make_agg(parse,
1529 (List *) parse->havingQual,
1540 * If there are no Aggs, we shouldn't have any HAVING qual anymore
1542 Assert(parse->havingQual == NULL);
1545 * If we have a GROUP BY clause, insert a group node (plus the
1546 * appropriate sort node, if necessary).
1548 if (parse->groupClause)
1551 * Add an explicit sort if we couldn't make the path come out
1552 * the way the GROUP node needs it.
1554 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1556 result_plan = make_groupsortplan(parse,
1560 current_pathkeys = group_pathkeys;
1563 result_plan = (Plan *) make_group(parse,
1569 /* The Group node won't change sort ordering */
1572 } /* end of if (setOperations) */
1575 * If we were not able to make the plan come out in the right order,
1576 * add an explicit sort step.
1578 if (parse->sortClause)
1580 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1581 result_plan = make_sortplan(parse, tlist, result_plan,
1586 * If there is a DISTINCT clause, add the UNIQUE node.
1588 if (parse->distinctClause)
1590 result_plan = (Plan *) make_unique(tlist, result_plan,
1591 parse->distinctClause);
1593 * If there was grouping or aggregation, leave plan_rows as-is
1594 * (ie, assume the result was already mostly unique). If not,
1595 * it's reasonable to assume the UNIQUE filter has effects
1596 * comparable to GROUP BY.
1598 if (!parse->groupClause && !parse->hasAggs)
1599 result_plan->plan_rows = estimate_num_groups(parse,
1600 parse->distinctClause,
1601 result_plan->plan_rows);
1605 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1607 if (parse->limitOffset || parse->limitCount)
1609 result_plan = (Plan *) make_limit(tlist, result_plan,
1618 * hash_safe_grouping - are grouping operators hashable?
1620 * We assume hashed aggregation will work if the datatype's equality operator
1621 * is marked hashjoinable.
1624 hash_safe_grouping(Query *parse)
1628 foreach(gl, parse->groupClause)
1630 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1631 TargetEntry *tle = get_sortgroupclause_tle(grpcl, parse->targetList);
1635 optup = equality_oper(tle->resdom->restype, false);
1636 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1637 ReleaseSysCache(optup);
1645 * make_subplanTargetList
1646 * Generate appropriate target list when grouping is required.
1648 * When grouping_planner inserts Aggregate or Group plan nodes above
1649 * the result of query_planner, we typically want to pass a different
1650 * target list to query_planner than the outer plan nodes should have.
1651 * This routine generates the correct target list for the subplan.
1653 * The initial target list passed from the parser already contains entries
1654 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1655 * for variables used only in HAVING clauses; so we need to add those
1656 * variables to the subplan target list. Also, if we are doing either
1657 * grouping or aggregation, we flatten all expressions except GROUP BY items
1658 * into their component variables; the other expressions will be computed by
1659 * the inserted nodes rather than by the subplan. For example,
1660 * given a query like
1661 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1662 * we want to pass this targetlist to the subplan:
1664 * where the a+b target will be used by the Sort/Group steps, and the
1665 * other targets will be used for computing the final results. (In the
1666 * above example we could theoretically suppress the a and b targets and
1667 * pass down only c,d,a+b, but it's not really worth the trouble to
1668 * eliminate simple var references from the subplan. We will avoid doing
1669 * the extra computation to recompute a+b at the outer level; see
1670 * replace_vars_with_subplan_refs() in setrefs.c.)
1672 * 'parse' is the query being processed.
1673 * 'tlist' is the query's target list.
1674 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1675 * expressions (if there are any) in the subplan's target list.
1677 * The result is the targetlist to be passed to the subplan.
1681 make_subplanTargetList(Query *parse,
1683 AttrNumber **groupColIdx)
1689 *groupColIdx = NULL;
1692 * If we're not grouping or aggregating, nothing to do here;
1693 * query_planner should receive the unmodified target list.
1695 if (!parse->hasAggs && !parse->groupClause && !parse->havingQual)
1699 * Otherwise, start with a "flattened" tlist (having just the vars
1700 * mentioned in the targetlist and HAVING qual --- but not upper-
1701 * level Vars; they will be replaced by Params later on).
1703 sub_tlist = flatten_tlist(tlist);
1704 extravars = pull_var_clause(parse->havingQual, false);
1705 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1706 freeList(extravars);
1709 * If grouping, create sub_tlist entries for all GROUP BY expressions
1710 * (GROUP BY items that are simple Vars should be in the list
1711 * already), and make an array showing where the group columns are in
1714 numCols = length(parse->groupClause);
1718 AttrNumber *grpColIdx;
1721 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1722 *groupColIdx = grpColIdx;
1724 foreach(gl, parse->groupClause)
1726 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1727 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1728 TargetEntry *te = NULL;
1731 /* Find or make a matching sub_tlist entry */
1732 foreach(sl, sub_tlist)
1734 te = (TargetEntry *) lfirst(sl);
1735 if (equal(groupexpr, te->expr))
1740 te = makeTargetEntry(makeResdom(length(sub_tlist) + 1,
1741 exprType(groupexpr),
1742 exprTypmod(groupexpr),
1745 (Expr *) groupexpr);
1746 sub_tlist = lappend(sub_tlist, te);
1749 /* and save its resno */
1750 grpColIdx[keyno++] = te->resdom->resno;
1758 * make_groupsortplan
1759 * Add a Sort node to explicitly sort according to the GROUP BY clause.
1761 * Note: the Sort node always just takes a copy of the subplan's tlist
1762 * plus ordering information. (This might seem inefficient if the
1763 * subplan contains complex GROUP BY expressions, but in fact Sort
1764 * does not evaluate its targetlist --- it only outputs the same
1765 * tuples in a new order. So the expressions we might be copying
1766 * are just dummies with no extra execution cost.)
1769 make_groupsortplan(Query *parse,
1771 AttrNumber *grpColIdx,
1774 List *sort_tlist = new_unsorted_tlist(subplan->targetlist);
1778 foreach(gl, groupClause)
1780 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1781 TargetEntry *te = nth(grpColIdx[keyno] - 1, sort_tlist);
1782 Resdom *resdom = te->resdom;
1785 * Check for the possibility of duplicate group-by clauses ---
1786 * the parser should have removed 'em, but the Sort executor
1787 * will get terribly confused if any get through!
1789 if (resdom->reskey == 0)
1791 /* OK, insert the ordering info needed by the executor. */
1792 resdom->reskey = ++keyno;
1793 resdom->reskeyop = grpcl->sortop;
1799 return (Plan *) make_sort(parse, sort_tlist, subplan, keyno);
1804 * Add a Sort node to implement an explicit ORDER BY clause.
1807 make_sortplan(Query *parse, List *tlist, Plan *plannode, List *sortcls)
1814 * First make a copy of the tlist so that we don't corrupt the
1817 sort_tlist = new_unsorted_tlist(tlist);
1821 SortClause *sortcl = (SortClause *) lfirst(i);
1822 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sort_tlist);
1823 Resdom *resdom = tle->resdom;
1826 * Check for the possibility of duplicate order-by clauses --- the
1827 * parser should have removed 'em, but the executor will get
1828 * terribly confused if any get through!
1830 if (resdom->reskey == 0)
1832 /* OK, insert the ordering info needed by the executor. */
1833 resdom->reskey = ++keyno;
1834 resdom->reskeyop = sortcl->sortop;
1840 return (Plan *) make_sort(parse, sort_tlist, plannode, keyno);
1844 * postprocess_setop_tlist
1845 * Fix up targetlist returned by plan_set_operations().
1847 * We need to transpose sort key info from the orig_tlist into new_tlist.
1848 * NOTE: this would not be good enough if we supported resjunk sort keys
1849 * for results of set operations --- then, we'd need to project a whole
1850 * new tlist to evaluate the resjunk columns. For now, just elog if we
1851 * find any resjunk columns in orig_tlist.
1854 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1858 foreach(l, new_tlist)
1860 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1861 TargetEntry *orig_tle;
1863 /* ignore resjunk columns in setop result */
1864 if (new_tle->resdom->resjunk)
1867 Assert(orig_tlist != NIL);
1868 orig_tle = (TargetEntry *) lfirst(orig_tlist);
1869 orig_tlist = lnext(orig_tlist);
1870 if (orig_tle->resdom->resjunk)
1871 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");
1872 Assert(new_tle->resdom->resno == orig_tle->resdom->resno);
1873 Assert(new_tle->resdom->restype == orig_tle->resdom->restype);
1874 new_tle->resdom->ressortgroupref = orig_tle->resdom->ressortgroupref;
1876 if (orig_tlist != NIL)
1877 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");