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