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