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