1 /*-------------------------------------------------------------------------
4 * The query optimizer external interface.
6 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/optimizer/plan/planner.c,v 1.212 2007/01/20 20:45:39 tgl Exp $
13 *-------------------------------------------------------------------------
20 #include "catalog/pg_operator.h"
21 #include "executor/executor.h"
22 #include "executor/nodeAgg.h"
23 #include "miscadmin.h"
24 #include "nodes/makefuncs.h"
25 #include "optimizer/clauses.h"
26 #include "optimizer/cost.h"
27 #include "optimizer/pathnode.h"
28 #include "optimizer/paths.h"
29 #include "optimizer/planmain.h"
30 #include "optimizer/planner.h"
31 #include "optimizer/prep.h"
32 #include "optimizer/subselect.h"
33 #include "optimizer/tlist.h"
34 #include "optimizer/var.h"
35 #ifdef OPTIMIZER_DEBUG
36 #include "nodes/print.h"
38 #include "parser/parse_expr.h"
39 #include "parser/parse_oper.h"
40 #include "parser/parsetree.h"
41 #include "utils/lsyscache.h"
42 #include "utils/syscache.h"
45 ParamListInfo PlannerBoundParamList = NULL; /* current boundParams */
48 /* Expression kind codes for preprocess_expression */
49 #define EXPRKIND_QUAL 0
50 #define EXPRKIND_TARGET 1
51 #define EXPRKIND_RTFUNC 2
52 #define EXPRKIND_VALUES 3
53 #define EXPRKIND_LIMIT 4
54 #define EXPRKIND_ININFO 5
55 #define EXPRKIND_APPINFO 6
58 static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
59 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
60 static Plan *inheritance_planner(PlannerInfo *root);
61 static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
62 static bool is_dummy_plan(Plan *plan);
63 static double preprocess_limit(PlannerInfo *root,
64 double tuple_fraction,
65 int64 *offset_est, int64 *count_est);
66 static Oid *extract_grouping_ops(List *groupClause);
67 static bool choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
68 Path *cheapest_path, Path *sorted_path,
69 Oid *groupOperators, double dNumGroups,
70 AggClauseCounts *agg_counts);
71 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
72 AttrNumber **groupColIdx, bool *need_tlist_eval);
73 static void locate_grouping_columns(PlannerInfo *root,
76 AttrNumber *groupColIdx);
77 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
80 /*****************************************************************************
82 * Query optimizer entry point
84 *****************************************************************************/
86 planner(Query *parse, bool isCursor, int cursorOptions,
87 ParamListInfo boundParams)
89 double tuple_fraction;
91 Index save_PlannerQueryLevel;
92 List *save_PlannerParamList;
93 ParamListInfo save_PlannerBoundParamList;
96 * The planner can be called recursively (an example is when
97 * eval_const_expressions tries to pre-evaluate an SQL function). So,
98 * these global state variables must be saved and restored.
100 * Query level and the param list cannot be moved into the per-query
101 * PlannerInfo structure since their whole purpose is communication across
102 * multiple sub-queries. Also, boundParams is explicitly info from outside
103 * the query, and so is likewise better handled as a global variable.
105 * Note we do NOT save and restore PlannerPlanId: it exists to assign
106 * unique IDs to SubPlan nodes, and we want those IDs to be unique for the
107 * life of a backend. Also, PlannerInitPlan is saved/restored in
108 * subquery_planner, not here.
110 save_PlannerQueryLevel = PlannerQueryLevel;
111 save_PlannerParamList = PlannerParamList;
112 save_PlannerBoundParamList = PlannerBoundParamList;
114 /* Initialize state for handling outer-level references and params */
115 PlannerQueryLevel = 0; /* will be 1 in top-level subquery_planner */
116 PlannerParamList = NIL;
117 PlannerBoundParamList = boundParams;
119 /* Determine what fraction of the plan is likely to be scanned */
123 * We have no real idea how many tuples the user will ultimately FETCH
124 * from a cursor, but it seems a good bet that he doesn't want 'em
125 * all. Optimize for 10% retrieval (you gotta better number? Should
126 * this be a SETtable parameter?)
128 tuple_fraction = 0.10;
132 /* Default assumption is we need all the tuples */
133 tuple_fraction = 0.0;
136 /* primary planning entry point (may recurse for subqueries) */
137 result_plan = subquery_planner(parse, tuple_fraction, NULL);
139 /* check we popped out the right number of levels */
140 Assert(PlannerQueryLevel == 0);
143 * If creating a plan for a scrollable cursor, make sure it can run
144 * backwards on demand. Add a Material node at the top at need.
146 if (isCursor && (cursorOptions & CURSOR_OPT_SCROLL))
148 if (!ExecSupportsBackwardScan(result_plan))
149 result_plan = materialize_finished_plan(result_plan);
152 /* final cleanup of the plan */
153 result_plan = set_plan_references(result_plan, parse->rtable);
155 /* executor wants to know total number of Params used overall */
156 result_plan->nParamExec = list_length(PlannerParamList);
158 /* restore state for outer planner, if any */
159 PlannerQueryLevel = save_PlannerQueryLevel;
160 PlannerParamList = save_PlannerParamList;
161 PlannerBoundParamList = save_PlannerBoundParamList;
167 /*--------------------
169 * Invokes the planner on a subquery. We recurse to here for each
170 * sub-SELECT found in the query tree.
172 * parse is the querytree produced by the parser & rewriter.
173 * tuple_fraction is the fraction of tuples we expect will be retrieved.
174 * tuple_fraction is interpreted as explained for grouping_planner, below.
176 * If subquery_pathkeys isn't NULL, it receives a list of pathkeys indicating
177 * the output sort ordering of the completed plan.
179 * Basically, this routine does the stuff that should only be done once
180 * per Query object. It then calls grouping_planner. At one time,
181 * grouping_planner could be invoked recursively on the same Query object;
182 * that's not currently true, but we keep the separation between the two
183 * routines anyway, in case we need it again someday.
185 * subquery_planner will be called recursively to handle sub-Query nodes
186 * found within the query's expressions and rangetable.
188 * Returns a query plan.
189 *--------------------
192 subquery_planner(Query *parse, double tuple_fraction,
193 List **subquery_pathkeys)
195 List *saved_initplan = PlannerInitPlan;
196 int saved_planid = PlannerPlanId;
202 /* Set up for a new level of subquery */
204 PlannerInitPlan = NIL;
206 /* Create a PlannerInfo data structure for this subquery */
207 root = makeNode(PlannerInfo);
209 root->planner_cxt = CurrentMemoryContext;
210 root->eq_classes = NIL;
211 root->in_info_list = NIL;
212 root->append_rel_list = NIL;
215 * Look for IN clauses at the top level of WHERE, and transform them into
216 * joins. Note that this step only handles IN clauses originally at top
217 * level of WHERE; if we pull up any subqueries in the next step, their
218 * INs are processed just before pulling them up.
220 if (parse->hasSubLinks)
221 parse->jointree->quals = pull_up_IN_clauses(root,
222 parse->jointree->quals);
225 * Check to see if any subqueries in the rangetable can be merged into
228 parse->jointree = (FromExpr *)
229 pull_up_subqueries(root, (Node *) parse->jointree, false, false);
232 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
233 * avoid the expense of doing flatten_join_alias_vars(). Also check for
234 * outer joins --- if none, we can skip reduce_outer_joins() and some
235 * other processing. This must be done after we have done
236 * pull_up_subqueries, of course.
238 * Note: if reduce_outer_joins manages to eliminate all outer joins,
239 * root->hasOuterJoins is not reset currently. This is OK since its
240 * purpose is merely to suppress unnecessary processing in simple cases.
242 root->hasJoinRTEs = false;
243 root->hasOuterJoins = false;
244 foreach(l, parse->rtable)
246 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
248 if (rte->rtekind == RTE_JOIN)
250 root->hasJoinRTEs = true;
251 if (IS_OUTER_JOIN(rte->jointype))
253 root->hasOuterJoins = true;
254 /* Can quit scanning once we find an outer join */
261 * Expand any rangetable entries that are inheritance sets into "append
262 * relations". This can add entries to the rangetable, but they must be
263 * plain base relations not joins, so it's OK (and marginally more
264 * efficient) to do it after checking for join RTEs. We must do it after
265 * pulling up subqueries, else we'd fail to handle inherited tables in
268 expand_inherited_tables(root);
271 * Set hasHavingQual to remember if HAVING clause is present. Needed
272 * because preprocess_expression will reduce a constant-true condition to
273 * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
275 root->hasHavingQual = (parse->havingQual != NULL);
277 /* Clear this flag; might get set in distribute_qual_to_rels */
278 root->hasPseudoConstantQuals = false;
281 * Do expression preprocessing on targetlist and quals.
283 parse->targetList = (List *)
284 preprocess_expression(root, (Node *) parse->targetList,
287 parse->returningList = (List *)
288 preprocess_expression(root, (Node *) parse->returningList,
291 preprocess_qual_conditions(root, (Node *) parse->jointree);
293 parse->havingQual = preprocess_expression(root, parse->havingQual,
296 parse->limitOffset = preprocess_expression(root, parse->limitOffset,
298 parse->limitCount = preprocess_expression(root, parse->limitCount,
301 root->in_info_list = (List *)
302 preprocess_expression(root, (Node *) root->in_info_list,
304 root->append_rel_list = (List *)
305 preprocess_expression(root, (Node *) root->append_rel_list,
308 /* Also need to preprocess expressions for function and values RTEs */
309 foreach(l, parse->rtable)
311 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
313 if (rte->rtekind == RTE_FUNCTION)
314 rte->funcexpr = preprocess_expression(root, rte->funcexpr,
316 else if (rte->rtekind == RTE_VALUES)
317 rte->values_lists = (List *)
318 preprocess_expression(root, (Node *) rte->values_lists,
323 * In some cases we may want to transfer a HAVING clause into WHERE. We
324 * cannot do so if the HAVING clause contains aggregates (obviously) or
325 * volatile functions (since a HAVING clause is supposed to be executed
326 * only once per group). Also, it may be that the clause is so expensive
327 * to execute that we're better off doing it only once per group, despite
328 * the loss of selectivity. This is hard to estimate short of doing the
329 * entire planning process twice, so we use a heuristic: clauses
330 * containing subplans are left in HAVING. Otherwise, we move or copy the
331 * HAVING clause into WHERE, in hopes of eliminating tuples before
332 * aggregation instead of after.
334 * If the query has explicit grouping then we can simply move such a
335 * clause into WHERE; any group that fails the clause will not be in the
336 * output because none of its tuples will reach the grouping or
337 * aggregation stage. Otherwise we must have a degenerate (variable-free)
338 * HAVING clause, which we put in WHERE so that query_planner() can use it
339 * in a gating Result node, but also keep in HAVING to ensure that we
340 * don't emit a bogus aggregated row. (This could be done better, but it
341 * seems not worth optimizing.)
343 * Note that both havingQual and parse->jointree->quals are in
344 * implicitly-ANDed-list form at this point, even though they are declared
348 foreach(l, (List *) parse->havingQual)
350 Node *havingclause = (Node *) lfirst(l);
352 if (contain_agg_clause(havingclause) ||
353 contain_volatile_functions(havingclause) ||
354 contain_subplans(havingclause))
356 /* keep it in HAVING */
357 newHaving = lappend(newHaving, havingclause);
359 else if (parse->groupClause)
361 /* move it to WHERE */
362 parse->jointree->quals = (Node *)
363 lappend((List *) parse->jointree->quals, havingclause);
367 /* put a copy in WHERE, keep it in HAVING */
368 parse->jointree->quals = (Node *)
369 lappend((List *) parse->jointree->quals,
370 copyObject(havingclause));
371 newHaving = lappend(newHaving, havingclause);
374 parse->havingQual = (Node *) newHaving;
377 * If we have any outer joins, try to reduce them to plain inner joins.
378 * This step is most easily done after we've done expression
381 if (root->hasOuterJoins)
382 reduce_outer_joins(root);
385 * Do the main planning. If we have an inherited target relation, that
386 * needs special processing, else go straight to grouping_planner.
388 if (parse->resultRelation &&
389 rt_fetch(parse->resultRelation, parse->rtable)->inh)
390 plan = inheritance_planner(root);
392 plan = grouping_planner(root, tuple_fraction);
395 * If any subplans were generated, or if we're inside a subplan, build
396 * initPlan list and extParam/allParam sets for plan nodes, and attach the
397 * initPlans to the top plan node.
399 if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
400 SS_finalize_plan(plan, parse->rtable);
402 /* Return sort ordering info if caller wants it */
403 if (subquery_pathkeys)
404 *subquery_pathkeys = root->query_pathkeys;
406 /* Return to outer subquery context */
408 PlannerInitPlan = saved_initplan;
409 /* we do NOT restore PlannerPlanId; that's not an oversight! */
415 * preprocess_expression
416 * Do subquery_planner's preprocessing work for an expression,
417 * which can be a targetlist, a WHERE clause (including JOIN/ON
418 * conditions), or a HAVING clause.
421 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
424 * Fall out quickly if expression is empty. This occurs often enough to
425 * be worth checking. Note that null->null is the correct conversion for
426 * implicit-AND result format, too.
432 * If the query has any join RTEs, replace join alias variables with
433 * base-relation variables. We must do this before sublink processing,
434 * else sublinks expanded out from join aliases wouldn't get processed. We
435 * can skip it in VALUES lists, however, since they can't contain any Vars
438 if (root->hasJoinRTEs && kind != EXPRKIND_VALUES)
439 expr = flatten_join_alias_vars(root, expr);
442 * Simplify constant expressions.
444 * Note: this also flattens nested AND and OR expressions into N-argument
445 * form. All processing of a qual expression after this point must be
446 * careful to maintain AND/OR flatness --- that is, do not generate a tree
447 * with AND directly under AND, nor OR directly under OR.
449 * Because this is a relatively expensive process, we skip it when the
450 * query is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()". The
451 * expression will only be evaluated once anyway, so no point in
452 * pre-simplifying; we can't execute it any faster than the executor can,
453 * and we will waste cycles copying the tree. Notice however that we
454 * still must do it for quals (to get AND/OR flatness); and if we are in a
455 * subquery we should not assume it will be done only once.
457 * For VALUES lists we never do this at all, again on the grounds that we
458 * should optimize for one-time evaluation.
460 if (kind != EXPRKIND_VALUES &&
461 (root->parse->jointree->fromlist != NIL ||
462 kind == EXPRKIND_QUAL ||
463 PlannerQueryLevel > 1))
464 expr = eval_const_expressions(expr);
467 * If it's a qual or havingQual, canonicalize it.
469 if (kind == EXPRKIND_QUAL)
471 expr = (Node *) canonicalize_qual((Expr *) expr);
473 #ifdef OPTIMIZER_DEBUG
474 printf("After canonicalize_qual()\n");
479 /* Expand SubLinks to SubPlans */
480 if (root->parse->hasSubLinks)
481 expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL));
484 * XXX do not insert anything here unless you have grokked the comments in
485 * SS_replace_correlation_vars ...
488 /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
489 if (PlannerQueryLevel > 1)
490 expr = SS_replace_correlation_vars(expr);
493 * If it's a qual or havingQual, convert it to implicit-AND format. (We
494 * don't want to do this before eval_const_expressions, since the latter
495 * would be unable to simplify a top-level AND correctly. Also,
496 * SS_process_sublinks expects explicit-AND format.)
498 if (kind == EXPRKIND_QUAL)
499 expr = (Node *) make_ands_implicit((Expr *) expr);
505 * preprocess_qual_conditions
506 * Recursively scan the query's jointree and do subquery_planner's
507 * preprocessing work on each qual condition found therein.
510 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
514 if (IsA(jtnode, RangeTblRef))
516 /* nothing to do here */
518 else if (IsA(jtnode, FromExpr))
520 FromExpr *f = (FromExpr *) jtnode;
523 foreach(l, f->fromlist)
524 preprocess_qual_conditions(root, lfirst(l));
526 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
528 else if (IsA(jtnode, JoinExpr))
530 JoinExpr *j = (JoinExpr *) jtnode;
532 preprocess_qual_conditions(root, j->larg);
533 preprocess_qual_conditions(root, j->rarg);
535 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
538 elog(ERROR, "unrecognized node type: %d",
539 (int) nodeTag(jtnode));
543 * inheritance_planner
544 * Generate a plan in the case where the result relation is an
547 * We have to handle this case differently from cases where a source relation
548 * is an inheritance set. Source inheritance is expanded at the bottom of the
549 * plan tree (see allpaths.c), but target inheritance has to be expanded at
550 * the top. The reason is that for UPDATE, each target relation needs a
551 * different targetlist matching its own column set. Also, for both UPDATE
552 * and DELETE, the executor needs the Append plan node at the top, else it
553 * can't keep track of which table is the current target table. Fortunately,
554 * the UPDATE/DELETE target can never be the nullable side of an outer join,
555 * so it's OK to generate the plan this way.
557 * Returns a query plan.
560 inheritance_planner(PlannerInfo *root)
562 Query *parse = root->parse;
563 int parentRTindex = parse->resultRelation;
564 List *subplans = NIL;
565 List *resultRelations = NIL;
566 List *returningLists = NIL;
572 foreach(l, root->append_rel_list)
574 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
577 /* append_rel_list contains all append rels; ignore others */
578 if (appinfo->parent_relid != parentRTindex)
582 * Generate modified query with this rel as target. We have to be
583 * prepared to translate varnos in in_info_list as well as in the
586 memcpy(&subroot, root, sizeof(PlannerInfo));
587 subroot.parse = (Query *)
588 adjust_appendrel_attrs((Node *) parse,
590 subroot.in_info_list = (List *)
591 adjust_appendrel_attrs((Node *) root->in_info_list,
593 /* There shouldn't be any OJ info to translate, as yet */
594 Assert(subroot.oj_info_list == NIL);
597 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
600 * If this child rel was excluded by constraint exclusion, exclude it
603 if (is_dummy_plan(subplan))
606 /* Save rtable and tlist from first rel for use below */
609 rtable = subroot.parse->rtable;
610 tlist = subplan->targetlist;
613 subplans = lappend(subplans, subplan);
615 /* Build target-relations list for the executor */
616 resultRelations = lappend_int(resultRelations, appinfo->child_relid);
618 /* Build list of per-relation RETURNING targetlists */
619 if (parse->returningList)
621 Assert(list_length(subroot.parse->returningLists) == 1);
622 returningLists = list_concat(returningLists,
623 subroot.parse->returningLists);
627 parse->resultRelations = resultRelations;
628 parse->returningLists = returningLists;
630 /* Mark result as unordered (probably unnecessary) */
631 root->query_pathkeys = NIL;
634 * If we managed to exclude every child rel, return a dummy plan
637 return (Plan *) make_result(tlist,
638 (Node *) list_make1(makeBoolConst(false,
643 * Planning might have modified the rangetable, due to changes of the
644 * Query structures inside subquery RTEs. We have to ensure that this
645 * gets propagated back to the master copy. But can't do this until we
646 * are done planning, because all the calls to grouping_planner need
647 * virgin sub-Queries to work from. (We are effectively assuming that
648 * sub-Queries will get planned identically each time, or at least that
649 * the impacts on their rangetables will be the same each time.)
651 * XXX should clean this up someday
653 parse->rtable = rtable;
655 return (Plan *) make_append(subplans, true, tlist);
658 /*--------------------
660 * Perform planning steps related to grouping, aggregation, etc.
661 * This primarily means adding top-level processing to the basic
662 * query plan produced by query_planner.
664 * tuple_fraction is the fraction of tuples we expect will be retrieved
666 * tuple_fraction is interpreted as follows:
667 * 0: expect all tuples to be retrieved (normal case)
668 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
669 * from the plan to be retrieved
670 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
671 * expected to be retrieved (ie, a LIMIT specification)
673 * Returns a query plan. Also, root->query_pathkeys is returned as the
674 * actual output ordering of the plan (in pathkey format).
675 *--------------------
678 grouping_planner(PlannerInfo *root, double tuple_fraction)
680 Query *parse = root->parse;
681 List *tlist = parse->targetList;
682 int64 offset_est = 0;
685 List *current_pathkeys;
687 double dNumGroups = 0;
689 /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
690 if (parse->limitCount || parse->limitOffset)
691 tuple_fraction = preprocess_limit(root, tuple_fraction,
692 &offset_est, &count_est);
694 if (parse->setOperations)
696 List *set_sortclauses;
699 * If there's a top-level ORDER BY, assume we have to fetch all the
700 * tuples. This might seem too simplistic given all the hackery below
701 * to possibly avoid the sort ... but a nonzero tuple_fraction is only
702 * of use to plan_set_operations() when the setop is UNION ALL, and
703 * the result of UNION ALL is always unsorted.
705 if (parse->sortClause)
706 tuple_fraction = 0.0;
709 * Construct the plan for set operations. The result will not need
710 * any work except perhaps a top-level sort and/or LIMIT.
712 result_plan = plan_set_operations(root, tuple_fraction,
716 * Calculate pathkeys representing the sort order (if any) of the set
717 * operation's result. We have to do this before overwriting the sort
720 current_pathkeys = make_pathkeys_for_sortclauses(root,
722 result_plan->targetlist,
726 * We should not need to call preprocess_targetlist, since we must be
727 * in a SELECT query node. Instead, use the targetlist returned by
728 * plan_set_operations (since this tells whether it returned any
729 * resjunk columns!), and transfer any sort key information from the
732 Assert(parse->commandType == CMD_SELECT);
734 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
737 * Can't handle FOR UPDATE/SHARE here (parser should have checked
738 * already, but let's make sure).
742 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
743 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
746 * Calculate pathkeys that represent result ordering requirements
748 sort_pathkeys = make_pathkeys_for_sortclauses(root,
755 /* No set operations, do regular planning */
757 List *group_pathkeys;
758 AttrNumber *groupColIdx = NULL;
759 Oid *groupOperators = NULL;
760 bool need_tlist_eval = true;
766 AggClauseCounts agg_counts;
767 int numGroupCols = list_length(parse->groupClause);
768 bool use_hashed_grouping = false;
770 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
772 /* Preprocess targetlist */
773 tlist = preprocess_targetlist(root, tlist);
776 * Generate appropriate target list for subplan; may be different from
777 * tlist if grouping or aggregation is needed.
779 sub_tlist = make_subplanTargetList(root, tlist,
780 &groupColIdx, &need_tlist_eval);
783 * Calculate pathkeys that represent grouping/ordering requirements.
784 * Stash them in PlannerInfo so that query_planner can canonicalize
785 * them after EquivalenceClasses have been formed.
787 root->group_pathkeys =
788 make_pathkeys_for_sortclauses(root,
792 root->sort_pathkeys =
793 make_pathkeys_for_sortclauses(root,
799 * Will need actual number of aggregates for estimating costs.
801 * Note: we do not attempt to detect duplicate aggregates here; a
802 * somewhat-overestimated count is okay for our present purposes.
804 * Note: think not that we can turn off hasAggs if we find no aggs. It
805 * is possible for constant-expression simplification to remove all
806 * explicit references to aggs, but we still have to follow the
807 * aggregate semantics (eg, producing only one output row).
811 count_agg_clauses((Node *) tlist, &agg_counts);
812 count_agg_clauses(parse->havingQual, &agg_counts);
816 * Figure out whether we need a sorted result from query_planner.
818 * If we have a GROUP BY clause, then we want a result sorted properly
819 * for grouping. Otherwise, if there is an ORDER BY clause, we want
820 * to sort by the ORDER BY clause. (Note: if we have both, and ORDER
821 * BY is a superset of GROUP BY, it would be tempting to request sort
822 * by ORDER BY --- but that might just leave us failing to exploit an
823 * available sort order at all. Needs more thought...)
825 if (parse->groupClause)
826 root->query_pathkeys = root->group_pathkeys;
827 else if (parse->sortClause)
828 root->query_pathkeys = root->sort_pathkeys;
830 root->query_pathkeys = NIL;
833 * Generate the best unsorted and presorted paths for this Query (but
834 * note there may not be any presorted path). query_planner will also
835 * estimate the number of groups in the query, and canonicalize all
838 query_planner(root, sub_tlist, tuple_fraction,
839 &cheapest_path, &sorted_path, &dNumGroups);
841 group_pathkeys = root->group_pathkeys;
842 sort_pathkeys = root->sort_pathkeys;
845 * If grouping, extract the grouping operators and decide whether we
846 * want to use hashed grouping.
848 if (parse->groupClause)
850 groupOperators = extract_grouping_ops(parse->groupClause);
851 use_hashed_grouping =
852 choose_hashed_grouping(root, tuple_fraction,
853 cheapest_path, sorted_path,
854 groupOperators, dNumGroups,
857 /* Also convert # groups to long int --- but 'ware overflow! */
858 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
862 * Select the best path. If we are doing hashed grouping, we will
863 * always read all the input tuples, so use the cheapest-total path.
864 * Otherwise, trust query_planner's decision about which to use.
866 if (use_hashed_grouping || !sorted_path)
867 best_path = cheapest_path;
869 best_path = sorted_path;
872 * Check to see if it's possible to optimize MIN/MAX aggregates. If
873 * so, we will forget all the work we did so far to choose a "regular"
874 * path ... but we had to do it anyway to be able to tell which way is
877 result_plan = optimize_minmax_aggregates(root,
880 if (result_plan != NULL)
883 * optimize_minmax_aggregates generated the full plan, with the
884 * right tlist, and it has no sort order.
886 current_pathkeys = NIL;
891 * Normal case --- create a plan according to query_planner's
894 result_plan = create_plan(root, best_path);
895 current_pathkeys = best_path->pathkeys;
898 * create_plan() returns a plan with just a "flat" tlist of
899 * required Vars. Usually we need to insert the sub_tlist as the
900 * tlist of the top plan node. However, we can skip that if we
901 * determined that whatever query_planner chose to return will be
907 * If the top-level plan node is one that cannot do expression
908 * evaluation, we must insert a Result node to project the
911 if (!is_projection_capable_plan(result_plan))
913 result_plan = (Plan *) make_result(sub_tlist, NULL,
919 * Otherwise, just replace the subplan's flat tlist with
922 result_plan->targetlist = sub_tlist;
926 * Also, account for the cost of evaluation of the sub_tlist.
928 * Up to now, we have only been dealing with "flat" tlists,
929 * containing just Vars. So their evaluation cost is zero
930 * according to the model used by cost_qual_eval() (or if you
931 * prefer, the cost is factored into cpu_tuple_cost). Thus we
932 * can avoid accounting for tlist cost throughout
933 * query_planner() and subroutines. But now we've inserted a
934 * tlist that might contain actual operators, sub-selects, etc
935 * --- so we'd better account for its cost.
937 * Below this point, any tlist eval cost for added-on nodes
938 * should be accounted for as we create those nodes.
939 * Presently, of the node types we can add on, only Agg and
940 * Group project new tlists (the rest just copy their input
941 * tuples) --- so make_agg() and make_group() are responsible
942 * for computing the added cost.
944 cost_qual_eval(&tlist_cost, sub_tlist);
945 result_plan->startup_cost += tlist_cost.startup;
946 result_plan->total_cost += tlist_cost.startup +
947 tlist_cost.per_tuple * result_plan->plan_rows;
952 * Since we're using query_planner's tlist and not the one
953 * make_subplanTargetList calculated, we have to refigure any
954 * grouping-column indexes make_subplanTargetList computed.
956 locate_grouping_columns(root, tlist, result_plan->targetlist,
961 * Insert AGG or GROUP node if needed, plus an explicit sort step
964 * HAVING clause, if any, becomes qual of the Agg or Group node.
966 if (use_hashed_grouping)
968 /* Hashed aggregate plan --- no sort needed */
969 result_plan = (Plan *) make_agg(root,
971 (List *) parse->havingQual,
979 /* Hashed aggregation produces randomly-ordered results */
980 current_pathkeys = NIL;
982 else if (parse->hasAggs)
984 /* Plain aggregate plan --- sort if needed */
985 AggStrategy aggstrategy;
987 if (parse->groupClause)
989 if (!pathkeys_contained_in(group_pathkeys,
992 result_plan = (Plan *)
993 make_sort_from_groupcols(root,
997 current_pathkeys = group_pathkeys;
999 aggstrategy = AGG_SORTED;
1002 * The AGG node will not change the sort ordering of its
1003 * groups, so current_pathkeys describes the result too.
1008 aggstrategy = AGG_PLAIN;
1009 /* Result will be only one row anyway; no sort order */
1010 current_pathkeys = NIL;
1013 result_plan = (Plan *) make_agg(root,
1015 (List *) parse->havingQual,
1024 else if (parse->groupClause)
1027 * GROUP BY without aggregation, so insert a group node (plus
1028 * the appropriate sort node, if necessary).
1030 * Add an explicit sort if we couldn't make the path come out
1031 * the way the GROUP node needs it.
1033 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1035 result_plan = (Plan *)
1036 make_sort_from_groupcols(root,
1040 current_pathkeys = group_pathkeys;
1043 result_plan = (Plan *) make_group(root,
1045 (List *) parse->havingQual,
1051 /* The Group node won't change sort ordering */
1053 else if (root->hasHavingQual)
1056 * No aggregates, and no GROUP BY, but we have a HAVING qual.
1057 * This is a degenerate case in which we are supposed to emit
1058 * either 0 or 1 row depending on whether HAVING succeeds.
1059 * Furthermore, there cannot be any variables in either HAVING
1060 * or the targetlist, so we actually do not need the FROM
1061 * table at all! We can just throw away the plan-so-far and
1062 * generate a Result node. This is a sufficiently unusual
1063 * corner case that it's not worth contorting the structure of
1064 * this routine to avoid having to generate the plan in the
1067 result_plan = (Plan *) make_result(tlist,
1071 } /* end of non-minmax-aggregate case */
1072 } /* end of if (setOperations) */
1075 * If we were not able to make the plan come out in the right order, add
1076 * an explicit sort step.
1078 if (parse->sortClause)
1080 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1082 result_plan = (Plan *) make_sort_from_pathkeys(root,
1085 current_pathkeys = sort_pathkeys;
1090 * If there is a DISTINCT clause, add the UNIQUE node.
1092 if (parse->distinctClause)
1094 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1097 * If there was grouping or aggregation, leave plan_rows as-is (ie,
1098 * assume the result was already mostly unique). If not, use the
1099 * number of distinct-groups calculated by query_planner.
1101 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1102 result_plan->plan_rows = dNumGroups;
1106 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1108 if (parse->limitCount || parse->limitOffset)
1110 result_plan = (Plan *) make_limit(result_plan,
1118 * Deal with the RETURNING clause if any. It's convenient to pass the
1119 * returningList through setrefs.c now rather than at top level (if we
1120 * waited, handling inherited UPDATE/DELETE would be much harder).
1122 if (parse->returningList)
1126 rlist = set_returning_clause_references(parse->returningList,
1128 parse->resultRelation);
1129 parse->returningLists = list_make1(rlist);
1133 * Return the actual output ordering in query_pathkeys for possible use by
1134 * an outer query level.
1136 root->query_pathkeys = current_pathkeys;
1142 * Detect whether a plan node is a "dummy" plan created when a relation
1143 * is deemed not to need scanning due to constraint exclusion.
1145 * Currently, such dummy plans are Result nodes with constant FALSE
1149 is_dummy_plan(Plan *plan)
1151 if (IsA(plan, Result))
1153 List *rcqual = (List *) ((Result *) plan)->resconstantqual;
1155 if (list_length(rcqual) == 1)
1157 Const *constqual = (Const *) linitial(rcqual);
1159 if (constqual && IsA(constqual, Const))
1161 if (!constqual->constisnull &&
1162 !DatumGetBool(constqual->constvalue))
1171 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1173 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1174 * results back in *count_est and *offset_est. These variables are set to
1175 * 0 if the corresponding clause is not present, and -1 if it's present
1176 * but we couldn't estimate the value for it. (The "0" convention is OK
1177 * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1178 * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
1179 * usual practice of never estimating less than one row.) These values will
1180 * be passed to make_limit, which see if you change this code.
1182 * The return value is the suitably adjusted tuple_fraction to use for
1183 * planning the query. This adjustment is not overridable, since it reflects
1184 * plan actions that grouping_planner() will certainly take, not assumptions
1188 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1189 int64 *offset_est, int64 *count_est)
1191 Query *parse = root->parse;
1193 double limit_fraction;
1195 /* Should not be called unless LIMIT or OFFSET */
1196 Assert(parse->limitCount || parse->limitOffset);
1199 * Try to obtain the clause values. We use estimate_expression_value
1200 * primarily because it can sometimes do something useful with Params.
1202 if (parse->limitCount)
1204 est = estimate_expression_value(parse->limitCount);
1205 if (est && IsA(est, Const))
1207 if (((Const *) est)->constisnull)
1209 /* NULL indicates LIMIT ALL, ie, no limit */
1210 *count_est = 0; /* treat as not present */
1214 *count_est = DatumGetInt64(((Const *) est)->constvalue);
1215 if (*count_est <= 0)
1216 *count_est = 1; /* force to at least 1 */
1220 *count_est = -1; /* can't estimate */
1223 *count_est = 0; /* not present */
1225 if (parse->limitOffset)
1227 est = estimate_expression_value(parse->limitOffset);
1228 if (est && IsA(est, Const))
1230 if (((Const *) est)->constisnull)
1232 /* Treat NULL as no offset; the executor will too */
1233 *offset_est = 0; /* treat as not present */
1237 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
1238 if (*offset_est < 0)
1239 *offset_est = 0; /* less than 0 is same as 0 */
1243 *offset_est = -1; /* can't estimate */
1246 *offset_est = 0; /* not present */
1248 if (*count_est != 0)
1251 * A LIMIT clause limits the absolute number of tuples returned.
1252 * However, if it's not a constant LIMIT then we have to guess; for
1253 * lack of a better idea, assume 10% of the plan's result is wanted.
1255 if (*count_est < 0 || *offset_est < 0)
1257 /* LIMIT or OFFSET is an expression ... punt ... */
1258 limit_fraction = 0.10;
1262 /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
1263 limit_fraction = (double) *count_est + (double) *offset_est;
1267 * If we have absolute limits from both caller and LIMIT, use the
1268 * smaller value; likewise if they are both fractional. If one is
1269 * fractional and the other absolute, we can't easily determine which
1270 * is smaller, but we use the heuristic that the absolute will usually
1273 if (tuple_fraction >= 1.0)
1275 if (limit_fraction >= 1.0)
1278 tuple_fraction = Min(tuple_fraction, limit_fraction);
1282 /* caller absolute, limit fractional; use caller's value */
1285 else if (tuple_fraction > 0.0)
1287 if (limit_fraction >= 1.0)
1289 /* caller fractional, limit absolute; use limit */
1290 tuple_fraction = limit_fraction;
1294 /* both fractional */
1295 tuple_fraction = Min(tuple_fraction, limit_fraction);
1300 /* no info from caller, just use limit */
1301 tuple_fraction = limit_fraction;
1304 else if (*offset_est != 0 && tuple_fraction > 0.0)
1307 * We have an OFFSET but no LIMIT. This acts entirely differently
1308 * from the LIMIT case: here, we need to increase rather than decrease
1309 * the caller's tuple_fraction, because the OFFSET acts to cause more
1310 * tuples to be fetched instead of fewer. This only matters if we got
1311 * a tuple_fraction > 0, however.
1313 * As above, use 10% if OFFSET is present but unestimatable.
1315 if (*offset_est < 0)
1316 limit_fraction = 0.10;
1318 limit_fraction = (double) *offset_est;
1321 * If we have absolute counts from both caller and OFFSET, add them
1322 * together; likewise if they are both fractional. If one is
1323 * fractional and the other absolute, we want to take the larger, and
1324 * we heuristically assume that's the fractional one.
1326 if (tuple_fraction >= 1.0)
1328 if (limit_fraction >= 1.0)
1330 /* both absolute, so add them together */
1331 tuple_fraction += limit_fraction;
1335 /* caller absolute, limit fractional; use limit */
1336 tuple_fraction = limit_fraction;
1341 if (limit_fraction >= 1.0)
1343 /* caller fractional, limit absolute; use caller's value */
1347 /* both fractional, so add them together */
1348 tuple_fraction += limit_fraction;
1349 if (tuple_fraction >= 1.0)
1350 tuple_fraction = 0.0; /* assume fetch all */
1355 return tuple_fraction;
1359 * extract_grouping_ops - make an array of the equality operator OIDs
1360 * for the GROUP BY clause
1363 extract_grouping_ops(List *groupClause)
1365 int numCols = list_length(groupClause);
1367 Oid *groupOperators;
1370 groupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
1372 foreach(glitem, groupClause)
1374 GroupClause *groupcl = (GroupClause *) lfirst(glitem);
1376 groupOperators[colno] = get_equality_op_for_ordering_op(groupcl->sortop);
1377 if (!OidIsValid(groupOperators[colno])) /* shouldn't happen */
1378 elog(ERROR, "could not find equality operator for ordering operator %u",
1383 return groupOperators;
1387 * choose_hashed_grouping - should we use hashed grouping?
1390 choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
1391 Path *cheapest_path, Path *sorted_path,
1392 Oid *groupOperators, double dNumGroups,
1393 AggClauseCounts *agg_counts)
1395 int numGroupCols = list_length(root->parse->groupClause);
1396 double cheapest_path_rows;
1397 int cheapest_path_width;
1399 List *current_pathkeys;
1405 * Check can't-do-it conditions, including whether the grouping operators
1406 * are hashjoinable. (We assume hashing is OK if they are marked
1407 * oprcanhash. If there isn't actually a supporting hash function,
1408 * the executor will complain at runtime.)
1410 * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1411 * (Doing so would imply storing *all* the input values in the hash table,
1412 * which seems like a certain loser.)
1414 if (!enable_hashagg)
1416 if (agg_counts->numDistinctAggs != 0)
1418 for (i = 0; i < numGroupCols; i++)
1420 if (!op_hashjoinable(groupOperators[i]))
1425 * Don't do it if it doesn't look like the hashtable will fit into
1428 * Beware here of the possibility that cheapest_path->parent is NULL. This
1429 * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
1431 if (cheapest_path->parent)
1433 cheapest_path_rows = cheapest_path->parent->rows;
1434 cheapest_path_width = cheapest_path->parent->width;
1438 cheapest_path_rows = 1; /* assume non-set result */
1439 cheapest_path_width = 100; /* arbitrary */
1442 /* Estimate per-hash-entry space at tuple width... */
1443 hashentrysize = MAXALIGN(cheapest_path_width) + MAXALIGN(sizeof(MinimalTupleData));
1444 /* plus space for pass-by-ref transition values... */
1445 hashentrysize += agg_counts->transitionSpace;
1446 /* plus the per-hash-entry overhead */
1447 hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1449 if (hashentrysize * dNumGroups > work_mem * 1024L)
1453 * See if the estimated cost is no more than doing it the other way. While
1454 * avoiding the need for sorted input is usually a win, the fact that the
1455 * output won't be sorted may be a loss; so we need to do an actual cost
1458 * We need to consider cheapest_path + hashagg [+ final sort] versus
1459 * either cheapest_path [+ sort] + group or agg [+ final sort] or
1460 * presorted_path + group or agg [+ final sort] where brackets indicate a
1461 * step that may not be needed. We assume query_planner() will have
1462 * returned a presorted path only if it's a winner compared to
1463 * cheapest_path for this purpose.
1465 * These path variables are dummies that just hold cost fields; we don't
1466 * make actual Paths for these steps.
1468 cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1469 numGroupCols, dNumGroups,
1470 cheapest_path->startup_cost, cheapest_path->total_cost,
1471 cheapest_path_rows);
1472 /* Result of hashed agg is always unsorted */
1473 if (root->sort_pathkeys)
1474 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
1475 dNumGroups, cheapest_path_width);
1479 sorted_p.startup_cost = sorted_path->startup_cost;
1480 sorted_p.total_cost = sorted_path->total_cost;
1481 current_pathkeys = sorted_path->pathkeys;
1485 sorted_p.startup_cost = cheapest_path->startup_cost;
1486 sorted_p.total_cost = cheapest_path->total_cost;
1487 current_pathkeys = cheapest_path->pathkeys;
1489 if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1491 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
1492 cheapest_path_rows, cheapest_path_width);
1493 current_pathkeys = root->group_pathkeys;
1496 if (root->parse->hasAggs)
1497 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1498 numGroupCols, dNumGroups,
1499 sorted_p.startup_cost, sorted_p.total_cost,
1500 cheapest_path_rows);
1502 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1503 sorted_p.startup_cost, sorted_p.total_cost,
1504 cheapest_path_rows);
1505 /* The Agg or Group node will preserve ordering */
1506 if (root->sort_pathkeys &&
1507 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1508 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
1509 dNumGroups, cheapest_path_width);
1512 * Now make the decision using the top-level tuple fraction. First we
1513 * have to convert an absolute count (LIMIT) into fractional form.
1515 if (tuple_fraction >= 1.0)
1516 tuple_fraction /= dNumGroups;
1518 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1519 tuple_fraction) < 0)
1521 /* Hashed is cheaper, so use it */
1528 * make_subplanTargetList
1529 * Generate appropriate target list when grouping is required.
1531 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1532 * above the result of query_planner, we typically want to pass a different
1533 * target list to query_planner than the outer plan nodes should have.
1534 * This routine generates the correct target list for the subplan.
1536 * The initial target list passed from the parser already contains entries
1537 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1538 * for variables used only in HAVING clauses; so we need to add those
1539 * variables to the subplan target list. Also, we flatten all expressions
1540 * except GROUP BY items into their component variables; the other expressions
1541 * will be computed by the inserted nodes rather than by the subplan.
1542 * For example, given a query like
1543 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1544 * we want to pass this targetlist to the subplan:
1546 * where the a+b target will be used by the Sort/Group steps, and the
1547 * other targets will be used for computing the final results. (In the
1548 * above example we could theoretically suppress the a and b targets and
1549 * pass down only c,d,a+b, but it's not really worth the trouble to
1550 * eliminate simple var references from the subplan. We will avoid doing
1551 * the extra computation to recompute a+b at the outer level; see
1552 * replace_vars_with_subplan_refs() in setrefs.c.)
1554 * If we are grouping or aggregating, *and* there are no non-Var grouping
1555 * expressions, then the returned tlist is effectively dummy; we do not
1556 * need to force it to be evaluated, because all the Vars it contains
1557 * should be present in the output of query_planner anyway.
1559 * 'tlist' is the query's target list.
1560 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1561 * expressions (if there are any) in the subplan's target list.
1562 * 'need_tlist_eval' is set true if we really need to evaluate the
1565 * The result is the targetlist to be passed to the subplan.
1569 make_subplanTargetList(PlannerInfo *root,
1571 AttrNumber **groupColIdx,
1572 bool *need_tlist_eval)
1574 Query *parse = root->parse;
1579 *groupColIdx = NULL;
1582 * If we're not grouping or aggregating, there's nothing to do here;
1583 * query_planner should receive the unmodified target list.
1585 if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1587 *need_tlist_eval = true;
1592 * Otherwise, start with a "flattened" tlist (having just the vars
1593 * mentioned in the targetlist and HAVING qual --- but not upper- level
1594 * Vars; they will be replaced by Params later on).
1596 sub_tlist = flatten_tlist(tlist);
1597 extravars = pull_var_clause(parse->havingQual, false);
1598 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1599 list_free(extravars);
1600 *need_tlist_eval = false; /* only eval if not flat tlist */
1603 * If grouping, create sub_tlist entries for all GROUP BY expressions
1604 * (GROUP BY items that are simple Vars should be in the list already),
1605 * and make an array showing where the group columns are in the sub_tlist.
1607 numCols = list_length(parse->groupClause);
1611 AttrNumber *grpColIdx;
1614 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1615 *groupColIdx = grpColIdx;
1617 foreach(gl, parse->groupClause)
1619 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1620 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1621 TargetEntry *te = NULL;
1624 /* Find or make a matching sub_tlist entry */
1625 foreach(sl, sub_tlist)
1627 te = (TargetEntry *) lfirst(sl);
1628 if (equal(groupexpr, te->expr))
1633 te = makeTargetEntry((Expr *) groupexpr,
1634 list_length(sub_tlist) + 1,
1637 sub_tlist = lappend(sub_tlist, te);
1638 *need_tlist_eval = true; /* it's not flat anymore */
1641 /* and save its resno */
1642 grpColIdx[keyno++] = te->resno;
1650 * locate_grouping_columns
1651 * Locate grouping columns in the tlist chosen by query_planner.
1653 * This is only needed if we don't use the sub_tlist chosen by
1654 * make_subplanTargetList. We have to forget the column indexes found
1655 * by that routine and re-locate the grouping vars in the real sub_tlist.
1658 locate_grouping_columns(PlannerInfo *root,
1661 AttrNumber *groupColIdx)
1667 * No work unless grouping.
1669 if (!root->parse->groupClause)
1671 Assert(groupColIdx == NULL);
1674 Assert(groupColIdx != NULL);
1676 foreach(gl, root->parse->groupClause)
1678 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1679 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1680 TargetEntry *te = NULL;
1683 foreach(sl, sub_tlist)
1685 te = (TargetEntry *) lfirst(sl);
1686 if (equal(groupexpr, te->expr))
1690 elog(ERROR, "failed to locate grouping columns");
1692 groupColIdx[keyno++] = te->resno;
1697 * postprocess_setop_tlist
1698 * Fix up targetlist returned by plan_set_operations().
1700 * We need to transpose sort key info from the orig_tlist into new_tlist.
1701 * NOTE: this would not be good enough if we supported resjunk sort keys
1702 * for results of set operations --- then, we'd need to project a whole
1703 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1704 * find any resjunk columns in orig_tlist.
1707 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1710 ListCell *orig_tlist_item = list_head(orig_tlist);
1712 foreach(l, new_tlist)
1714 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1715 TargetEntry *orig_tle;
1717 /* ignore resjunk columns in setop result */
1718 if (new_tle->resjunk)
1721 Assert(orig_tlist_item != NULL);
1722 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1723 orig_tlist_item = lnext(orig_tlist_item);
1724 if (orig_tle->resjunk) /* should not happen */
1725 elog(ERROR, "resjunk output columns are not implemented");
1726 Assert(new_tle->resno == orig_tle->resno);
1727 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1729 if (orig_tlist_item != NULL)
1730 elog(ERROR, "resjunk output columns are not implemented");