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