]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/planner.c
Make GROUP BY work properly for datatypes that only support hashing and not
[postgresql] / src / backend / optimizer / plan / planner.c
1 /*-------------------------------------------------------------------------
2  *
3  * planner.c
4  *        The query optimizer external interface.
5  *
6  * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/optimizer/plan/planner.c,v 1.237 2008/08/03 19:10:52 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include <limits.h>
19
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"
37 #endif
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"
43
44
45 /* GUC parameter */
46 double cursor_tuple_fraction = DEFAULT_CURSOR_TUPLE_FRACTION;
47
48 /* Hook for plugins to get control in planner() */
49 planner_hook_type planner_hook = NULL;
50
51
52 /* Expression kind codes for preprocess_expression */
53 #define EXPRKIND_QUAL           0
54 #define EXPRKIND_TARGET         1
55 #define EXPRKIND_RTFUNC         2
56 #define EXPRKIND_VALUES         3
57 #define EXPRKIND_LIMIT          4
58 #define EXPRKIND_ININFO         5
59 #define EXPRKIND_APPINFO        6
60
61
62 static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
63 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
64 static Plan *inheritance_planner(PlannerInfo *root);
65 static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
66 static bool is_dummy_plan(Plan *plan);
67 static double preprocess_limit(PlannerInfo *root,
68                                  double tuple_fraction,
69                                  int64 *offset_est, int64 *count_est);
70 static void preprocess_groupclause(PlannerInfo *root);
71 static Oid *extract_grouping_ops(List *groupClause);
72 static bool grouping_is_sortable(List *groupClause);
73 static bool grouping_is_hashable(List *groupClause);
74 static bool choose_hashed_grouping(PlannerInfo *root,
75                                            double tuple_fraction, double limit_tuples,
76                                            Path *cheapest_path, Path *sorted_path,
77                                            double dNumGroups, AggClauseCounts *agg_counts);
78 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
79                                            AttrNumber **groupColIdx, bool *need_tlist_eval);
80 static void locate_grouping_columns(PlannerInfo *root,
81                                                 List *tlist,
82                                                 List *sub_tlist,
83                                                 AttrNumber *groupColIdx);
84 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
85
86
87 /*****************************************************************************
88  *
89  *         Query optimizer entry point
90  *
91  * To support loadable plugins that monitor or modify planner behavior,
92  * we provide a hook variable that lets a plugin get control before and
93  * after the standard planning process.  The plugin would normally call
94  * standard_planner().
95  *
96  * Note to plugin authors: standard_planner() scribbles on its Query input,
97  * so you'd better copy that data structure if you want to plan more than once.
98  *
99  *****************************************************************************/
100 PlannedStmt *
101 planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
102 {
103         PlannedStmt *result;
104
105         if (planner_hook)
106                 result = (*planner_hook) (parse, cursorOptions, boundParams);
107         else
108                 result = standard_planner(parse, cursorOptions, boundParams);
109         return result;
110 }
111
112 PlannedStmt *
113 standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
114 {
115         PlannedStmt *result;
116         PlannerGlobal *glob;
117         double          tuple_fraction;
118         PlannerInfo *root;
119         Plan       *top_plan;
120         ListCell   *lp,
121                            *lr;
122
123         /* Cursor options may come from caller or from DECLARE CURSOR stmt */
124         if (parse->utilityStmt &&
125                 IsA(parse->utilityStmt, DeclareCursorStmt))
126                 cursorOptions |= ((DeclareCursorStmt *) parse->utilityStmt)->options;
127
128         /*
129          * Set up global state for this planner invocation.  This data is needed
130          * across all levels of sub-Query that might exist in the given command,
131          * so we keep it in a separate struct that's linked to by each per-Query
132          * PlannerInfo.
133          */
134         glob = makeNode(PlannerGlobal);
135
136         glob->boundParams = boundParams;
137         glob->paramlist = NIL;
138         glob->subplans = NIL;
139         glob->subrtables = NIL;
140         glob->rewindPlanIDs = NULL;
141         glob->finalrtable = NIL;
142         glob->relationOids = NIL;
143         glob->transientPlan = false;
144
145         /* Determine what fraction of the plan is likely to be scanned */
146         if (cursorOptions & CURSOR_OPT_FAST_PLAN)
147         {
148                 /*
149                  * We have no real idea how many tuples the user will ultimately FETCH
150                  * from a cursor, but it is often the case that he doesn't want 'em
151                  * all, or would prefer a fast-start plan anyway so that he can
152                  * process some of the tuples sooner.  Use a GUC parameter to decide
153                  * what fraction to optimize for.
154                  */
155                 tuple_fraction = cursor_tuple_fraction;
156
157                 /*
158                  * We document cursor_tuple_fraction as simply being a fraction,
159                  * which means the edge cases 0 and 1 have to be treated specially
160                  * here.  We convert 1 to 0 ("all the tuples") and 0 to a very small
161                  * fraction.
162                  */
163                 if (tuple_fraction >= 1.0)
164                         tuple_fraction = 0.0;
165                 else if (tuple_fraction <= 0.0)
166                         tuple_fraction = 1e-10;
167         }
168         else
169         {
170                 /* Default assumption is we need all the tuples */
171                 tuple_fraction = 0.0;
172         }
173
174         /* primary planning entry point (may recurse for subqueries) */
175         top_plan = subquery_planner(glob, parse, 1, tuple_fraction, &root);
176
177         /*
178          * If creating a plan for a scrollable cursor, make sure it can run
179          * backwards on demand.  Add a Material node at the top at need.
180          */
181         if (cursorOptions & CURSOR_OPT_SCROLL)
182         {
183                 if (!ExecSupportsBackwardScan(top_plan))
184                         top_plan = materialize_finished_plan(top_plan);
185         }
186
187         /* final cleanup of the plan */
188         Assert(glob->finalrtable == NIL);
189         top_plan = set_plan_references(glob, top_plan, root->parse->rtable);
190         /* ... and the subplans (both regular subplans and initplans) */
191         Assert(list_length(glob->subplans) == list_length(glob->subrtables));
192         forboth(lp, glob->subplans, lr, glob->subrtables)
193         {
194                 Plan       *subplan = (Plan *) lfirst(lp);
195                 List       *subrtable = (List *) lfirst(lr);
196
197                 lfirst(lp) = set_plan_references(glob, subplan, subrtable);
198         }
199
200         /* build the PlannedStmt result */
201         result = makeNode(PlannedStmt);
202
203         result->commandType = parse->commandType;
204         result->canSetTag = parse->canSetTag;
205         result->transientPlan = glob->transientPlan;
206         result->planTree = top_plan;
207         result->rtable = glob->finalrtable;
208         result->resultRelations = root->resultRelations;
209         result->utilityStmt = parse->utilityStmt;
210         result->intoClause = parse->intoClause;
211         result->subplans = glob->subplans;
212         result->rewindPlanIDs = glob->rewindPlanIDs;
213         result->returningLists = root->returningLists;
214         result->rowMarks = parse->rowMarks;
215         result->relationOids = glob->relationOids;
216         result->nParamExec = list_length(glob->paramlist);
217
218         return result;
219 }
220
221
222 /*--------------------
223  * subquery_planner
224  *        Invokes the planner on a subquery.  We recurse to here for each
225  *        sub-SELECT found in the query tree.
226  *
227  * glob is the global state for the current planner run.
228  * parse is the querytree produced by the parser & rewriter.
229  * level is the current recursion depth (1 at the top-level Query).
230  * tuple_fraction is the fraction of tuples we expect will be retrieved.
231  * tuple_fraction is interpreted as explained for grouping_planner, below.
232  *
233  * If subroot isn't NULL, we pass back the query's final PlannerInfo struct;
234  * among other things this tells the output sort ordering of the plan.
235  *
236  * Basically, this routine does the stuff that should only be done once
237  * per Query object.  It then calls grouping_planner.  At one time,
238  * grouping_planner could be invoked recursively on the same Query object;
239  * that's not currently true, but we keep the separation between the two
240  * routines anyway, in case we need it again someday.
241  *
242  * subquery_planner will be called recursively to handle sub-Query nodes
243  * found within the query's expressions and rangetable.
244  *
245  * Returns a query plan.
246  *--------------------
247  */
248 Plan *
249 subquery_planner(PlannerGlobal *glob, Query *parse,
250                                  Index level, double tuple_fraction,
251                                  PlannerInfo **subroot)
252 {
253         int                     num_old_subplans = list_length(glob->subplans);
254         PlannerInfo *root;
255         Plan       *plan;
256         List       *newHaving;
257         ListCell   *l;
258
259         /* Create a PlannerInfo data structure for this subquery */
260         root = makeNode(PlannerInfo);
261         root->parse = parse;
262         root->glob = glob;
263         root->query_level = level;
264         root->planner_cxt = CurrentMemoryContext;
265         root->init_plans = NIL;
266         root->eq_classes = NIL;
267         root->in_info_list = NIL;
268         root->append_rel_list = NIL;
269
270         /*
271          * Look for IN clauses at the top level of WHERE, and transform them into
272          * joins.  Note that this step only handles IN clauses originally at top
273          * level of WHERE; if we pull up any subqueries below, their INs are
274          * processed just before pulling them up.
275          */
276         if (parse->hasSubLinks)
277                 parse->jointree->quals = pull_up_IN_clauses(root,
278                                                                                                         parse->jointree->quals);
279
280         /*
281          * Scan the rangetable for set-returning functions, and inline them
282          * if possible (producing subqueries that might get pulled up next).
283          * Recursion issues here are handled in the same way as for IN clauses.
284          */
285         inline_set_returning_functions(root);
286
287         /*
288          * Check to see if any subqueries in the rangetable can be merged into
289          * this query.
290          */
291         parse->jointree = (FromExpr *)
292                 pull_up_subqueries(root, (Node *) parse->jointree, false, false);
293
294         /*
295          * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
296          * avoid the expense of doing flatten_join_alias_vars().  Also check for
297          * outer joins --- if none, we can skip reduce_outer_joins() and some
298          * other processing.  This must be done after we have done
299          * pull_up_subqueries, of course.
300          *
301          * Note: if reduce_outer_joins manages to eliminate all outer joins,
302          * root->hasOuterJoins is not reset currently.  This is OK since its
303          * purpose is merely to suppress unnecessary processing in simple cases.
304          */
305         root->hasJoinRTEs = false;
306         root->hasOuterJoins = false;
307         foreach(l, parse->rtable)
308         {
309                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
310
311                 if (rte->rtekind == RTE_JOIN)
312                 {
313                         root->hasJoinRTEs = true;
314                         if (IS_OUTER_JOIN(rte->jointype))
315                         {
316                                 root->hasOuterJoins = true;
317                                 /* Can quit scanning once we find an outer join */
318                                 break;
319                         }
320                 }
321         }
322
323         /*
324          * Expand any rangetable entries that are inheritance sets into "append
325          * relations".  This can add entries to the rangetable, but they must be
326          * plain base relations not joins, so it's OK (and marginally more
327          * efficient) to do it after checking for join RTEs.  We must do it after
328          * pulling up subqueries, else we'd fail to handle inherited tables in
329          * subqueries.
330          */
331         expand_inherited_tables(root);
332
333         /*
334          * Set hasHavingQual to remember if HAVING clause is present.  Needed
335          * because preprocess_expression will reduce a constant-true condition to
336          * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
337          */
338         root->hasHavingQual = (parse->havingQual != NULL);
339
340         /* Clear this flag; might get set in distribute_qual_to_rels */
341         root->hasPseudoConstantQuals = false;
342
343         /*
344          * Do expression preprocessing on targetlist and quals.
345          */
346         parse->targetList = (List *)
347                 preprocess_expression(root, (Node *) parse->targetList,
348                                                           EXPRKIND_TARGET);
349
350         parse->returningList = (List *)
351                 preprocess_expression(root, (Node *) parse->returningList,
352                                                           EXPRKIND_TARGET);
353
354         preprocess_qual_conditions(root, (Node *) parse->jointree);
355
356         parse->havingQual = preprocess_expression(root, parse->havingQual,
357                                                                                           EXPRKIND_QUAL);
358
359         parse->limitOffset = preprocess_expression(root, parse->limitOffset,
360                                                                                            EXPRKIND_LIMIT);
361         parse->limitCount = preprocess_expression(root, parse->limitCount,
362                                                                                           EXPRKIND_LIMIT);
363
364         root->in_info_list = (List *)
365                 preprocess_expression(root, (Node *) root->in_info_list,
366                                                           EXPRKIND_ININFO);
367         root->append_rel_list = (List *)
368                 preprocess_expression(root, (Node *) root->append_rel_list,
369                                                           EXPRKIND_APPINFO);
370
371         /* Also need to preprocess expressions for function and values RTEs */
372         foreach(l, parse->rtable)
373         {
374                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
375
376                 if (rte->rtekind == RTE_FUNCTION)
377                         rte->funcexpr = preprocess_expression(root, rte->funcexpr,
378                                                                                                   EXPRKIND_RTFUNC);
379                 else if (rte->rtekind == RTE_VALUES)
380                         rte->values_lists = (List *)
381                                 preprocess_expression(root, (Node *) rte->values_lists,
382                                                                           EXPRKIND_VALUES);
383         }
384
385         /*
386          * In some cases we may want to transfer a HAVING clause into WHERE. We
387          * cannot do so if the HAVING clause contains aggregates (obviously) or
388          * volatile functions (since a HAVING clause is supposed to be executed
389          * only once per group).  Also, it may be that the clause is so expensive
390          * to execute that we're better off doing it only once per group, despite
391          * the loss of selectivity.  This is hard to estimate short of doing the
392          * entire planning process twice, so we use a heuristic: clauses
393          * containing subplans are left in HAVING.      Otherwise, we move or copy the
394          * HAVING clause into WHERE, in hopes of eliminating tuples before
395          * aggregation instead of after.
396          *
397          * If the query has explicit grouping then we can simply move such a
398          * clause into WHERE; any group that fails the clause will not be in the
399          * output because none of its tuples will reach the grouping or
400          * aggregation stage.  Otherwise we must have a degenerate (variable-free)
401          * HAVING clause, which we put in WHERE so that query_planner() can use it
402          * in a gating Result node, but also keep in HAVING to ensure that we
403          * don't emit a bogus aggregated row. (This could be done better, but it
404          * seems not worth optimizing.)
405          *
406          * Note that both havingQual and parse->jointree->quals are in
407          * implicitly-ANDed-list form at this point, even though they are declared
408          * as Node *.
409          */
410         newHaving = NIL;
411         foreach(l, (List *) parse->havingQual)
412         {
413                 Node       *havingclause = (Node *) lfirst(l);
414
415                 if (contain_agg_clause(havingclause) ||
416                         contain_volatile_functions(havingclause) ||
417                         contain_subplans(havingclause))
418                 {
419                         /* keep it in HAVING */
420                         newHaving = lappend(newHaving, havingclause);
421                 }
422                 else if (parse->groupClause)
423                 {
424                         /* move it to WHERE */
425                         parse->jointree->quals = (Node *)
426                                 lappend((List *) parse->jointree->quals, havingclause);
427                 }
428                 else
429                 {
430                         /* put a copy in WHERE, keep it in HAVING */
431                         parse->jointree->quals = (Node *)
432                                 lappend((List *) parse->jointree->quals,
433                                                 copyObject(havingclause));
434                         newHaving = lappend(newHaving, havingclause);
435                 }
436         }
437         parse->havingQual = (Node *) newHaving;
438
439         /*
440          * If we have any outer joins, try to reduce them to plain inner joins.
441          * This step is most easily done after we've done expression
442          * preprocessing.
443          */
444         if (root->hasOuterJoins)
445                 reduce_outer_joins(root);
446
447         /*
448          * Do the main planning.  If we have an inherited target relation, that
449          * needs special processing, else go straight to grouping_planner.
450          */
451         if (parse->resultRelation &&
452                 rt_fetch(parse->resultRelation, parse->rtable)->inh)
453                 plan = inheritance_planner(root);
454         else
455                 plan = grouping_planner(root, tuple_fraction);
456
457         /*
458          * If any subplans were generated, or if we're inside a subplan, build
459          * initPlan list and extParam/allParam sets for plan nodes, and attach the
460          * initPlans to the top plan node.
461          */
462         if (list_length(glob->subplans) != num_old_subplans ||
463                 root->query_level > 1)
464                 SS_finalize_plan(root, plan, true);
465
466         /* Return internal info if caller wants it */
467         if (subroot)
468                 *subroot = root;
469
470         return plan;
471 }
472
473 /*
474  * preprocess_expression
475  *              Do subquery_planner's preprocessing work for an expression,
476  *              which can be a targetlist, a WHERE clause (including JOIN/ON
477  *              conditions), or a HAVING clause.
478  */
479 static Node *
480 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
481 {
482         /*
483          * Fall out quickly if expression is empty.  This occurs often enough to
484          * be worth checking.  Note that null->null is the correct conversion for
485          * implicit-AND result format, too.
486          */
487         if (expr == NULL)
488                 return NULL;
489
490         /*
491          * If the query has any join RTEs, replace join alias variables with
492          * base-relation variables. We must do this before sublink processing,
493          * else sublinks expanded out from join aliases wouldn't get processed. We
494          * can skip it in VALUES lists, however, since they can't contain any Vars
495          * at all.
496          */
497         if (root->hasJoinRTEs && kind != EXPRKIND_VALUES)
498                 expr = flatten_join_alias_vars(root, expr);
499
500         /*
501          * Simplify constant expressions.
502          *
503          * Note: this also flattens nested AND and OR expressions into N-argument
504          * form.  All processing of a qual expression after this point must be
505          * careful to maintain AND/OR flatness --- that is, do not generate a tree
506          * with AND directly under AND, nor OR directly under OR.
507          *
508          * Because this is a relatively expensive process, we skip it when the
509          * query is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()". The
510          * expression will only be evaluated once anyway, so no point in
511          * pre-simplifying; we can't execute it any faster than the executor can,
512          * and we will waste cycles copying the tree.  Notice however that we
513          * still must do it for quals (to get AND/OR flatness); and if we are in a
514          * subquery we should not assume it will be done only once.
515          *
516          * For VALUES lists we never do this at all, again on the grounds that we
517          * should optimize for one-time evaluation.
518          */
519         if (kind != EXPRKIND_VALUES &&
520                 (root->parse->jointree->fromlist != NIL ||
521                  kind == EXPRKIND_QUAL ||
522                  root->query_level > 1))
523                 expr = eval_const_expressions(root, expr);
524
525         /*
526          * If it's a qual or havingQual, canonicalize it.
527          */
528         if (kind == EXPRKIND_QUAL)
529         {
530                 expr = (Node *) canonicalize_qual((Expr *) expr);
531
532 #ifdef OPTIMIZER_DEBUG
533                 printf("After canonicalize_qual()\n");
534                 pprint(expr);
535 #endif
536         }
537
538         /* Expand SubLinks to SubPlans */
539         if (root->parse->hasSubLinks)
540                 expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
541
542         /*
543          * XXX do not insert anything here unless you have grokked the comments in
544          * SS_replace_correlation_vars ...
545          */
546
547         /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
548         if (root->query_level > 1)
549                 expr = SS_replace_correlation_vars(root, expr);
550
551         /*
552          * If it's a qual or havingQual, convert it to implicit-AND format. (We
553          * don't want to do this before eval_const_expressions, since the latter
554          * would be unable to simplify a top-level AND correctly. Also,
555          * SS_process_sublinks expects explicit-AND format.)
556          */
557         if (kind == EXPRKIND_QUAL)
558                 expr = (Node *) make_ands_implicit((Expr *) expr);
559
560         return expr;
561 }
562
563 /*
564  * preprocess_qual_conditions
565  *              Recursively scan the query's jointree and do subquery_planner's
566  *              preprocessing work on each qual condition found therein.
567  */
568 static void
569 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
570 {
571         if (jtnode == NULL)
572                 return;
573         if (IsA(jtnode, RangeTblRef))
574         {
575                 /* nothing to do here */
576         }
577         else if (IsA(jtnode, FromExpr))
578         {
579                 FromExpr   *f = (FromExpr *) jtnode;
580                 ListCell   *l;
581
582                 foreach(l, f->fromlist)
583                         preprocess_qual_conditions(root, lfirst(l));
584
585                 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
586         }
587         else if (IsA(jtnode, JoinExpr))
588         {
589                 JoinExpr   *j = (JoinExpr *) jtnode;
590
591                 preprocess_qual_conditions(root, j->larg);
592                 preprocess_qual_conditions(root, j->rarg);
593
594                 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
595         }
596         else
597                 elog(ERROR, "unrecognized node type: %d",
598                          (int) nodeTag(jtnode));
599 }
600
601 /*
602  * inheritance_planner
603  *        Generate a plan in the case where the result relation is an
604  *        inheritance set.
605  *
606  * We have to handle this case differently from cases where a source relation
607  * is an inheritance set. Source inheritance is expanded at the bottom of the
608  * plan tree (see allpaths.c), but target inheritance has to be expanded at
609  * the top.  The reason is that for UPDATE, each target relation needs a
610  * different targetlist matching its own column set.  Also, for both UPDATE
611  * and DELETE, the executor needs the Append plan node at the top, else it
612  * can't keep track of which table is the current target table.  Fortunately,
613  * the UPDATE/DELETE target can never be the nullable side of an outer join,
614  * so it's OK to generate the plan this way.
615  *
616  * Returns a query plan.
617  */
618 static Plan *
619 inheritance_planner(PlannerInfo *root)
620 {
621         Query      *parse = root->parse;
622         int                     parentRTindex = parse->resultRelation;
623         List       *subplans = NIL;
624         List       *resultRelations = NIL;
625         List       *returningLists = NIL;
626         List       *rtable = NIL;
627         List       *tlist = NIL;
628         PlannerInfo subroot;
629         ListCell   *l;
630
631         foreach(l, root->append_rel_list)
632         {
633                 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
634                 Plan       *subplan;
635
636                 /* append_rel_list contains all append rels; ignore others */
637                 if (appinfo->parent_relid != parentRTindex)
638                         continue;
639
640                 /*
641                  * Generate modified query with this rel as target.  We have to be
642                  * prepared to translate varnos in in_info_list as well as in the
643                  * Query proper.
644                  */
645                 memcpy(&subroot, root, sizeof(PlannerInfo));
646                 subroot.parse = (Query *)
647                         adjust_appendrel_attrs((Node *) parse,
648                                                                    appinfo);
649                 subroot.in_info_list = (List *)
650                         adjust_appendrel_attrs((Node *) root->in_info_list,
651                                                                    appinfo);
652                 subroot.init_plans = NIL;
653                 /* There shouldn't be any OJ info to translate, as yet */
654                 Assert(subroot.oj_info_list == NIL);
655
656                 /* Generate plan */
657                 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
658
659                 /*
660                  * If this child rel was excluded by constraint exclusion, exclude it
661                  * from the plan.
662                  */
663                 if (is_dummy_plan(subplan))
664                         continue;
665
666                 /* Save rtable and tlist from first rel for use below */
667                 if (subplans == NIL)
668                 {
669                         rtable = subroot.parse->rtable;
670                         tlist = subplan->targetlist;
671                 }
672
673                 subplans = lappend(subplans, subplan);
674
675                 /* Make sure any initplans from this rel get into the outer list */
676                 root->init_plans = list_concat(root->init_plans, subroot.init_plans);
677
678                 /* Build target-relations list for the executor */
679                 resultRelations = lappend_int(resultRelations, appinfo->child_relid);
680
681                 /* Build list of per-relation RETURNING targetlists */
682                 if (parse->returningList)
683                 {
684                         Assert(list_length(subroot.returningLists) == 1);
685                         returningLists = list_concat(returningLists,
686                                                                                  subroot.returningLists);
687                 }
688         }
689
690         root->resultRelations = resultRelations;
691         root->returningLists = returningLists;
692
693         /* Mark result as unordered (probably unnecessary) */
694         root->query_pathkeys = NIL;
695
696         /*
697          * If we managed to exclude every child rel, return a dummy plan
698          */
699         if (subplans == NIL)
700         {
701                 root->resultRelations = list_make1_int(parentRTindex);
702                 /* although dummy, it must have a valid tlist for executor */
703                 tlist = preprocess_targetlist(root, parse->targetList);
704                 return (Plan *) make_result(root,
705                                                                         tlist,
706                                                                         (Node *) list_make1(makeBoolConst(false,
707                                                                                                                                           false)),
708                                                                         NULL);
709         }
710
711         /*
712          * Planning might have modified the rangetable, due to changes of the
713          * Query structures inside subquery RTEs.  We have to ensure that this
714          * gets propagated back to the master copy.  But can't do this until we
715          * are done planning, because all the calls to grouping_planner need
716          * virgin sub-Queries to work from.  (We are effectively assuming that
717          * sub-Queries will get planned identically each time, or at least that
718          * the impacts on their rangetables will be the same each time.)
719          *
720          * XXX should clean this up someday
721          */
722         parse->rtable = rtable;
723
724         /* Suppress Append if there's only one surviving child rel */
725         if (list_length(subplans) == 1)
726                 return (Plan *) linitial(subplans);
727
728         return (Plan *) make_append(subplans, true, tlist);
729 }
730
731 /*--------------------
732  * grouping_planner
733  *        Perform planning steps related to grouping, aggregation, etc.
734  *        This primarily means adding top-level processing to the basic
735  *        query plan produced by query_planner.
736  *
737  * tuple_fraction is the fraction of tuples we expect will be retrieved
738  *
739  * tuple_fraction is interpreted as follows:
740  *        0: expect all tuples to be retrieved (normal case)
741  *        0 < tuple_fraction < 1: expect the given fraction of tuples available
742  *              from the plan to be retrieved
743  *        tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
744  *              expected to be retrieved (ie, a LIMIT specification)
745  *
746  * Returns a query plan.  Also, root->query_pathkeys is returned as the
747  * actual output ordering of the plan (in pathkey format).
748  *--------------------
749  */
750 static Plan *
751 grouping_planner(PlannerInfo *root, double tuple_fraction)
752 {
753         Query      *parse = root->parse;
754         List       *tlist = parse->targetList;
755         int64           offset_est = 0;
756         int64           count_est = 0;
757         double          limit_tuples = -1.0;
758         Plan       *result_plan;
759         List       *current_pathkeys;
760         List       *sort_pathkeys;
761         double          dNumGroups = 0;
762
763         /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
764         if (parse->limitCount || parse->limitOffset)
765         {
766                 tuple_fraction = preprocess_limit(root, tuple_fraction,
767                                                                                   &offset_est, &count_est);
768
769                 /*
770                  * If we have a known LIMIT, and don't have an unknown OFFSET, we can
771                  * estimate the effects of using a bounded sort.
772                  */
773                 if (count_est > 0 && offset_est >= 0)
774                         limit_tuples = (double) count_est + (double) offset_est;
775         }
776
777         if (parse->setOperations)
778         {
779                 List       *set_sortclauses;
780
781                 /*
782                  * If there's a top-level ORDER BY, assume we have to fetch all the
783                  * tuples.      This might seem too simplistic given all the hackery below
784                  * to possibly avoid the sort ... but a nonzero tuple_fraction is only
785                  * of use to plan_set_operations() when the setop is UNION ALL, and
786                  * the result of UNION ALL is always unsorted.
787                  */
788                 if (parse->sortClause)
789                         tuple_fraction = 0.0;
790
791                 /*
792                  * Construct the plan for set operations.  The result will not need
793                  * any work except perhaps a top-level sort and/or LIMIT.
794                  */
795                 result_plan = plan_set_operations(root, tuple_fraction,
796                                                                                   &set_sortclauses);
797
798                 /*
799                  * Calculate pathkeys representing the sort order (if any) of the set
800                  * operation's result.  We have to do this before overwriting the sort
801                  * key information...
802                  */
803                 current_pathkeys = make_pathkeys_for_sortclauses(root,
804                                                                                                                  set_sortclauses,
805                                                                                                          result_plan->targetlist,
806                                                                                                                  true);
807
808                 /*
809                  * We should not need to call preprocess_targetlist, since we must be
810                  * in a SELECT query node.      Instead, use the targetlist returned by
811                  * plan_set_operations (since this tells whether it returned any
812                  * resjunk columns!), and transfer any sort key information from the
813                  * original tlist.
814                  */
815                 Assert(parse->commandType == CMD_SELECT);
816
817                 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
818
819                 /*
820                  * Can't handle FOR UPDATE/SHARE here (parser should have checked
821                  * already, but let's make sure).
822                  */
823                 if (parse->rowMarks)
824                         ereport(ERROR,
825                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
826                                          errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
827
828                 /*
829                  * Calculate pathkeys that represent result ordering requirements
830                  */
831                 Assert(parse->distinctClause == NIL);
832                 sort_pathkeys = make_pathkeys_for_sortclauses(root,
833                                                                                                           parse->sortClause,
834                                                                                                           tlist,
835                                                                                                           true);
836         }
837         else
838         {
839                 /* No set operations, do regular planning */
840                 List       *sub_tlist;
841                 List       *group_pathkeys;
842                 AttrNumber *groupColIdx = NULL;
843                 bool            need_tlist_eval = true;
844                 QualCost        tlist_cost;
845                 Path       *cheapest_path;
846                 Path       *sorted_path;
847                 Path       *best_path;
848                 long            numGroups = 0;
849                 AggClauseCounts agg_counts;
850                 int                     numGroupCols;
851                 bool            use_hashed_grouping = false;
852
853                 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
854
855                 /* Preprocess GROUP BY clause, if any */
856                 if (parse->groupClause)
857                         preprocess_groupclause(root);
858                 numGroupCols = list_length(parse->groupClause);
859
860                 /* Preprocess targetlist */
861                 tlist = preprocess_targetlist(root, tlist);
862
863                 /*
864                  * Generate appropriate target list for subplan; may be different from
865                  * tlist if grouping or aggregation is needed.
866                  */
867                 sub_tlist = make_subplanTargetList(root, tlist,
868                                                                                    &groupColIdx, &need_tlist_eval);
869
870                 /*
871                  * Calculate pathkeys that represent grouping/ordering requirements.
872                  * Stash them in PlannerInfo so that query_planner can canonicalize
873                  * them after EquivalenceClasses have been formed.
874                  *
875                  * Note: for the moment, DISTINCT is always implemented via sort/uniq,
876                  * and we set the sort_pathkeys to be the more rigorous of the
877                  * DISTINCT and ORDER BY requirements.  This should be changed
878                  * someday, but DISTINCT ON is a bit of a problem ...
879                  */
880                 if (parse->groupClause && grouping_is_sortable(parse->groupClause))
881                         root->group_pathkeys =
882                                 make_pathkeys_for_sortclauses(root,
883                                                                                           parse->groupClause,
884                                                                                           tlist,
885                                                                                           false);
886                 else
887                         root->group_pathkeys = NIL;
888
889                 if (list_length(parse->distinctClause) > list_length(parse->sortClause))
890                         root->sort_pathkeys =
891                                 make_pathkeys_for_sortclauses(root,
892                                                                                           parse->distinctClause,
893                                                                                           tlist,
894                                                                                           false);
895                 else
896                         root->sort_pathkeys =
897                                 make_pathkeys_for_sortclauses(root,
898                                                                                           parse->sortClause,
899                                                                                           tlist,
900                                                                                           false);
901
902                 /*
903                  * Will need actual number of aggregates for estimating costs.
904                  *
905                  * Note: we do not attempt to detect duplicate aggregates here; a
906                  * somewhat-overestimated count is okay for our present purposes.
907                  *
908                  * Note: think not that we can turn off hasAggs if we find no aggs. It
909                  * is possible for constant-expression simplification to remove all
910                  * explicit references to aggs, but we still have to follow the
911                  * aggregate semantics (eg, producing only one output row).
912                  */
913                 if (parse->hasAggs)
914                 {
915                         count_agg_clauses((Node *) tlist, &agg_counts);
916                         count_agg_clauses(parse->havingQual, &agg_counts);
917                 }
918
919                 /*
920                  * Figure out whether we need a sorted result from query_planner.
921                  *
922                  * If we have a sortable GROUP BY clause, then we want a result sorted
923                  * properly for grouping.  Otherwise, if there is an ORDER BY clause,
924                  * we want to sort by the ORDER BY clause. (Note: if we have both, and
925                  * ORDER BY is a superset of GROUP BY, it would be tempting to request
926                  * sort by ORDER BY --- but that might just leave us failing to
927                  * exploit an available sort order at all. Needs more thought...)
928                  */
929                 if (root->group_pathkeys)
930                         root->query_pathkeys = root->group_pathkeys;
931                 else if (root->sort_pathkeys)
932                         root->query_pathkeys = root->sort_pathkeys;
933                 else
934                         root->query_pathkeys = NIL;
935
936                 /*
937                  * Generate the best unsorted and presorted paths for this Query (but
938                  * note there may not be any presorted path).  query_planner will also
939                  * estimate the number of groups in the query, and canonicalize all
940                  * the pathkeys.
941                  */
942                 query_planner(root, sub_tlist, tuple_fraction, limit_tuples,
943                                           &cheapest_path, &sorted_path, &dNumGroups);
944
945                 group_pathkeys = root->group_pathkeys;
946                 sort_pathkeys = root->sort_pathkeys;
947
948                 /*
949                  * If grouping, decide whether to use sorted or hashed grouping.
950                  */
951                 if (parse->groupClause)
952                 {
953                         bool    can_hash;
954                         bool    can_sort;
955
956                         /*
957                          * Executor doesn't support hashed aggregation with DISTINCT
958                          * aggregates.  (Doing so would imply storing *all* the input
959                          * values in the hash table, which seems like a certain loser.)
960                          */
961                         can_hash = (agg_counts.numDistinctAggs == 0 &&
962                                                 grouping_is_hashable(parse->groupClause));
963                         can_sort = grouping_is_sortable(parse->groupClause);
964                         if (can_hash && can_sort)
965                         {
966                                 /* we have a meaningful choice to make ... */
967                                 use_hashed_grouping =
968                                         choose_hashed_grouping(root,
969                                                                                    tuple_fraction, limit_tuples,
970                                                                                    cheapest_path, sorted_path,
971                                                                                    dNumGroups, &agg_counts);
972                         }
973                         else if (can_hash)
974                                 use_hashed_grouping = true;
975                         else if (can_sort)
976                                 use_hashed_grouping = false;
977                         else
978                                 ereport(ERROR,
979                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
980                                                  errmsg("could not implement GROUP BY"),
981                                                  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
982
983                         /* Also convert # groups to long int --- but 'ware overflow! */
984                         numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
985                 }
986
987                 /*
988                  * Select the best path.  If we are doing hashed grouping, we will
989                  * always read all the input tuples, so use the cheapest-total path.
990                  * Otherwise, trust query_planner's decision about which to use.
991                  */
992                 if (use_hashed_grouping || !sorted_path)
993                         best_path = cheapest_path;
994                 else
995                         best_path = sorted_path;
996
997                 /*
998                  * Check to see if it's possible to optimize MIN/MAX aggregates. If
999                  * so, we will forget all the work we did so far to choose a "regular"
1000                  * path ... but we had to do it anyway to be able to tell which way is
1001                  * cheaper.
1002                  */
1003                 result_plan = optimize_minmax_aggregates(root,
1004                                                                                                  tlist,
1005                                                                                                  best_path);
1006                 if (result_plan != NULL)
1007                 {
1008                         /*
1009                          * optimize_minmax_aggregates generated the full plan, with the
1010                          * right tlist, and it has no sort order.
1011                          */
1012                         current_pathkeys = NIL;
1013                 }
1014                 else
1015                 {
1016                         /*
1017                          * Normal case --- create a plan according to query_planner's
1018                          * results.
1019                          */
1020                         bool    need_sort_for_grouping = false;
1021
1022                         result_plan = create_plan(root, best_path);
1023                         current_pathkeys = best_path->pathkeys;
1024
1025                         /* Detect if we'll need an explicit sort for grouping */
1026                         if (parse->groupClause && !use_hashed_grouping &&
1027                                 !pathkeys_contained_in(group_pathkeys, current_pathkeys))
1028                         {
1029                                 need_sort_for_grouping = true;
1030                                 /*
1031                                  * Always override query_planner's tlist, so that we don't
1032                                  * sort useless data from a "physical" tlist.
1033                                  */
1034                                 need_tlist_eval = true;
1035                         }
1036
1037                         /*
1038                          * create_plan() returns a plan with just a "flat" tlist of
1039                          * required Vars.  Usually we need to insert the sub_tlist as the
1040                          * tlist of the top plan node.  However, we can skip that if we
1041                          * determined that whatever query_planner chose to return will be
1042                          * good enough.
1043                          */
1044                         if (need_tlist_eval)
1045                         {
1046                                 /*
1047                                  * If the top-level plan node is one that cannot do expression
1048                                  * evaluation, we must insert a Result node to project the
1049                                  * desired tlist.
1050                                  */
1051                                 if (!is_projection_capable_plan(result_plan))
1052                                 {
1053                                         result_plan = (Plan *) make_result(root,
1054                                                                                                            sub_tlist,
1055                                                                                                            NULL,
1056                                                                                                            result_plan);
1057                                 }
1058                                 else
1059                                 {
1060                                         /*
1061                                          * Otherwise, just replace the subplan's flat tlist with
1062                                          * the desired tlist.
1063                                          */
1064                                         result_plan->targetlist = sub_tlist;
1065                                 }
1066
1067                                 /*
1068                                  * Also, account for the cost of evaluation of the sub_tlist.
1069                                  *
1070                                  * Up to now, we have only been dealing with "flat" tlists,
1071                                  * containing just Vars.  So their evaluation cost is zero
1072                                  * according to the model used by cost_qual_eval() (or if you
1073                                  * prefer, the cost is factored into cpu_tuple_cost).  Thus we
1074                                  * can avoid accounting for tlist cost throughout
1075                                  * query_planner() and subroutines.  But now we've inserted a
1076                                  * tlist that might contain actual operators, sub-selects, etc
1077                                  * --- so we'd better account for its cost.
1078                                  *
1079                                  * Below this point, any tlist eval cost for added-on nodes
1080                                  * should be accounted for as we create those nodes.
1081                                  * Presently, of the node types we can add on, only Agg and
1082                                  * Group project new tlists (the rest just copy their input
1083                                  * tuples) --- so make_agg() and make_group() are responsible
1084                                  * for computing the added cost.
1085                                  */
1086                                 cost_qual_eval(&tlist_cost, sub_tlist, root);
1087                                 result_plan->startup_cost += tlist_cost.startup;
1088                                 result_plan->total_cost += tlist_cost.startup +
1089                                         tlist_cost.per_tuple * result_plan->plan_rows;
1090                         }
1091                         else
1092                         {
1093                                 /*
1094                                  * Since we're using query_planner's tlist and not the one
1095                                  * make_subplanTargetList calculated, we have to refigure any
1096                                  * grouping-column indexes make_subplanTargetList computed.
1097                                  */
1098                                 locate_grouping_columns(root, tlist, result_plan->targetlist,
1099                                                                                 groupColIdx);
1100                         }
1101
1102                         /*
1103                          * Insert AGG or GROUP node if needed, plus an explicit sort step
1104                          * if necessary.
1105                          *
1106                          * HAVING clause, if any, becomes qual of the Agg or Group node.
1107                          */
1108                         if (use_hashed_grouping)
1109                         {
1110                                 /* Hashed aggregate plan --- no sort needed */
1111                                 result_plan = (Plan *) make_agg(root,
1112                                                                                                 tlist,
1113                                                                                                 (List *) parse->havingQual,
1114                                                                                                 AGG_HASHED,
1115                                                                                                 numGroupCols,
1116                                                                                                 groupColIdx,
1117                                                                         extract_grouping_ops(parse->groupClause),
1118                                                                                                 numGroups,
1119                                                                                                 agg_counts.numAggs,
1120                                                                                                 result_plan);
1121                                 /* Hashed aggregation produces randomly-ordered results */
1122                                 current_pathkeys = NIL;
1123                         }
1124                         else if (parse->hasAggs)
1125                         {
1126                                 /* Plain aggregate plan --- sort if needed */
1127                                 AggStrategy aggstrategy;
1128
1129                                 if (parse->groupClause)
1130                                 {
1131                                         if (need_sort_for_grouping)
1132                                         {
1133                                                 result_plan = (Plan *)
1134                                                         make_sort_from_groupcols(root,
1135                                                                                                          parse->groupClause,
1136                                                                                                          groupColIdx,
1137                                                                                                          result_plan);
1138                                                 current_pathkeys = group_pathkeys;
1139                                         }
1140                                         aggstrategy = AGG_SORTED;
1141
1142                                         /*
1143                                          * The AGG node will not change the sort ordering of its
1144                                          * groups, so current_pathkeys describes the result too.
1145                                          */
1146                                 }
1147                                 else
1148                                 {
1149                                         aggstrategy = AGG_PLAIN;
1150                                         /* Result will be only one row anyway; no sort order */
1151                                         current_pathkeys = NIL;
1152                                 }
1153
1154                                 result_plan = (Plan *) make_agg(root,
1155                                                                                                 tlist,
1156                                                                                                 (List *) parse->havingQual,
1157                                                                                                 aggstrategy,
1158                                                                                                 numGroupCols,
1159                                                                                                 groupColIdx,
1160                                                                         extract_grouping_ops(parse->groupClause),
1161                                                                                                 numGroups,
1162                                                                                                 agg_counts.numAggs,
1163                                                                                                 result_plan);
1164                         }
1165                         else if (parse->groupClause)
1166                         {
1167                                 /*
1168                                  * GROUP BY without aggregation, so insert a group node (plus
1169                                  * the appropriate sort node, if necessary).
1170                                  *
1171                                  * Add an explicit sort if we couldn't make the path come out
1172                                  * the way the GROUP node needs it.
1173                                  */
1174                                 if (need_sort_for_grouping)
1175                                 {
1176                                         result_plan = (Plan *)
1177                                                 make_sort_from_groupcols(root,
1178                                                                                                  parse->groupClause,
1179                                                                                                  groupColIdx,
1180                                                                                                  result_plan);
1181                                         current_pathkeys = group_pathkeys;
1182                                 }
1183
1184                                 result_plan = (Plan *) make_group(root,
1185                                                                                                   tlist,
1186                                                                                                   (List *) parse->havingQual,
1187                                                                                                   numGroupCols,
1188                                                                                                   groupColIdx,
1189                                                                         extract_grouping_ops(parse->groupClause),
1190                                                                                                   dNumGroups,
1191                                                                                                   result_plan);
1192                                 /* The Group node won't change sort ordering */
1193                         }
1194                         else if (root->hasHavingQual)
1195                         {
1196                                 /*
1197                                  * No aggregates, and no GROUP BY, but we have a HAVING qual.
1198                                  * This is a degenerate case in which we are supposed to emit
1199                                  * either 0 or 1 row depending on whether HAVING succeeds.
1200                                  * Furthermore, there cannot be any variables in either HAVING
1201                                  * or the targetlist, so we actually do not need the FROM
1202                                  * table at all!  We can just throw away the plan-so-far and
1203                                  * generate a Result node.      This is a sufficiently unusual
1204                                  * corner case that it's not worth contorting the structure of
1205                                  * this routine to avoid having to generate the plan in the
1206                                  * first place.
1207                                  */
1208                                 result_plan = (Plan *) make_result(root,
1209                                                                                                    tlist,
1210                                                                                                    parse->havingQual,
1211                                                                                                    NULL);
1212                         }
1213                 }                                               /* end of non-minmax-aggregate case */
1214         }                                                       /* end of if (setOperations) */
1215
1216         /*
1217          * If we were not able to make the plan come out in the right order, add
1218          * an explicit sort step.
1219          */
1220         if (sort_pathkeys)
1221         {
1222                 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1223                 {
1224                         result_plan = (Plan *) make_sort_from_pathkeys(root,
1225                                                                                                                    result_plan,
1226                                                                                                                    sort_pathkeys,
1227                                                                                                                    limit_tuples);
1228                         current_pathkeys = sort_pathkeys;
1229                 }
1230         }
1231
1232         /*
1233          * If there is a DISTINCT clause, add the UNIQUE node.
1234          */
1235         if (parse->distinctClause)
1236         {
1237                 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1238
1239                 /*
1240                  * If there was grouping or aggregation, leave plan_rows as-is (ie,
1241                  * assume the result was already mostly unique).  If not, use the
1242                  * number of distinct-groups calculated by query_planner.
1243                  */
1244                 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1245                         result_plan->plan_rows = dNumGroups;
1246         }
1247
1248         /*
1249          * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1250          */
1251         if (parse->limitCount || parse->limitOffset)
1252         {
1253                 result_plan = (Plan *) make_limit(result_plan,
1254                                                                                   parse->limitOffset,
1255                                                                                   parse->limitCount,
1256                                                                                   offset_est,
1257                                                                                   count_est);
1258         }
1259
1260         /*
1261          * Deal with the RETURNING clause if any.  It's convenient to pass the
1262          * returningList through setrefs.c now rather than at top level (if we
1263          * waited, handling inherited UPDATE/DELETE would be much harder).
1264          */
1265         if (parse->returningList)
1266         {
1267                 List       *rlist;
1268
1269                 Assert(parse->resultRelation);
1270                 rlist = set_returning_clause_references(root->glob,
1271                                                                                                 parse->returningList,
1272                                                                                                 result_plan,
1273                                                                                                 parse->resultRelation);
1274                 root->returningLists = list_make1(rlist);
1275         }
1276         else
1277                 root->returningLists = NIL;
1278
1279         /* Compute result-relations list if needed */
1280         if (parse->resultRelation)
1281                 root->resultRelations = list_make1_int(parse->resultRelation);
1282         else
1283                 root->resultRelations = NIL;
1284
1285         /*
1286          * Return the actual output ordering in query_pathkeys for possible use by
1287          * an outer query level.
1288          */
1289         root->query_pathkeys = current_pathkeys;
1290
1291         return result_plan;
1292 }
1293
1294 /*
1295  * Detect whether a plan node is a "dummy" plan created when a relation
1296  * is deemed not to need scanning due to constraint exclusion.
1297  *
1298  * Currently, such dummy plans are Result nodes with constant FALSE
1299  * filter quals.
1300  */
1301 static bool
1302 is_dummy_plan(Plan *plan)
1303 {
1304         if (IsA(plan, Result))
1305         {
1306                 List       *rcqual = (List *) ((Result *) plan)->resconstantqual;
1307
1308                 if (list_length(rcqual) == 1)
1309                 {
1310                         Const      *constqual = (Const *) linitial(rcqual);
1311
1312                         if (constqual && IsA(constqual, Const))
1313                         {
1314                                 if (!constqual->constisnull &&
1315                                         !DatumGetBool(constqual->constvalue))
1316                                         return true;
1317                         }
1318                 }
1319         }
1320         return false;
1321 }
1322
1323 /*
1324  * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1325  *
1326  * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1327  * results back in *count_est and *offset_est.  These variables are set to
1328  * 0 if the corresponding clause is not present, and -1 if it's present
1329  * but we couldn't estimate the value for it.  (The "0" convention is OK
1330  * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1331  * LIMIT 0 as though it were LIMIT 1.  But this is in line with the planner's
1332  * usual practice of never estimating less than one row.)  These values will
1333  * be passed to make_limit, which see if you change this code.
1334  *
1335  * The return value is the suitably adjusted tuple_fraction to use for
1336  * planning the query.  This adjustment is not overridable, since it reflects
1337  * plan actions that grouping_planner() will certainly take, not assumptions
1338  * about context.
1339  */
1340 static double
1341 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1342                                  int64 *offset_est, int64 *count_est)
1343 {
1344         Query      *parse = root->parse;
1345         Node       *est;
1346         double          limit_fraction;
1347
1348         /* Should not be called unless LIMIT or OFFSET */
1349         Assert(parse->limitCount || parse->limitOffset);
1350
1351         /*
1352          * Try to obtain the clause values.  We use estimate_expression_value
1353          * primarily because it can sometimes do something useful with Params.
1354          */
1355         if (parse->limitCount)
1356         {
1357                 est = estimate_expression_value(root, parse->limitCount);
1358                 if (est && IsA(est, Const))
1359                 {
1360                         if (((Const *) est)->constisnull)
1361                         {
1362                                 /* NULL indicates LIMIT ALL, ie, no limit */
1363                                 *count_est = 0; /* treat as not present */
1364                         }
1365                         else
1366                         {
1367                                 *count_est = DatumGetInt64(((Const *) est)->constvalue);
1368                                 if (*count_est <= 0)
1369                                         *count_est = 1;         /* force to at least 1 */
1370                         }
1371                 }
1372                 else
1373                         *count_est = -1;        /* can't estimate */
1374         }
1375         else
1376                 *count_est = 0;                 /* not present */
1377
1378         if (parse->limitOffset)
1379         {
1380                 est = estimate_expression_value(root, parse->limitOffset);
1381                 if (est && IsA(est, Const))
1382                 {
1383                         if (((Const *) est)->constisnull)
1384                         {
1385                                 /* Treat NULL as no offset; the executor will too */
1386                                 *offset_est = 0;        /* treat as not present */
1387                         }
1388                         else
1389                         {
1390                                 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
1391                                 if (*offset_est < 0)
1392                                         *offset_est = 0;        /* less than 0 is same as 0 */
1393                         }
1394                 }
1395                 else
1396                         *offset_est = -1;       /* can't estimate */
1397         }
1398         else
1399                 *offset_est = 0;                /* not present */
1400
1401         if (*count_est != 0)
1402         {
1403                 /*
1404                  * A LIMIT clause limits the absolute number of tuples returned.
1405                  * However, if it's not a constant LIMIT then we have to guess; for
1406                  * lack of a better idea, assume 10% of the plan's result is wanted.
1407                  */
1408                 if (*count_est < 0 || *offset_est < 0)
1409                 {
1410                         /* LIMIT or OFFSET is an expression ... punt ... */
1411                         limit_fraction = 0.10;
1412                 }
1413                 else
1414                 {
1415                         /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
1416                         limit_fraction = (double) *count_est + (double) *offset_est;
1417                 }
1418
1419                 /*
1420                  * If we have absolute limits from both caller and LIMIT, use the
1421                  * smaller value; likewise if they are both fractional.  If one is
1422                  * fractional and the other absolute, we can't easily determine which
1423                  * is smaller, but we use the heuristic that the absolute will usually
1424                  * be smaller.
1425                  */
1426                 if (tuple_fraction >= 1.0)
1427                 {
1428                         if (limit_fraction >= 1.0)
1429                         {
1430                                 /* both absolute */
1431                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
1432                         }
1433                         else
1434                         {
1435                                 /* caller absolute, limit fractional; use caller's value */
1436                         }
1437                 }
1438                 else if (tuple_fraction > 0.0)
1439                 {
1440                         if (limit_fraction >= 1.0)
1441                         {
1442                                 /* caller fractional, limit absolute; use limit */
1443                                 tuple_fraction = limit_fraction;
1444                         }
1445                         else
1446                         {
1447                                 /* both fractional */
1448                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
1449                         }
1450                 }
1451                 else
1452                 {
1453                         /* no info from caller, just use limit */
1454                         tuple_fraction = limit_fraction;
1455                 }
1456         }
1457         else if (*offset_est != 0 && tuple_fraction > 0.0)
1458         {
1459                 /*
1460                  * We have an OFFSET but no LIMIT.      This acts entirely differently
1461                  * from the LIMIT case: here, we need to increase rather than decrease
1462                  * the caller's tuple_fraction, because the OFFSET acts to cause more
1463                  * tuples to be fetched instead of fewer.  This only matters if we got
1464                  * a tuple_fraction > 0, however.
1465                  *
1466                  * As above, use 10% if OFFSET is present but unestimatable.
1467                  */
1468                 if (*offset_est < 0)
1469                         limit_fraction = 0.10;
1470                 else
1471                         limit_fraction = (double) *offset_est;
1472
1473                 /*
1474                  * If we have absolute counts from both caller and OFFSET, add them
1475                  * together; likewise if they are both fractional.      If one is
1476                  * fractional and the other absolute, we want to take the larger, and
1477                  * we heuristically assume that's the fractional one.
1478                  */
1479                 if (tuple_fraction >= 1.0)
1480                 {
1481                         if (limit_fraction >= 1.0)
1482                         {
1483                                 /* both absolute, so add them together */
1484                                 tuple_fraction += limit_fraction;
1485                         }
1486                         else
1487                         {
1488                                 /* caller absolute, limit fractional; use limit */
1489                                 tuple_fraction = limit_fraction;
1490                         }
1491                 }
1492                 else
1493                 {
1494                         if (limit_fraction >= 1.0)
1495                         {
1496                                 /* caller fractional, limit absolute; use caller's value */
1497                         }
1498                         else
1499                         {
1500                                 /* both fractional, so add them together */
1501                                 tuple_fraction += limit_fraction;
1502                                 if (tuple_fraction >= 1.0)
1503                                         tuple_fraction = 0.0;           /* assume fetch all */
1504                         }
1505                 }
1506         }
1507
1508         return tuple_fraction;
1509 }
1510
1511
1512 /*
1513  * preprocess_groupclause - do preparatory work on GROUP BY clause
1514  *
1515  * The idea here is to adjust the ordering of the GROUP BY elements
1516  * (which in itself is semantically insignificant) to match ORDER BY,
1517  * thereby allowing a single sort operation to both implement the ORDER BY
1518  * requirement and set up for a Unique step that implements GROUP BY.
1519  *
1520  * In principle it might be interesting to consider other orderings of the
1521  * GROUP BY elements, which could match the sort ordering of other
1522  * possible plans (eg an indexscan) and thereby reduce cost.  We don't
1523  * bother with that, though.  Hashed grouping will frequently win anyway.
1524  *
1525  * Note: we need no comparable processing of the distinctClause because
1526  * the parser already enforced that that matches ORDER BY.
1527  */
1528 static void
1529 preprocess_groupclause(PlannerInfo *root)
1530 {
1531         Query      *parse = root->parse;
1532         List       *new_groupclause;
1533         bool            partial_match;
1534         ListCell   *sl;
1535         ListCell   *gl;
1536
1537         /* If no ORDER BY, nothing useful to do here */
1538         if (parse->sortClause == NIL)
1539                 return;
1540
1541         /*
1542          * Scan the ORDER BY clause and construct a list of matching GROUP BY
1543          * items, but only as far as we can make a matching prefix.
1544          *
1545          * This code assumes that the sortClause contains no duplicate items.
1546          */
1547         new_groupclause = NIL;
1548         foreach(sl, parse->sortClause)
1549         {
1550                 SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
1551
1552                 foreach(gl, parse->groupClause)
1553                 {
1554                         SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
1555
1556                         if (equal(gc, sc))
1557                         {
1558                                 new_groupclause = lappend(new_groupclause, gc);
1559                                 break;
1560                         }
1561                 }
1562                 if (gl == NULL)
1563                         break;                          /* no match, so stop scanning */
1564         }
1565
1566         /* Did we match all of the ORDER BY list, or just some of it? */
1567         partial_match = (sl != NULL);
1568
1569         /* If no match at all, no point in reordering GROUP BY */
1570         if (new_groupclause == NIL)
1571                 return;
1572
1573         /*
1574          * Add any remaining GROUP BY items to the new list, but only if we
1575          * were able to make a complete match.  In other words, we only
1576          * rearrange the GROUP BY list if the result is that one list is a
1577          * prefix of the other --- otherwise there's no possibility of a
1578          * common sort.  Also, give up if there are any non-sortable GROUP BY
1579          * items, since then there's no hope anyway.
1580          */
1581         foreach(gl, parse->groupClause)
1582         {
1583                 SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
1584
1585                 if (list_member_ptr(new_groupclause, gc))
1586                         continue;                       /* it matched an ORDER BY item */
1587                 if (partial_match)
1588                         return;                         /* give up, no common sort possible */
1589                 if (!OidIsValid(gc->sortop))
1590                         return;                         /* give up, GROUP BY can't be sorted */
1591                 new_groupclause = lappend(new_groupclause, gc);
1592         }
1593
1594         /* Success --- install the rearranged GROUP BY list */
1595         Assert(list_length(parse->groupClause) == list_length(new_groupclause));
1596         parse->groupClause = new_groupclause;
1597 }
1598
1599 /*
1600  * extract_grouping_ops - make an array of the equality operator OIDs
1601  *              for a SortGroupClause list
1602  */
1603 static Oid *
1604 extract_grouping_ops(List *groupClause)
1605 {
1606         int                     numCols = list_length(groupClause);
1607         int                     colno = 0;
1608         Oid                *groupOperators;
1609         ListCell   *glitem;
1610
1611         groupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
1612
1613         foreach(glitem, groupClause)
1614         {
1615                 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1616
1617                 groupOperators[colno] = groupcl->eqop;
1618                 Assert(OidIsValid(groupOperators[colno]));
1619                 colno++;
1620         }
1621
1622         return groupOperators;
1623 }
1624
1625 /*
1626  * grouping_is_sortable - is it possible to implement grouping list by sorting?
1627  *
1628  * This is easy since the parser will have included a sortop if one exists.
1629  */
1630 static bool
1631 grouping_is_sortable(List *groupClause)
1632 {
1633         ListCell   *glitem;
1634
1635         foreach(glitem, groupClause)
1636         {
1637                 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1638
1639                 if (!OidIsValid(groupcl->sortop))
1640                         return false;
1641         }
1642         return true;
1643 }
1644
1645 /*
1646  * grouping_is_hashable - is it possible to implement grouping list by hashing?
1647  *
1648  * We assume hashing is OK if the equality operators are marked oprcanhash.
1649  * (If there isn't actually a supporting hash function, the executor will
1650  * complain at runtime; but this is a misdeclaration of the operator, not
1651  * a system bug.)
1652  */
1653 static bool
1654 grouping_is_hashable(List *groupClause)
1655 {
1656         ListCell   *glitem;
1657
1658         foreach(glitem, groupClause)
1659         {
1660                 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1661
1662                 if (!op_hashjoinable(groupcl->eqop))
1663                         return false;
1664         }
1665         return true;
1666 }
1667
1668 /*
1669  * choose_hashed_grouping - should we use hashed grouping?
1670  *
1671  * Note: this is only applied when both alternatives are actually feasible.
1672  */
1673 static bool
1674 choose_hashed_grouping(PlannerInfo *root,
1675                                            double tuple_fraction, double limit_tuples,
1676                                            Path *cheapest_path, Path *sorted_path,
1677                                            double dNumGroups, AggClauseCounts *agg_counts)
1678 {
1679         int                     numGroupCols = list_length(root->parse->groupClause);
1680         double          cheapest_path_rows;
1681         int                     cheapest_path_width;
1682         Size            hashentrysize;
1683         List       *current_pathkeys;
1684         Path            hashed_p;
1685         Path            sorted_p;
1686
1687         /* Prefer sorting when enable_hashagg is off */
1688         if (!enable_hashagg)
1689                 return false;
1690
1691         /*
1692          * Don't do it if it doesn't look like the hashtable will fit into
1693          * work_mem.
1694          *
1695          * Beware here of the possibility that cheapest_path->parent is NULL. This
1696          * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
1697          */
1698         if (cheapest_path->parent)
1699         {
1700                 cheapest_path_rows = cheapest_path->parent->rows;
1701                 cheapest_path_width = cheapest_path->parent->width;
1702         }
1703         else
1704         {
1705                 cheapest_path_rows = 1; /* assume non-set result */
1706                 cheapest_path_width = 100;              /* arbitrary */
1707         }
1708
1709         /* Estimate per-hash-entry space at tuple width... */
1710         hashentrysize = MAXALIGN(cheapest_path_width) + MAXALIGN(sizeof(MinimalTupleData));
1711         /* plus space for pass-by-ref transition values... */
1712         hashentrysize += agg_counts->transitionSpace;
1713         /* plus the per-hash-entry overhead */
1714         hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1715
1716         if (hashentrysize * dNumGroups > work_mem * 1024L)
1717                 return false;
1718
1719         /*
1720          * See if the estimated cost is no more than doing it the other way. While
1721          * avoiding the need for sorted input is usually a win, the fact that the
1722          * output won't be sorted may be a loss; so we need to do an actual cost
1723          * comparison.
1724          *
1725          * We need to consider cheapest_path + hashagg [+ final sort] versus
1726          * either cheapest_path [+ sort] + group or agg [+ final sort] or
1727          * presorted_path + group or agg [+ final sort] where brackets indicate a
1728          * step that may not be needed. We assume query_planner() will have
1729          * returned a presorted path only if it's a winner compared to
1730          * cheapest_path for this purpose.
1731          *
1732          * These path variables are dummies that just hold cost fields; we don't
1733          * make actual Paths for these steps.
1734          */
1735         cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1736                          numGroupCols, dNumGroups,
1737                          cheapest_path->startup_cost, cheapest_path->total_cost,
1738                          cheapest_path_rows);
1739         /* Result of hashed agg is always unsorted */
1740         if (root->sort_pathkeys)
1741                 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
1742                                   dNumGroups, cheapest_path_width, limit_tuples);
1743
1744         if (sorted_path)
1745         {
1746                 sorted_p.startup_cost = sorted_path->startup_cost;
1747                 sorted_p.total_cost = sorted_path->total_cost;
1748                 current_pathkeys = sorted_path->pathkeys;
1749         }
1750         else
1751         {
1752                 sorted_p.startup_cost = cheapest_path->startup_cost;
1753                 sorted_p.total_cost = cheapest_path->total_cost;
1754                 current_pathkeys = cheapest_path->pathkeys;
1755         }
1756         if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1757         {
1758                 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
1759                                   cheapest_path_rows, cheapest_path_width, -1.0);
1760                 current_pathkeys = root->group_pathkeys;
1761         }
1762
1763         if (root->parse->hasAggs)
1764                 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1765                                  numGroupCols, dNumGroups,
1766                                  sorted_p.startup_cost, sorted_p.total_cost,
1767                                  cheapest_path_rows);
1768         else
1769                 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1770                                    sorted_p.startup_cost, sorted_p.total_cost,
1771                                    cheapest_path_rows);
1772         /* The Agg or Group node will preserve ordering */
1773         if (root->sort_pathkeys &&
1774                 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1775                 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
1776                                   dNumGroups, cheapest_path_width, limit_tuples);
1777
1778         /*
1779          * Now make the decision using the top-level tuple fraction.  First we
1780          * have to convert an absolute count (LIMIT) into fractional form.
1781          */
1782         if (tuple_fraction >= 1.0)
1783                 tuple_fraction /= dNumGroups;
1784
1785         if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1786                                                                           tuple_fraction) < 0)
1787         {
1788                 /* Hashed is cheaper, so use it */
1789                 return true;
1790         }
1791         return false;
1792 }
1793
1794 /*---------------
1795  * make_subplanTargetList
1796  *        Generate appropriate target list when grouping is required.
1797  *
1798  * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1799  * above the result of query_planner, we typically want to pass a different
1800  * target list to query_planner than the outer plan nodes should have.
1801  * This routine generates the correct target list for the subplan.
1802  *
1803  * The initial target list passed from the parser already contains entries
1804  * for all ORDER BY and GROUP BY expressions, but it will not have entries
1805  * for variables used only in HAVING clauses; so we need to add those
1806  * variables to the subplan target list.  Also, we flatten all expressions
1807  * except GROUP BY items into their component variables; the other expressions
1808  * will be computed by the inserted nodes rather than by the subplan.
1809  * For example, given a query like
1810  *              SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1811  * we want to pass this targetlist to the subplan:
1812  *              a,b,c,d,a+b
1813  * where the a+b target will be used by the Sort/Group steps, and the
1814  * other targets will be used for computing the final results.  (In the
1815  * above example we could theoretically suppress the a and b targets and
1816  * pass down only c,d,a+b, but it's not really worth the trouble to
1817  * eliminate simple var references from the subplan.  We will avoid doing
1818  * the extra computation to recompute a+b at the outer level; see
1819  * fix_upper_expr() in setrefs.c.)
1820  *
1821  * If we are grouping or aggregating, *and* there are no non-Var grouping
1822  * expressions, then the returned tlist is effectively dummy; we do not
1823  * need to force it to be evaluated, because all the Vars it contains
1824  * should be present in the output of query_planner anyway.
1825  *
1826  * 'tlist' is the query's target list.
1827  * 'groupColIdx' receives an array of column numbers for the GROUP BY
1828  *                      expressions (if there are any) in the subplan's target list.
1829  * 'need_tlist_eval' is set true if we really need to evaluate the
1830  *                      result tlist.
1831  *
1832  * The result is the targetlist to be passed to the subplan.
1833  *---------------
1834  */
1835 static List *
1836 make_subplanTargetList(PlannerInfo *root,
1837                                            List *tlist,
1838                                            AttrNumber **groupColIdx,
1839                                            bool *need_tlist_eval)
1840 {
1841         Query      *parse = root->parse;
1842         List       *sub_tlist;
1843         List       *extravars;
1844         int                     numCols;
1845
1846         *groupColIdx = NULL;
1847
1848         /*
1849          * If we're not grouping or aggregating, there's nothing to do here;
1850          * query_planner should receive the unmodified target list.
1851          */
1852         if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1853         {
1854                 *need_tlist_eval = true;
1855                 return tlist;
1856         }
1857
1858         /*
1859          * Otherwise, start with a "flattened" tlist (having just the vars
1860          * mentioned in the targetlist and HAVING qual --- but not upper- level
1861          * Vars; they will be replaced by Params later on).
1862          */
1863         sub_tlist = flatten_tlist(tlist);
1864         extravars = pull_var_clause(parse->havingQual, false);
1865         sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1866         list_free(extravars);
1867         *need_tlist_eval = false;       /* only eval if not flat tlist */
1868
1869         /*
1870          * If grouping, create sub_tlist entries for all GROUP BY expressions
1871          * (GROUP BY items that are simple Vars should be in the list already),
1872          * and make an array showing where the group columns are in the sub_tlist.
1873          */
1874         numCols = list_length(parse->groupClause);
1875         if (numCols > 0)
1876         {
1877                 int                     keyno = 0;
1878                 AttrNumber *grpColIdx;
1879                 ListCell   *gl;
1880
1881                 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1882                 *groupColIdx = grpColIdx;
1883
1884                 foreach(gl, parse->groupClause)
1885                 {
1886                         SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
1887                         Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1888                         TargetEntry *te = NULL;
1889                         ListCell   *sl;
1890
1891                         /* Find or make a matching sub_tlist entry */
1892                         foreach(sl, sub_tlist)
1893                         {
1894                                 te = (TargetEntry *) lfirst(sl);
1895                                 if (equal(groupexpr, te->expr))
1896                                         break;
1897                         }
1898                         if (!sl)
1899                         {
1900                                 te = makeTargetEntry((Expr *) groupexpr,
1901                                                                          list_length(sub_tlist) + 1,
1902                                                                          NULL,
1903                                                                          false);
1904                                 sub_tlist = lappend(sub_tlist, te);
1905                                 *need_tlist_eval = true;                /* it's not flat anymore */
1906                         }
1907
1908                         /* and save its resno */
1909                         grpColIdx[keyno++] = te->resno;
1910                 }
1911         }
1912
1913         return sub_tlist;
1914 }
1915
1916 /*
1917  * locate_grouping_columns
1918  *              Locate grouping columns in the tlist chosen by query_planner.
1919  *
1920  * This is only needed if we don't use the sub_tlist chosen by
1921  * make_subplanTargetList.      We have to forget the column indexes found
1922  * by that routine and re-locate the grouping vars in the real sub_tlist.
1923  */
1924 static void
1925 locate_grouping_columns(PlannerInfo *root,
1926                                                 List *tlist,
1927                                                 List *sub_tlist,
1928                                                 AttrNumber *groupColIdx)
1929 {
1930         int                     keyno = 0;
1931         ListCell   *gl;
1932
1933         /*
1934          * No work unless grouping.
1935          */
1936         if (!root->parse->groupClause)
1937         {
1938                 Assert(groupColIdx == NULL);
1939                 return;
1940         }
1941         Assert(groupColIdx != NULL);
1942
1943         foreach(gl, root->parse->groupClause)
1944         {
1945                 SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
1946                 Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1947                 TargetEntry *te = NULL;
1948                 ListCell   *sl;
1949
1950                 foreach(sl, sub_tlist)
1951                 {
1952                         te = (TargetEntry *) lfirst(sl);
1953                         if (equal(groupexpr, te->expr))
1954                                 break;
1955                 }
1956                 if (!sl)
1957                         elog(ERROR, "failed to locate grouping columns");
1958
1959                 groupColIdx[keyno++] = te->resno;
1960         }
1961 }
1962
1963 /*
1964  * postprocess_setop_tlist
1965  *        Fix up targetlist returned by plan_set_operations().
1966  *
1967  * We need to transpose sort key info from the orig_tlist into new_tlist.
1968  * NOTE: this would not be good enough if we supported resjunk sort keys
1969  * for results of set operations --- then, we'd need to project a whole
1970  * new tlist to evaluate the resjunk columns.  For now, just ereport if we
1971  * find any resjunk columns in orig_tlist.
1972  */
1973 static List *
1974 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1975 {
1976         ListCell   *l;
1977         ListCell   *orig_tlist_item = list_head(orig_tlist);
1978
1979         foreach(l, new_tlist)
1980         {
1981                 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1982                 TargetEntry *orig_tle;
1983
1984                 /* ignore resjunk columns in setop result */
1985                 if (new_tle->resjunk)
1986                         continue;
1987
1988                 Assert(orig_tlist_item != NULL);
1989                 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1990                 orig_tlist_item = lnext(orig_tlist_item);
1991                 if (orig_tle->resjunk)  /* should not happen */
1992                         elog(ERROR, "resjunk output columns are not implemented");
1993                 Assert(new_tle->resno == orig_tle->resno);
1994                 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1995         }
1996         if (orig_tlist_item != NULL)
1997                 elog(ERROR, "resjunk output columns are not implemented");
1998         return new_tlist;
1999 }