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.214 2007/02/20 17:32:15 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 /* Expression kind codes for preprocess_expression */
46 #define EXPRKIND_QUAL 0
47 #define EXPRKIND_TARGET 1
48 #define EXPRKIND_RTFUNC 2
49 #define EXPRKIND_VALUES 3
50 #define EXPRKIND_LIMIT 4
51 #define EXPRKIND_ININFO 5
52 #define EXPRKIND_APPINFO 6
55 static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
56 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
57 static Plan *inheritance_planner(PlannerInfo *root);
58 static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
59 static bool is_dummy_plan(Plan *plan);
60 static double preprocess_limit(PlannerInfo *root,
61 double tuple_fraction,
62 int64 *offset_est, int64 *count_est);
63 static Oid *extract_grouping_ops(List *groupClause);
64 static bool choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
65 Path *cheapest_path, Path *sorted_path,
66 Oid *groupOperators, double dNumGroups,
67 AggClauseCounts *agg_counts);
68 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
69 AttrNumber **groupColIdx, bool *need_tlist_eval);
70 static void locate_grouping_columns(PlannerInfo *root,
73 AttrNumber *groupColIdx);
74 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
77 /*****************************************************************************
79 * Query optimizer entry point
81 *****************************************************************************/
83 planner(Query *parse, bool isCursor, int cursorOptions,
84 ParamListInfo boundParams)
88 double tuple_fraction;
93 * Set up global state for this planner invocation. This data is needed
94 * across all levels of sub-Query that might exist in the given command,
95 * so we keep it in a separate struct that's linked to by each per-Query
98 glob = makeNode(PlannerGlobal);
100 glob->boundParams = boundParams;
101 glob->paramlist = NIL;
102 glob->next_plan_id = 0;
104 /* Determine what fraction of the plan is likely to be scanned */
108 * We have no real idea how many tuples the user will ultimately FETCH
109 * from a cursor, but it seems a good bet that he doesn't want 'em
110 * all. Optimize for 10% retrieval (you gotta better number? Should
111 * this be a SETtable parameter?)
113 tuple_fraction = 0.10;
117 /* Default assumption is we need all the tuples */
118 tuple_fraction = 0.0;
121 /* primary planning entry point (may recurse for subqueries) */
122 top_plan = subquery_planner(glob, parse, 1, tuple_fraction, &root);
125 * If creating a plan for a scrollable cursor, make sure it can run
126 * backwards on demand. Add a Material node at the top at need.
128 if (isCursor && (cursorOptions & CURSOR_OPT_SCROLL))
130 if (!ExecSupportsBackwardScan(top_plan))
131 top_plan = materialize_finished_plan(top_plan);
134 /* final cleanup of the plan */
135 top_plan = set_plan_references(top_plan, parse->rtable);
137 /* build the PlannedStmt result */
138 result = makeNode(PlannedStmt);
140 result->commandType = parse->commandType;
141 result->canSetTag = parse->canSetTag;
142 result->planTree = top_plan;
143 result->rtable = parse->rtable;
144 result->resultRelations = root->resultRelations;
145 result->into = parse->into;
146 result->returningLists = root->returningLists;
147 result->rowMarks = parse->rowMarks;
148 result->nParamExec = list_length(glob->paramlist);
154 /*--------------------
156 * Invokes the planner on a subquery. We recurse to here for each
157 * sub-SELECT found in the query tree.
159 * glob is the global state for the current planner run.
160 * parse is the querytree produced by the parser & rewriter.
161 * level is the current recursion depth (1 at the top-level Query).
162 * tuple_fraction is the fraction of tuples we expect will be retrieved.
163 * tuple_fraction is interpreted as explained for grouping_planner, below.
165 * If subroot isn't NULL, we pass back the query's final PlannerInfo struct;
166 * among other things this tells the output sort ordering of the plan.
168 * Basically, this routine does the stuff that should only be done once
169 * per Query object. It then calls grouping_planner. At one time,
170 * grouping_planner could be invoked recursively on the same Query object;
171 * that's not currently true, but we keep the separation between the two
172 * routines anyway, in case we need it again someday.
174 * subquery_planner will be called recursively to handle sub-Query nodes
175 * found within the query's expressions and rangetable.
177 * Returns a query plan.
178 *--------------------
181 subquery_planner(PlannerGlobal *glob, Query *parse,
182 Index level, double tuple_fraction,
183 PlannerInfo **subroot)
185 int saved_plan_id = glob->next_plan_id;
191 /* Create a PlannerInfo data structure for this subquery */
192 root = makeNode(PlannerInfo);
195 root->query_level = level;
196 root->planner_cxt = CurrentMemoryContext;
197 root->init_plans = NIL;
198 root->eq_classes = NIL;
199 root->in_info_list = NIL;
200 root->append_rel_list = NIL;
203 * Look for IN clauses at the top level of WHERE, and transform them into
204 * joins. Note that this step only handles IN clauses originally at top
205 * level of WHERE; if we pull up any subqueries in the next step, their
206 * INs are processed just before pulling them up.
208 if (parse->hasSubLinks)
209 parse->jointree->quals = pull_up_IN_clauses(root,
210 parse->jointree->quals);
213 * Check to see if any subqueries in the rangetable can be merged into
216 parse->jointree = (FromExpr *)
217 pull_up_subqueries(root, (Node *) parse->jointree, false, false);
220 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
221 * avoid the expense of doing flatten_join_alias_vars(). Also check for
222 * outer joins --- if none, we can skip reduce_outer_joins() and some
223 * other processing. This must be done after we have done
224 * pull_up_subqueries, of course.
226 * Note: if reduce_outer_joins manages to eliminate all outer joins,
227 * root->hasOuterJoins is not reset currently. This is OK since its
228 * purpose is merely to suppress unnecessary processing in simple cases.
230 root->hasJoinRTEs = false;
231 root->hasOuterJoins = false;
232 foreach(l, parse->rtable)
234 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
236 if (rte->rtekind == RTE_JOIN)
238 root->hasJoinRTEs = true;
239 if (IS_OUTER_JOIN(rte->jointype))
241 root->hasOuterJoins = true;
242 /* Can quit scanning once we find an outer join */
249 * Expand any rangetable entries that are inheritance sets into "append
250 * relations". This can add entries to the rangetable, but they must be
251 * plain base relations not joins, so it's OK (and marginally more
252 * efficient) to do it after checking for join RTEs. We must do it after
253 * pulling up subqueries, else we'd fail to handle inherited tables in
256 expand_inherited_tables(root);
259 * Set hasHavingQual to remember if HAVING clause is present. Needed
260 * because preprocess_expression will reduce a constant-true condition to
261 * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
263 root->hasHavingQual = (parse->havingQual != NULL);
265 /* Clear this flag; might get set in distribute_qual_to_rels */
266 root->hasPseudoConstantQuals = false;
269 * Do expression preprocessing on targetlist and quals.
271 parse->targetList = (List *)
272 preprocess_expression(root, (Node *) parse->targetList,
275 parse->returningList = (List *)
276 preprocess_expression(root, (Node *) parse->returningList,
279 preprocess_qual_conditions(root, (Node *) parse->jointree);
281 parse->havingQual = preprocess_expression(root, parse->havingQual,
284 parse->limitOffset = preprocess_expression(root, parse->limitOffset,
286 parse->limitCount = preprocess_expression(root, parse->limitCount,
289 root->in_info_list = (List *)
290 preprocess_expression(root, (Node *) root->in_info_list,
292 root->append_rel_list = (List *)
293 preprocess_expression(root, (Node *) root->append_rel_list,
296 /* Also need to preprocess expressions for function and values RTEs */
297 foreach(l, parse->rtable)
299 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
301 if (rte->rtekind == RTE_FUNCTION)
302 rte->funcexpr = preprocess_expression(root, rte->funcexpr,
304 else if (rte->rtekind == RTE_VALUES)
305 rte->values_lists = (List *)
306 preprocess_expression(root, (Node *) rte->values_lists,
311 * In some cases we may want to transfer a HAVING clause into WHERE. We
312 * cannot do so if the HAVING clause contains aggregates (obviously) or
313 * volatile functions (since a HAVING clause is supposed to be executed
314 * only once per group). Also, it may be that the clause is so expensive
315 * to execute that we're better off doing it only once per group, despite
316 * the loss of selectivity. This is hard to estimate short of doing the
317 * entire planning process twice, so we use a heuristic: clauses
318 * containing subplans are left in HAVING. Otherwise, we move or copy the
319 * HAVING clause into WHERE, in hopes of eliminating tuples before
320 * aggregation instead of after.
322 * If the query has explicit grouping then we can simply move such a
323 * clause into WHERE; any group that fails the clause will not be in the
324 * output because none of its tuples will reach the grouping or
325 * aggregation stage. Otherwise we must have a degenerate (variable-free)
326 * HAVING clause, which we put in WHERE so that query_planner() can use it
327 * in a gating Result node, but also keep in HAVING to ensure that we
328 * don't emit a bogus aggregated row. (This could be done better, but it
329 * seems not worth optimizing.)
331 * Note that both havingQual and parse->jointree->quals are in
332 * implicitly-ANDed-list form at this point, even though they are declared
336 foreach(l, (List *) parse->havingQual)
338 Node *havingclause = (Node *) lfirst(l);
340 if (contain_agg_clause(havingclause) ||
341 contain_volatile_functions(havingclause) ||
342 contain_subplans(havingclause))
344 /* keep it in HAVING */
345 newHaving = lappend(newHaving, havingclause);
347 else if (parse->groupClause)
349 /* move it to WHERE */
350 parse->jointree->quals = (Node *)
351 lappend((List *) parse->jointree->quals, havingclause);
355 /* put a copy in WHERE, keep it in HAVING */
356 parse->jointree->quals = (Node *)
357 lappend((List *) parse->jointree->quals,
358 copyObject(havingclause));
359 newHaving = lappend(newHaving, havingclause);
362 parse->havingQual = (Node *) newHaving;
365 * If we have any outer joins, try to reduce them to plain inner joins.
366 * This step is most easily done after we've done expression
369 if (root->hasOuterJoins)
370 reduce_outer_joins(root);
373 * Do the main planning. If we have an inherited target relation, that
374 * needs special processing, else go straight to grouping_planner.
376 if (parse->resultRelation &&
377 rt_fetch(parse->resultRelation, parse->rtable)->inh)
378 plan = inheritance_planner(root);
380 plan = grouping_planner(root, tuple_fraction);
383 * If any subplans were generated, or if we're inside a subplan, build
384 * initPlan list and extParam/allParam sets for plan nodes, and attach the
385 * initPlans to the top plan node.
387 if (root->glob->next_plan_id != saved_plan_id || root->query_level > 1)
388 SS_finalize_plan(root, plan);
390 /* Return internal info if caller wants it */
398 * preprocess_expression
399 * Do subquery_planner's preprocessing work for an expression,
400 * which can be a targetlist, a WHERE clause (including JOIN/ON
401 * conditions), or a HAVING clause.
404 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
407 * Fall out quickly if expression is empty. This occurs often enough to
408 * be worth checking. Note that null->null is the correct conversion for
409 * implicit-AND result format, too.
415 * If the query has any join RTEs, replace join alias variables with
416 * base-relation variables. We must do this before sublink processing,
417 * else sublinks expanded out from join aliases wouldn't get processed. We
418 * can skip it in VALUES lists, however, since they can't contain any Vars
421 if (root->hasJoinRTEs && kind != EXPRKIND_VALUES)
422 expr = flatten_join_alias_vars(root, expr);
425 * Simplify constant expressions.
427 * Note: this also flattens nested AND and OR expressions into N-argument
428 * form. All processing of a qual expression after this point must be
429 * careful to maintain AND/OR flatness --- that is, do not generate a tree
430 * with AND directly under AND, nor OR directly under OR.
432 * Because this is a relatively expensive process, we skip it when the
433 * query is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()". The
434 * expression will only be evaluated once anyway, so no point in
435 * pre-simplifying; we can't execute it any faster than the executor can,
436 * and we will waste cycles copying the tree. Notice however that we
437 * still must do it for quals (to get AND/OR flatness); and if we are in a
438 * subquery we should not assume it will be done only once.
440 * For VALUES lists we never do this at all, again on the grounds that we
441 * should optimize for one-time evaluation.
443 if (kind != EXPRKIND_VALUES &&
444 (root->parse->jointree->fromlist != NIL ||
445 kind == EXPRKIND_QUAL ||
446 root->query_level > 1))
447 expr = eval_const_expressions(expr);
450 * If it's a qual or havingQual, canonicalize it.
452 if (kind == EXPRKIND_QUAL)
454 expr = (Node *) canonicalize_qual((Expr *) expr);
456 #ifdef OPTIMIZER_DEBUG
457 printf("After canonicalize_qual()\n");
462 /* Expand SubLinks to SubPlans */
463 if (root->parse->hasSubLinks)
464 expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
467 * XXX do not insert anything here unless you have grokked the comments in
468 * SS_replace_correlation_vars ...
471 /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
472 if (root->query_level > 1)
473 expr = SS_replace_correlation_vars(root, expr);
476 * If it's a qual or havingQual, convert it to implicit-AND format. (We
477 * don't want to do this before eval_const_expressions, since the latter
478 * would be unable to simplify a top-level AND correctly. Also,
479 * SS_process_sublinks expects explicit-AND format.)
481 if (kind == EXPRKIND_QUAL)
482 expr = (Node *) make_ands_implicit((Expr *) expr);
488 * preprocess_qual_conditions
489 * Recursively scan the query's jointree and do subquery_planner's
490 * preprocessing work on each qual condition found therein.
493 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
497 if (IsA(jtnode, RangeTblRef))
499 /* nothing to do here */
501 else if (IsA(jtnode, FromExpr))
503 FromExpr *f = (FromExpr *) jtnode;
506 foreach(l, f->fromlist)
507 preprocess_qual_conditions(root, lfirst(l));
509 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
511 else if (IsA(jtnode, JoinExpr))
513 JoinExpr *j = (JoinExpr *) jtnode;
515 preprocess_qual_conditions(root, j->larg);
516 preprocess_qual_conditions(root, j->rarg);
518 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
521 elog(ERROR, "unrecognized node type: %d",
522 (int) nodeTag(jtnode));
526 * inheritance_planner
527 * Generate a plan in the case where the result relation is an
530 * We have to handle this case differently from cases where a source relation
531 * is an inheritance set. Source inheritance is expanded at the bottom of the
532 * plan tree (see allpaths.c), but target inheritance has to be expanded at
533 * the top. The reason is that for UPDATE, each target relation needs a
534 * different targetlist matching its own column set. Also, for both UPDATE
535 * and DELETE, the executor needs the Append plan node at the top, else it
536 * can't keep track of which table is the current target table. Fortunately,
537 * the UPDATE/DELETE target can never be the nullable side of an outer join,
538 * so it's OK to generate the plan this way.
540 * Returns a query plan.
543 inheritance_planner(PlannerInfo *root)
545 Query *parse = root->parse;
546 int parentRTindex = parse->resultRelation;
547 List *subplans = NIL;
548 List *resultRelations = NIL;
549 List *returningLists = NIL;
555 foreach(l, root->append_rel_list)
557 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
560 /* append_rel_list contains all append rels; ignore others */
561 if (appinfo->parent_relid != parentRTindex)
565 * Generate modified query with this rel as target. We have to be
566 * prepared to translate varnos in in_info_list as well as in the
569 memcpy(&subroot, root, sizeof(PlannerInfo));
570 subroot.parse = (Query *)
571 adjust_appendrel_attrs((Node *) parse,
573 subroot.in_info_list = (List *)
574 adjust_appendrel_attrs((Node *) root->in_info_list,
576 subroot.init_plans = NIL;
577 /* There shouldn't be any OJ info to translate, as yet */
578 Assert(subroot.oj_info_list == NIL);
581 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
584 * If this child rel was excluded by constraint exclusion, exclude it
587 if (is_dummy_plan(subplan))
590 /* Save rtable and tlist from first rel for use below */
593 rtable = subroot.parse->rtable;
594 tlist = subplan->targetlist;
597 subplans = lappend(subplans, subplan);
599 /* Make sure any initplans from this rel get into the outer list */
600 root->init_plans = list_concat(root->init_plans, subroot.init_plans);
602 /* Build target-relations list for the executor */
603 resultRelations = lappend_int(resultRelations, appinfo->child_relid);
605 /* Build list of per-relation RETURNING targetlists */
606 if (parse->returningList)
608 Assert(list_length(subroot.returningLists) == 1);
609 returningLists = list_concat(returningLists,
610 subroot.returningLists);
614 root->resultRelations = resultRelations;
615 root->returningLists = returningLists;
617 /* Mark result as unordered (probably unnecessary) */
618 root->query_pathkeys = NIL;
621 * If we managed to exclude every child rel, return a dummy plan
624 return (Plan *) make_result(tlist,
625 (Node *) list_make1(makeBoolConst(false,
630 * Planning might have modified the rangetable, due to changes of the
631 * Query structures inside subquery RTEs. We have to ensure that this
632 * gets propagated back to the master copy. But can't do this until we
633 * are done planning, because all the calls to grouping_planner need
634 * virgin sub-Queries to work from. (We are effectively assuming that
635 * sub-Queries will get planned identically each time, or at least that
636 * the impacts on their rangetables will be the same each time.)
638 * XXX should clean this up someday
640 parse->rtable = rtable;
642 return (Plan *) make_append(subplans, true, tlist);
645 /*--------------------
647 * Perform planning steps related to grouping, aggregation, etc.
648 * This primarily means adding top-level processing to the basic
649 * query plan produced by query_planner.
651 * tuple_fraction is the fraction of tuples we expect will be retrieved
653 * tuple_fraction is interpreted as follows:
654 * 0: expect all tuples to be retrieved (normal case)
655 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
656 * from the plan to be retrieved
657 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
658 * expected to be retrieved (ie, a LIMIT specification)
660 * Returns a query plan. Also, root->query_pathkeys is returned as the
661 * actual output ordering of the plan (in pathkey format).
662 *--------------------
665 grouping_planner(PlannerInfo *root, double tuple_fraction)
667 Query *parse = root->parse;
668 List *tlist = parse->targetList;
669 int64 offset_est = 0;
672 List *current_pathkeys;
674 double dNumGroups = 0;
676 /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
677 if (parse->limitCount || parse->limitOffset)
678 tuple_fraction = preprocess_limit(root, tuple_fraction,
679 &offset_est, &count_est);
681 if (parse->setOperations)
683 List *set_sortclauses;
686 * If there's a top-level ORDER BY, assume we have to fetch all the
687 * tuples. This might seem too simplistic given all the hackery below
688 * to possibly avoid the sort ... but a nonzero tuple_fraction is only
689 * of use to plan_set_operations() when the setop is UNION ALL, and
690 * the result of UNION ALL is always unsorted.
692 if (parse->sortClause)
693 tuple_fraction = 0.0;
696 * Construct the plan for set operations. The result will not need
697 * any work except perhaps a top-level sort and/or LIMIT.
699 result_plan = plan_set_operations(root, tuple_fraction,
703 * Calculate pathkeys representing the sort order (if any) of the set
704 * operation's result. We have to do this before overwriting the sort
707 current_pathkeys = make_pathkeys_for_sortclauses(root,
709 result_plan->targetlist,
713 * We should not need to call preprocess_targetlist, since we must be
714 * in a SELECT query node. Instead, use the targetlist returned by
715 * plan_set_operations (since this tells whether it returned any
716 * resjunk columns!), and transfer any sort key information from the
719 Assert(parse->commandType == CMD_SELECT);
721 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
724 * Can't handle FOR UPDATE/SHARE here (parser should have checked
725 * already, but let's make sure).
729 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
730 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
733 * Calculate pathkeys that represent result ordering requirements
735 sort_pathkeys = make_pathkeys_for_sortclauses(root,
742 /* No set operations, do regular planning */
744 List *group_pathkeys;
745 AttrNumber *groupColIdx = NULL;
746 Oid *groupOperators = NULL;
747 bool need_tlist_eval = true;
753 AggClauseCounts agg_counts;
754 int numGroupCols = list_length(parse->groupClause);
755 bool use_hashed_grouping = false;
757 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
759 /* Preprocess targetlist */
760 tlist = preprocess_targetlist(root, tlist);
763 * Generate appropriate target list for subplan; may be different from
764 * tlist if grouping or aggregation is needed.
766 sub_tlist = make_subplanTargetList(root, tlist,
767 &groupColIdx, &need_tlist_eval);
770 * Calculate pathkeys that represent grouping/ordering requirements.
771 * Stash them in PlannerInfo so that query_planner can canonicalize
772 * them after EquivalenceClasses have been formed.
774 root->group_pathkeys =
775 make_pathkeys_for_sortclauses(root,
779 root->sort_pathkeys =
780 make_pathkeys_for_sortclauses(root,
786 * Will need actual number of aggregates for estimating costs.
788 * Note: we do not attempt to detect duplicate aggregates here; a
789 * somewhat-overestimated count is okay for our present purposes.
791 * Note: think not that we can turn off hasAggs if we find no aggs. It
792 * is possible for constant-expression simplification to remove all
793 * explicit references to aggs, but we still have to follow the
794 * aggregate semantics (eg, producing only one output row).
798 count_agg_clauses((Node *) tlist, &agg_counts);
799 count_agg_clauses(parse->havingQual, &agg_counts);
803 * Figure out whether we need a sorted result from query_planner.
805 * If we have a GROUP BY clause, then we want a result sorted properly
806 * for grouping. Otherwise, if there is an ORDER BY clause, we want
807 * to sort by the ORDER BY clause. (Note: if we have both, and ORDER
808 * BY is a superset of GROUP BY, it would be tempting to request sort
809 * by ORDER BY --- but that might just leave us failing to exploit an
810 * available sort order at all. Needs more thought...)
812 if (parse->groupClause)
813 root->query_pathkeys = root->group_pathkeys;
814 else if (parse->sortClause)
815 root->query_pathkeys = root->sort_pathkeys;
817 root->query_pathkeys = NIL;
820 * Generate the best unsorted and presorted paths for this Query (but
821 * note there may not be any presorted path). query_planner will also
822 * estimate the number of groups in the query, and canonicalize all
825 query_planner(root, sub_tlist, tuple_fraction,
826 &cheapest_path, &sorted_path, &dNumGroups);
828 group_pathkeys = root->group_pathkeys;
829 sort_pathkeys = root->sort_pathkeys;
832 * If grouping, extract the grouping operators and decide whether we
833 * want to use hashed grouping.
835 if (parse->groupClause)
837 groupOperators = extract_grouping_ops(parse->groupClause);
838 use_hashed_grouping =
839 choose_hashed_grouping(root, tuple_fraction,
840 cheapest_path, sorted_path,
841 groupOperators, dNumGroups,
844 /* Also convert # groups to long int --- but 'ware overflow! */
845 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
849 * Select the best path. If we are doing hashed grouping, we will
850 * always read all the input tuples, so use the cheapest-total path.
851 * Otherwise, trust query_planner's decision about which to use.
853 if (use_hashed_grouping || !sorted_path)
854 best_path = cheapest_path;
856 best_path = sorted_path;
859 * Check to see if it's possible to optimize MIN/MAX aggregates. If
860 * so, we will forget all the work we did so far to choose a "regular"
861 * path ... but we had to do it anyway to be able to tell which way is
864 result_plan = optimize_minmax_aggregates(root,
867 if (result_plan != NULL)
870 * optimize_minmax_aggregates generated the full plan, with the
871 * right tlist, and it has no sort order.
873 current_pathkeys = NIL;
878 * Normal case --- create a plan according to query_planner's
881 result_plan = create_plan(root, best_path);
882 current_pathkeys = best_path->pathkeys;
885 * create_plan() returns a plan with just a "flat" tlist of
886 * required Vars. Usually we need to insert the sub_tlist as the
887 * tlist of the top plan node. However, we can skip that if we
888 * determined that whatever query_planner chose to return will be
894 * If the top-level plan node is one that cannot do expression
895 * evaluation, we must insert a Result node to project the
898 if (!is_projection_capable_plan(result_plan))
900 result_plan = (Plan *) make_result(sub_tlist, NULL,
906 * Otherwise, just replace the subplan's flat tlist with
909 result_plan->targetlist = sub_tlist;
913 * Also, account for the cost of evaluation of the sub_tlist.
915 * Up to now, we have only been dealing with "flat" tlists,
916 * containing just Vars. So their evaluation cost is zero
917 * according to the model used by cost_qual_eval() (or if you
918 * prefer, the cost is factored into cpu_tuple_cost). Thus we
919 * can avoid accounting for tlist cost throughout
920 * query_planner() and subroutines. But now we've inserted a
921 * tlist that might contain actual operators, sub-selects, etc
922 * --- so we'd better account for its cost.
924 * Below this point, any tlist eval cost for added-on nodes
925 * should be accounted for as we create those nodes.
926 * Presently, of the node types we can add on, only Agg and
927 * Group project new tlists (the rest just copy their input
928 * tuples) --- so make_agg() and make_group() are responsible
929 * for computing the added cost.
931 cost_qual_eval(&tlist_cost, sub_tlist);
932 result_plan->startup_cost += tlist_cost.startup;
933 result_plan->total_cost += tlist_cost.startup +
934 tlist_cost.per_tuple * result_plan->plan_rows;
939 * Since we're using query_planner's tlist and not the one
940 * make_subplanTargetList calculated, we have to refigure any
941 * grouping-column indexes make_subplanTargetList computed.
943 locate_grouping_columns(root, tlist, result_plan->targetlist,
948 * Insert AGG or GROUP node if needed, plus an explicit sort step
951 * HAVING clause, if any, becomes qual of the Agg or Group node.
953 if (use_hashed_grouping)
955 /* Hashed aggregate plan --- no sort needed */
956 result_plan = (Plan *) make_agg(root,
958 (List *) parse->havingQual,
966 /* Hashed aggregation produces randomly-ordered results */
967 current_pathkeys = NIL;
969 else if (parse->hasAggs)
971 /* Plain aggregate plan --- sort if needed */
972 AggStrategy aggstrategy;
974 if (parse->groupClause)
976 if (!pathkeys_contained_in(group_pathkeys,
979 result_plan = (Plan *)
980 make_sort_from_groupcols(root,
984 current_pathkeys = group_pathkeys;
986 aggstrategy = AGG_SORTED;
989 * The AGG node will not change the sort ordering of its
990 * groups, so current_pathkeys describes the result too.
995 aggstrategy = AGG_PLAIN;
996 /* Result will be only one row anyway; no sort order */
997 current_pathkeys = NIL;
1000 result_plan = (Plan *) make_agg(root,
1002 (List *) parse->havingQual,
1011 else if (parse->groupClause)
1014 * GROUP BY without aggregation, so insert a group node (plus
1015 * the appropriate sort node, if necessary).
1017 * Add an explicit sort if we couldn't make the path come out
1018 * the way the GROUP node needs it.
1020 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1022 result_plan = (Plan *)
1023 make_sort_from_groupcols(root,
1027 current_pathkeys = group_pathkeys;
1030 result_plan = (Plan *) make_group(root,
1032 (List *) parse->havingQual,
1038 /* The Group node won't change sort ordering */
1040 else if (root->hasHavingQual)
1043 * No aggregates, and no GROUP BY, but we have a HAVING qual.
1044 * This is a degenerate case in which we are supposed to emit
1045 * either 0 or 1 row depending on whether HAVING succeeds.
1046 * Furthermore, there cannot be any variables in either HAVING
1047 * or the targetlist, so we actually do not need the FROM
1048 * table at all! We can just throw away the plan-so-far and
1049 * generate a Result node. This is a sufficiently unusual
1050 * corner case that it's not worth contorting the structure of
1051 * this routine to avoid having to generate the plan in the
1054 result_plan = (Plan *) make_result(tlist,
1058 } /* end of non-minmax-aggregate case */
1059 } /* end of if (setOperations) */
1062 * If we were not able to make the plan come out in the right order, add
1063 * an explicit sort step.
1065 if (parse->sortClause)
1067 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1069 result_plan = (Plan *) make_sort_from_pathkeys(root,
1072 current_pathkeys = sort_pathkeys;
1077 * If there is a DISTINCT clause, add the UNIQUE node.
1079 if (parse->distinctClause)
1081 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1084 * If there was grouping or aggregation, leave plan_rows as-is (ie,
1085 * assume the result was already mostly unique). If not, use the
1086 * number of distinct-groups calculated by query_planner.
1088 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1089 result_plan->plan_rows = dNumGroups;
1093 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1095 if (parse->limitCount || parse->limitOffset)
1097 result_plan = (Plan *) make_limit(result_plan,
1105 * Deal with the RETURNING clause if any. It's convenient to pass the
1106 * returningList through setrefs.c now rather than at top level (if we
1107 * waited, handling inherited UPDATE/DELETE would be much harder).
1109 if (parse->returningList)
1113 rlist = set_returning_clause_references(parse->returningList,
1115 parse->resultRelation);
1116 root->returningLists = list_make1(rlist);
1119 root->returningLists = NIL;
1121 /* Compute result-relations list if needed */
1122 if (parse->resultRelation)
1123 root->resultRelations = list_make1_int(parse->resultRelation);
1125 root->resultRelations = NIL;
1128 * Return the actual output ordering in query_pathkeys for possible use by
1129 * an outer query level.
1131 root->query_pathkeys = current_pathkeys;
1137 * Detect whether a plan node is a "dummy" plan created when a relation
1138 * is deemed not to need scanning due to constraint exclusion.
1140 * Currently, such dummy plans are Result nodes with constant FALSE
1144 is_dummy_plan(Plan *plan)
1146 if (IsA(plan, Result))
1148 List *rcqual = (List *) ((Result *) plan)->resconstantqual;
1150 if (list_length(rcqual) == 1)
1152 Const *constqual = (Const *) linitial(rcqual);
1154 if (constqual && IsA(constqual, Const))
1156 if (!constqual->constisnull &&
1157 !DatumGetBool(constqual->constvalue))
1166 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1168 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1169 * results back in *count_est and *offset_est. These variables are set to
1170 * 0 if the corresponding clause is not present, and -1 if it's present
1171 * but we couldn't estimate the value for it. (The "0" convention is OK
1172 * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1173 * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
1174 * usual practice of never estimating less than one row.) These values will
1175 * be passed to make_limit, which see if you change this code.
1177 * The return value is the suitably adjusted tuple_fraction to use for
1178 * planning the query. This adjustment is not overridable, since it reflects
1179 * plan actions that grouping_planner() will certainly take, not assumptions
1183 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1184 int64 *offset_est, int64 *count_est)
1186 Query *parse = root->parse;
1188 double limit_fraction;
1190 /* Should not be called unless LIMIT or OFFSET */
1191 Assert(parse->limitCount || parse->limitOffset);
1194 * Try to obtain the clause values. We use estimate_expression_value
1195 * primarily because it can sometimes do something useful with Params.
1197 if (parse->limitCount)
1199 est = estimate_expression_value(root, parse->limitCount);
1200 if (est && IsA(est, Const))
1202 if (((Const *) est)->constisnull)
1204 /* NULL indicates LIMIT ALL, ie, no limit */
1205 *count_est = 0; /* treat as not present */
1209 *count_est = DatumGetInt64(((Const *) est)->constvalue);
1210 if (*count_est <= 0)
1211 *count_est = 1; /* force to at least 1 */
1215 *count_est = -1; /* can't estimate */
1218 *count_est = 0; /* not present */
1220 if (parse->limitOffset)
1222 est = estimate_expression_value(root, parse->limitOffset);
1223 if (est && IsA(est, Const))
1225 if (((Const *) est)->constisnull)
1227 /* Treat NULL as no offset; the executor will too */
1228 *offset_est = 0; /* treat as not present */
1232 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
1233 if (*offset_est < 0)
1234 *offset_est = 0; /* less than 0 is same as 0 */
1238 *offset_est = -1; /* can't estimate */
1241 *offset_est = 0; /* not present */
1243 if (*count_est != 0)
1246 * A LIMIT clause limits the absolute number of tuples returned.
1247 * However, if it's not a constant LIMIT then we have to guess; for
1248 * lack of a better idea, assume 10% of the plan's result is wanted.
1250 if (*count_est < 0 || *offset_est < 0)
1252 /* LIMIT or OFFSET is an expression ... punt ... */
1253 limit_fraction = 0.10;
1257 /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
1258 limit_fraction = (double) *count_est + (double) *offset_est;
1262 * If we have absolute limits from both caller and LIMIT, use the
1263 * smaller value; likewise if they are both fractional. If one is
1264 * fractional and the other absolute, we can't easily determine which
1265 * is smaller, but we use the heuristic that the absolute will usually
1268 if (tuple_fraction >= 1.0)
1270 if (limit_fraction >= 1.0)
1273 tuple_fraction = Min(tuple_fraction, limit_fraction);
1277 /* caller absolute, limit fractional; use caller's value */
1280 else if (tuple_fraction > 0.0)
1282 if (limit_fraction >= 1.0)
1284 /* caller fractional, limit absolute; use limit */
1285 tuple_fraction = limit_fraction;
1289 /* both fractional */
1290 tuple_fraction = Min(tuple_fraction, limit_fraction);
1295 /* no info from caller, just use limit */
1296 tuple_fraction = limit_fraction;
1299 else if (*offset_est != 0 && tuple_fraction > 0.0)
1302 * We have an OFFSET but no LIMIT. This acts entirely differently
1303 * from the LIMIT case: here, we need to increase rather than decrease
1304 * the caller's tuple_fraction, because the OFFSET acts to cause more
1305 * tuples to be fetched instead of fewer. This only matters if we got
1306 * a tuple_fraction > 0, however.
1308 * As above, use 10% if OFFSET is present but unestimatable.
1310 if (*offset_est < 0)
1311 limit_fraction = 0.10;
1313 limit_fraction = (double) *offset_est;
1316 * If we have absolute counts from both caller and OFFSET, add them
1317 * together; likewise if they are both fractional. If one is
1318 * fractional and the other absolute, we want to take the larger, and
1319 * we heuristically assume that's the fractional one.
1321 if (tuple_fraction >= 1.0)
1323 if (limit_fraction >= 1.0)
1325 /* both absolute, so add them together */
1326 tuple_fraction += limit_fraction;
1330 /* caller absolute, limit fractional; use limit */
1331 tuple_fraction = limit_fraction;
1336 if (limit_fraction >= 1.0)
1338 /* caller fractional, limit absolute; use caller's value */
1342 /* both fractional, so add them together */
1343 tuple_fraction += limit_fraction;
1344 if (tuple_fraction >= 1.0)
1345 tuple_fraction = 0.0; /* assume fetch all */
1350 return tuple_fraction;
1354 * extract_grouping_ops - make an array of the equality operator OIDs
1355 * for the GROUP BY clause
1358 extract_grouping_ops(List *groupClause)
1360 int numCols = list_length(groupClause);
1362 Oid *groupOperators;
1365 groupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
1367 foreach(glitem, groupClause)
1369 GroupClause *groupcl = (GroupClause *) lfirst(glitem);
1371 groupOperators[colno] = get_equality_op_for_ordering_op(groupcl->sortop);
1372 if (!OidIsValid(groupOperators[colno])) /* shouldn't happen */
1373 elog(ERROR, "could not find equality operator for ordering operator %u",
1378 return groupOperators;
1382 * choose_hashed_grouping - should we use hashed grouping?
1385 choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
1386 Path *cheapest_path, Path *sorted_path,
1387 Oid *groupOperators, double dNumGroups,
1388 AggClauseCounts *agg_counts)
1390 int numGroupCols = list_length(root->parse->groupClause);
1391 double cheapest_path_rows;
1392 int cheapest_path_width;
1394 List *current_pathkeys;
1400 * Check can't-do-it conditions, including whether the grouping operators
1401 * are hashjoinable. (We assume hashing is OK if they are marked
1402 * oprcanhash. If there isn't actually a supporting hash function,
1403 * the executor will complain at runtime.)
1405 * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1406 * (Doing so would imply storing *all* the input values in the hash table,
1407 * which seems like a certain loser.)
1409 if (!enable_hashagg)
1411 if (agg_counts->numDistinctAggs != 0)
1413 for (i = 0; i < numGroupCols; i++)
1415 if (!op_hashjoinable(groupOperators[i]))
1420 * Don't do it if it doesn't look like the hashtable will fit into
1423 * Beware here of the possibility that cheapest_path->parent is NULL. This
1424 * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
1426 if (cheapest_path->parent)
1428 cheapest_path_rows = cheapest_path->parent->rows;
1429 cheapest_path_width = cheapest_path->parent->width;
1433 cheapest_path_rows = 1; /* assume non-set result */
1434 cheapest_path_width = 100; /* arbitrary */
1437 /* Estimate per-hash-entry space at tuple width... */
1438 hashentrysize = MAXALIGN(cheapest_path_width) + MAXALIGN(sizeof(MinimalTupleData));
1439 /* plus space for pass-by-ref transition values... */
1440 hashentrysize += agg_counts->transitionSpace;
1441 /* plus the per-hash-entry overhead */
1442 hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1444 if (hashentrysize * dNumGroups > work_mem * 1024L)
1448 * See if the estimated cost is no more than doing it the other way. While
1449 * avoiding the need for sorted input is usually a win, the fact that the
1450 * output won't be sorted may be a loss; so we need to do an actual cost
1453 * We need to consider cheapest_path + hashagg [+ final sort] versus
1454 * either cheapest_path [+ sort] + group or agg [+ final sort] or
1455 * presorted_path + group or agg [+ final sort] where brackets indicate a
1456 * step that may not be needed. We assume query_planner() will have
1457 * returned a presorted path only if it's a winner compared to
1458 * cheapest_path for this purpose.
1460 * These path variables are dummies that just hold cost fields; we don't
1461 * make actual Paths for these steps.
1463 cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1464 numGroupCols, dNumGroups,
1465 cheapest_path->startup_cost, cheapest_path->total_cost,
1466 cheapest_path_rows);
1467 /* Result of hashed agg is always unsorted */
1468 if (root->sort_pathkeys)
1469 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
1470 dNumGroups, cheapest_path_width);
1474 sorted_p.startup_cost = sorted_path->startup_cost;
1475 sorted_p.total_cost = sorted_path->total_cost;
1476 current_pathkeys = sorted_path->pathkeys;
1480 sorted_p.startup_cost = cheapest_path->startup_cost;
1481 sorted_p.total_cost = cheapest_path->total_cost;
1482 current_pathkeys = cheapest_path->pathkeys;
1484 if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1486 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
1487 cheapest_path_rows, cheapest_path_width);
1488 current_pathkeys = root->group_pathkeys;
1491 if (root->parse->hasAggs)
1492 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1493 numGroupCols, dNumGroups,
1494 sorted_p.startup_cost, sorted_p.total_cost,
1495 cheapest_path_rows);
1497 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1498 sorted_p.startup_cost, sorted_p.total_cost,
1499 cheapest_path_rows);
1500 /* The Agg or Group node will preserve ordering */
1501 if (root->sort_pathkeys &&
1502 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1503 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
1504 dNumGroups, cheapest_path_width);
1507 * Now make the decision using the top-level tuple fraction. First we
1508 * have to convert an absolute count (LIMIT) into fractional form.
1510 if (tuple_fraction >= 1.0)
1511 tuple_fraction /= dNumGroups;
1513 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1514 tuple_fraction) < 0)
1516 /* Hashed is cheaper, so use it */
1523 * make_subplanTargetList
1524 * Generate appropriate target list when grouping is required.
1526 * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1527 * above the result of query_planner, we typically want to pass a different
1528 * target list to query_planner than the outer plan nodes should have.
1529 * This routine generates the correct target list for the subplan.
1531 * The initial target list passed from the parser already contains entries
1532 * for all ORDER BY and GROUP BY expressions, but it will not have entries
1533 * for variables used only in HAVING clauses; so we need to add those
1534 * variables to the subplan target list. Also, we flatten all expressions
1535 * except GROUP BY items into their component variables; the other expressions
1536 * will be computed by the inserted nodes rather than by the subplan.
1537 * For example, given a query like
1538 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1539 * we want to pass this targetlist to the subplan:
1541 * where the a+b target will be used by the Sort/Group steps, and the
1542 * other targets will be used for computing the final results. (In the
1543 * above example we could theoretically suppress the a and b targets and
1544 * pass down only c,d,a+b, but it's not really worth the trouble to
1545 * eliminate simple var references from the subplan. We will avoid doing
1546 * the extra computation to recompute a+b at the outer level; see
1547 * replace_vars_with_subplan_refs() in setrefs.c.)
1549 * If we are grouping or aggregating, *and* there are no non-Var grouping
1550 * expressions, then the returned tlist is effectively dummy; we do not
1551 * need to force it to be evaluated, because all the Vars it contains
1552 * should be present in the output of query_planner anyway.
1554 * 'tlist' is the query's target list.
1555 * 'groupColIdx' receives an array of column numbers for the GROUP BY
1556 * expressions (if there are any) in the subplan's target list.
1557 * 'need_tlist_eval' is set true if we really need to evaluate the
1560 * The result is the targetlist to be passed to the subplan.
1564 make_subplanTargetList(PlannerInfo *root,
1566 AttrNumber **groupColIdx,
1567 bool *need_tlist_eval)
1569 Query *parse = root->parse;
1574 *groupColIdx = NULL;
1577 * If we're not grouping or aggregating, there's nothing to do here;
1578 * query_planner should receive the unmodified target list.
1580 if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1582 *need_tlist_eval = true;
1587 * Otherwise, start with a "flattened" tlist (having just the vars
1588 * mentioned in the targetlist and HAVING qual --- but not upper- level
1589 * Vars; they will be replaced by Params later on).
1591 sub_tlist = flatten_tlist(tlist);
1592 extravars = pull_var_clause(parse->havingQual, false);
1593 sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1594 list_free(extravars);
1595 *need_tlist_eval = false; /* only eval if not flat tlist */
1598 * If grouping, create sub_tlist entries for all GROUP BY expressions
1599 * (GROUP BY items that are simple Vars should be in the list already),
1600 * and make an array showing where the group columns are in the sub_tlist.
1602 numCols = list_length(parse->groupClause);
1606 AttrNumber *grpColIdx;
1609 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1610 *groupColIdx = grpColIdx;
1612 foreach(gl, parse->groupClause)
1614 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1615 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1616 TargetEntry *te = NULL;
1619 /* Find or make a matching sub_tlist entry */
1620 foreach(sl, sub_tlist)
1622 te = (TargetEntry *) lfirst(sl);
1623 if (equal(groupexpr, te->expr))
1628 te = makeTargetEntry((Expr *) groupexpr,
1629 list_length(sub_tlist) + 1,
1632 sub_tlist = lappend(sub_tlist, te);
1633 *need_tlist_eval = true; /* it's not flat anymore */
1636 /* and save its resno */
1637 grpColIdx[keyno++] = te->resno;
1645 * locate_grouping_columns
1646 * Locate grouping columns in the tlist chosen by query_planner.
1648 * This is only needed if we don't use the sub_tlist chosen by
1649 * make_subplanTargetList. We have to forget the column indexes found
1650 * by that routine and re-locate the grouping vars in the real sub_tlist.
1653 locate_grouping_columns(PlannerInfo *root,
1656 AttrNumber *groupColIdx)
1662 * No work unless grouping.
1664 if (!root->parse->groupClause)
1666 Assert(groupColIdx == NULL);
1669 Assert(groupColIdx != NULL);
1671 foreach(gl, root->parse->groupClause)
1673 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1674 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1675 TargetEntry *te = NULL;
1678 foreach(sl, sub_tlist)
1680 te = (TargetEntry *) lfirst(sl);
1681 if (equal(groupexpr, te->expr))
1685 elog(ERROR, "failed to locate grouping columns");
1687 groupColIdx[keyno++] = te->resno;
1692 * postprocess_setop_tlist
1693 * Fix up targetlist returned by plan_set_operations().
1695 * We need to transpose sort key info from the orig_tlist into new_tlist.
1696 * NOTE: this would not be good enough if we supported resjunk sort keys
1697 * for results of set operations --- then, we'd need to project a whole
1698 * new tlist to evaluate the resjunk columns. For now, just ereport if we
1699 * find any resjunk columns in orig_tlist.
1702 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1705 ListCell *orig_tlist_item = list_head(orig_tlist);
1707 foreach(l, new_tlist)
1709 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1710 TargetEntry *orig_tle;
1712 /* ignore resjunk columns in setop result */
1713 if (new_tle->resjunk)
1716 Assert(orig_tlist_item != NULL);
1717 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1718 orig_tlist_item = lnext(orig_tlist_item);
1719 if (orig_tle->resjunk) /* should not happen */
1720 elog(ERROR, "resjunk output columns are not implemented");
1721 Assert(new_tle->resno == orig_tle->resno);
1722 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1724 if (orig_tlist_item != NULL)
1725 elog(ERROR, "resjunk output columns are not implemented");