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