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