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