]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/planner.c
Improve SELECT DISTINCT to consider hash aggregation, as well as sort/uniq,
[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.238 2008/08/05 02:43:17 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, sort by the more rigorous
1308                          * of DISTINCT and ORDER BY, to avoid a second sort below.
1309                          */
1310                         if (!pathkeys_contained_in(root->distinct_pathkeys,
1311                                                                            current_pathkeys))
1312                         {
1313                                 if (list_length(root->distinct_pathkeys) >=
1314                                         list_length(root->sort_pathkeys))
1315                                         current_pathkeys = root->distinct_pathkeys;
1316                                 else
1317                                 {
1318                                         current_pathkeys = root->sort_pathkeys;
1319                                         /* Assert checks that parser didn't mess up... */
1320                                         Assert(pathkeys_contained_in(root->distinct_pathkeys,
1321                                                                                                  current_pathkeys));
1322                                 }
1323
1324                                 result_plan = (Plan *) make_sort_from_pathkeys(root,
1325                                                                                                                            result_plan,
1326                                                                                                                            current_pathkeys,
1327                                                                                                                            -1.0);
1328                         }
1329
1330                         result_plan = (Plan *) make_unique(result_plan,
1331                                                                                            parse->distinctClause);
1332                         result_plan->plan_rows = dNumDistinctRows;
1333                         /* The Unique node won't change sort ordering */
1334                 }
1335         }
1336
1337         /*
1338          * If ORDER BY was given and we were not able to make the plan come out in
1339          * the right order, add an explicit sort step.
1340          */
1341         if (parse->sortClause)
1342         {
1343                 if (!pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1344                 {
1345                         result_plan = (Plan *) make_sort_from_pathkeys(root,
1346                                                                                                                    result_plan,
1347                                                                                                                    root->sort_pathkeys,
1348                                                                                                                    limit_tuples);
1349                         current_pathkeys = root->sort_pathkeys;
1350                 }
1351         }
1352
1353         /*
1354          * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1355          */
1356         if (parse->limitCount || parse->limitOffset)
1357         {
1358                 result_plan = (Plan *) make_limit(result_plan,
1359                                                                                   parse->limitOffset,
1360                                                                                   parse->limitCount,
1361                                                                                   offset_est,
1362                                                                                   count_est);
1363         }
1364
1365         /*
1366          * Deal with the RETURNING clause if any.  It's convenient to pass the
1367          * returningList through setrefs.c now rather than at top level (if we
1368          * waited, handling inherited UPDATE/DELETE would be much harder).
1369          */
1370         if (parse->returningList)
1371         {
1372                 List       *rlist;
1373
1374                 Assert(parse->resultRelation);
1375                 rlist = set_returning_clause_references(root->glob,
1376                                                                                                 parse->returningList,
1377                                                                                                 result_plan,
1378                                                                                                 parse->resultRelation);
1379                 root->returningLists = list_make1(rlist);
1380         }
1381         else
1382                 root->returningLists = NIL;
1383
1384         /* Compute result-relations list if needed */
1385         if (parse->resultRelation)
1386                 root->resultRelations = list_make1_int(parse->resultRelation);
1387         else
1388                 root->resultRelations = NIL;
1389
1390         /*
1391          * Return the actual output ordering in query_pathkeys for possible use by
1392          * an outer query level.
1393          */
1394         root->query_pathkeys = current_pathkeys;
1395
1396         return result_plan;
1397 }
1398
1399 /*
1400  * Detect whether a plan node is a "dummy" plan created when a relation
1401  * is deemed not to need scanning due to constraint exclusion.
1402  *
1403  * Currently, such dummy plans are Result nodes with constant FALSE
1404  * filter quals.
1405  */
1406 static bool
1407 is_dummy_plan(Plan *plan)
1408 {
1409         if (IsA(plan, Result))
1410         {
1411                 List       *rcqual = (List *) ((Result *) plan)->resconstantqual;
1412
1413                 if (list_length(rcqual) == 1)
1414                 {
1415                         Const      *constqual = (Const *) linitial(rcqual);
1416
1417                         if (constqual && IsA(constqual, Const))
1418                         {
1419                                 if (!constqual->constisnull &&
1420                                         !DatumGetBool(constqual->constvalue))
1421                                         return true;
1422                         }
1423                 }
1424         }
1425         return false;
1426 }
1427
1428 /*
1429  * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1430  *
1431  * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1432  * results back in *count_est and *offset_est.  These variables are set to
1433  * 0 if the corresponding clause is not present, and -1 if it's present
1434  * but we couldn't estimate the value for it.  (The "0" convention is OK
1435  * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1436  * LIMIT 0 as though it were LIMIT 1.  But this is in line with the planner's
1437  * usual practice of never estimating less than one row.)  These values will
1438  * be passed to make_limit, which see if you change this code.
1439  *
1440  * The return value is the suitably adjusted tuple_fraction to use for
1441  * planning the query.  This adjustment is not overridable, since it reflects
1442  * plan actions that grouping_planner() will certainly take, not assumptions
1443  * about context.
1444  */
1445 static double
1446 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1447                                  int64 *offset_est, int64 *count_est)
1448 {
1449         Query      *parse = root->parse;
1450         Node       *est;
1451         double          limit_fraction;
1452
1453         /* Should not be called unless LIMIT or OFFSET */
1454         Assert(parse->limitCount || parse->limitOffset);
1455
1456         /*
1457          * Try to obtain the clause values.  We use estimate_expression_value
1458          * primarily because it can sometimes do something useful with Params.
1459          */
1460         if (parse->limitCount)
1461         {
1462                 est = estimate_expression_value(root, parse->limitCount);
1463                 if (est && IsA(est, Const))
1464                 {
1465                         if (((Const *) est)->constisnull)
1466                         {
1467                                 /* NULL indicates LIMIT ALL, ie, no limit */
1468                                 *count_est = 0; /* treat as not present */
1469                         }
1470                         else
1471                         {
1472                                 *count_est = DatumGetInt64(((Const *) est)->constvalue);
1473                                 if (*count_est <= 0)
1474                                         *count_est = 1;         /* force to at least 1 */
1475                         }
1476                 }
1477                 else
1478                         *count_est = -1;        /* can't estimate */
1479         }
1480         else
1481                 *count_est = 0;                 /* not present */
1482
1483         if (parse->limitOffset)
1484         {
1485                 est = estimate_expression_value(root, parse->limitOffset);
1486                 if (est && IsA(est, Const))
1487                 {
1488                         if (((Const *) est)->constisnull)
1489                         {
1490                                 /* Treat NULL as no offset; the executor will too */
1491                                 *offset_est = 0;        /* treat as not present */
1492                         }
1493                         else
1494                         {
1495                                 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
1496                                 if (*offset_est < 0)
1497                                         *offset_est = 0;        /* less than 0 is same as 0 */
1498                         }
1499                 }
1500                 else
1501                         *offset_est = -1;       /* can't estimate */
1502         }
1503         else
1504                 *offset_est = 0;                /* not present */
1505
1506         if (*count_est != 0)
1507         {
1508                 /*
1509                  * A LIMIT clause limits the absolute number of tuples returned.
1510                  * However, if it's not a constant LIMIT then we have to guess; for
1511                  * lack of a better idea, assume 10% of the plan's result is wanted.
1512                  */
1513                 if (*count_est < 0 || *offset_est < 0)
1514                 {
1515                         /* LIMIT or OFFSET is an expression ... punt ... */
1516                         limit_fraction = 0.10;
1517                 }
1518                 else
1519                 {
1520                         /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
1521                         limit_fraction = (double) *count_est + (double) *offset_est;
1522                 }
1523
1524                 /*
1525                  * If we have absolute limits from both caller and LIMIT, use the
1526                  * smaller value; likewise if they are both fractional.  If one is
1527                  * fractional and the other absolute, we can't easily determine which
1528                  * is smaller, but we use the heuristic that the absolute will usually
1529                  * be smaller.
1530                  */
1531                 if (tuple_fraction >= 1.0)
1532                 {
1533                         if (limit_fraction >= 1.0)
1534                         {
1535                                 /* both absolute */
1536                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
1537                         }
1538                         else
1539                         {
1540                                 /* caller absolute, limit fractional; use caller's value */
1541                         }
1542                 }
1543                 else if (tuple_fraction > 0.0)
1544                 {
1545                         if (limit_fraction >= 1.0)
1546                         {
1547                                 /* caller fractional, limit absolute; use limit */
1548                                 tuple_fraction = limit_fraction;
1549                         }
1550                         else
1551                         {
1552                                 /* both fractional */
1553                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
1554                         }
1555                 }
1556                 else
1557                 {
1558                         /* no info from caller, just use limit */
1559                         tuple_fraction = limit_fraction;
1560                 }
1561         }
1562         else if (*offset_est != 0 && tuple_fraction > 0.0)
1563         {
1564                 /*
1565                  * We have an OFFSET but no LIMIT.      This acts entirely differently
1566                  * from the LIMIT case: here, we need to increase rather than decrease
1567                  * the caller's tuple_fraction, because the OFFSET acts to cause more
1568                  * tuples to be fetched instead of fewer.  This only matters if we got
1569                  * a tuple_fraction > 0, however.
1570                  *
1571                  * As above, use 10% if OFFSET is present but unestimatable.
1572                  */
1573                 if (*offset_est < 0)
1574                         limit_fraction = 0.10;
1575                 else
1576                         limit_fraction = (double) *offset_est;
1577
1578                 /*
1579                  * If we have absolute counts from both caller and OFFSET, add them
1580                  * together; likewise if they are both fractional.      If one is
1581                  * fractional and the other absolute, we want to take the larger, and
1582                  * we heuristically assume that's the fractional one.
1583                  */
1584                 if (tuple_fraction >= 1.0)
1585                 {
1586                         if (limit_fraction >= 1.0)
1587                         {
1588                                 /* both absolute, so add them together */
1589                                 tuple_fraction += limit_fraction;
1590                         }
1591                         else
1592                         {
1593                                 /* caller absolute, limit fractional; use limit */
1594                                 tuple_fraction = limit_fraction;
1595                         }
1596                 }
1597                 else
1598                 {
1599                         if (limit_fraction >= 1.0)
1600                         {
1601                                 /* caller fractional, limit absolute; use caller's value */
1602                         }
1603                         else
1604                         {
1605                                 /* both fractional, so add them together */
1606                                 tuple_fraction += limit_fraction;
1607                                 if (tuple_fraction >= 1.0)
1608                                         tuple_fraction = 0.0;           /* assume fetch all */
1609                         }
1610                 }
1611         }
1612
1613         return tuple_fraction;
1614 }
1615
1616
1617 /*
1618  * preprocess_groupclause - do preparatory work on GROUP BY clause
1619  *
1620  * The idea here is to adjust the ordering of the GROUP BY elements
1621  * (which in itself is semantically insignificant) to match ORDER BY,
1622  * thereby allowing a single sort operation to both implement the ORDER BY
1623  * requirement and set up for a Unique step that implements GROUP BY.
1624  *
1625  * In principle it might be interesting to consider other orderings of the
1626  * GROUP BY elements, which could match the sort ordering of other
1627  * possible plans (eg an indexscan) and thereby reduce cost.  We don't
1628  * bother with that, though.  Hashed grouping will frequently win anyway.
1629  *
1630  * Note: we need no comparable processing of the distinctClause because
1631  * the parser already enforced that that matches ORDER BY.
1632  */
1633 static void
1634 preprocess_groupclause(PlannerInfo *root)
1635 {
1636         Query      *parse = root->parse;
1637         List       *new_groupclause;
1638         bool            partial_match;
1639         ListCell   *sl;
1640         ListCell   *gl;
1641
1642         /* If no ORDER BY, nothing useful to do here */
1643         if (parse->sortClause == NIL)
1644                 return;
1645
1646         /*
1647          * Scan the ORDER BY clause and construct a list of matching GROUP BY
1648          * items, but only as far as we can make a matching prefix.
1649          *
1650          * This code assumes that the sortClause contains no duplicate items.
1651          */
1652         new_groupclause = NIL;
1653         foreach(sl, parse->sortClause)
1654         {
1655                 SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
1656
1657                 foreach(gl, parse->groupClause)
1658                 {
1659                         SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
1660
1661                         if (equal(gc, sc))
1662                         {
1663                                 new_groupclause = lappend(new_groupclause, gc);
1664                                 break;
1665                         }
1666                 }
1667                 if (gl == NULL)
1668                         break;                          /* no match, so stop scanning */
1669         }
1670
1671         /* Did we match all of the ORDER BY list, or just some of it? */
1672         partial_match = (sl != NULL);
1673
1674         /* If no match at all, no point in reordering GROUP BY */
1675         if (new_groupclause == NIL)
1676                 return;
1677
1678         /*
1679          * Add any remaining GROUP BY items to the new list, but only if we
1680          * were able to make a complete match.  In other words, we only
1681          * rearrange the GROUP BY list if the result is that one list is a
1682          * prefix of the other --- otherwise there's no possibility of a
1683          * common sort.  Also, give up if there are any non-sortable GROUP BY
1684          * items, since then there's no hope anyway.
1685          */
1686         foreach(gl, parse->groupClause)
1687         {
1688                 SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
1689
1690                 if (list_member_ptr(new_groupclause, gc))
1691                         continue;                       /* it matched an ORDER BY item */
1692                 if (partial_match)
1693                         return;                         /* give up, no common sort possible */
1694                 if (!OidIsValid(gc->sortop))
1695                         return;                         /* give up, GROUP BY can't be sorted */
1696                 new_groupclause = lappend(new_groupclause, gc);
1697         }
1698
1699         /* Success --- install the rearranged GROUP BY list */
1700         Assert(list_length(parse->groupClause) == list_length(new_groupclause));
1701         parse->groupClause = new_groupclause;
1702 }
1703
1704 /*
1705  * extract_grouping_ops - make an array of the equality operator OIDs
1706  *              for a SortGroupClause list
1707  */
1708 static Oid *
1709 extract_grouping_ops(List *groupClause)
1710 {
1711         int                     numCols = list_length(groupClause);
1712         int                     colno = 0;
1713         Oid                *groupOperators;
1714         ListCell   *glitem;
1715
1716         groupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
1717
1718         foreach(glitem, groupClause)
1719         {
1720                 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1721
1722                 groupOperators[colno] = groupcl->eqop;
1723                 Assert(OidIsValid(groupOperators[colno]));
1724                 colno++;
1725         }
1726
1727         return groupOperators;
1728 }
1729
1730 /*
1731  * extract_grouping_cols - make an array of the grouping column resnos
1732  *              for a SortGroupClause list
1733  */
1734 static AttrNumber *
1735 extract_grouping_cols(List *groupClause, List *tlist)
1736 {
1737         AttrNumber *grpColIdx;
1738         int                     numCols = list_length(groupClause);
1739         int                     colno = 0;
1740         ListCell   *glitem;
1741
1742         grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1743
1744         foreach(glitem, groupClause)
1745         {
1746                 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1747                 TargetEntry *tle = get_sortgroupclause_tle(groupcl, tlist);
1748
1749                 grpColIdx[colno++] = tle->resno;
1750         }
1751
1752         return grpColIdx;
1753 }
1754
1755 /*
1756  * grouping_is_sortable - is it possible to implement grouping list by sorting?
1757  *
1758  * This is easy since the parser will have included a sortop if one exists.
1759  */
1760 static bool
1761 grouping_is_sortable(List *groupClause)
1762 {
1763         ListCell   *glitem;
1764
1765         foreach(glitem, groupClause)
1766         {
1767                 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1768
1769                 if (!OidIsValid(groupcl->sortop))
1770                         return false;
1771         }
1772         return true;
1773 }
1774
1775 /*
1776  * grouping_is_hashable - is it possible to implement grouping list by hashing?
1777  *
1778  * We assume hashing is OK if the equality operators are marked oprcanhash.
1779  * (If there isn't actually a supporting hash function, the executor will
1780  * complain at runtime; but this is a misdeclaration of the operator, not
1781  * a system bug.)
1782  */
1783 static bool
1784 grouping_is_hashable(List *groupClause)
1785 {
1786         ListCell   *glitem;
1787
1788         foreach(glitem, groupClause)
1789         {
1790                 SortGroupClause *groupcl = (SortGroupClause *) lfirst(glitem);
1791
1792                 if (!op_hashjoinable(groupcl->eqop))
1793                         return false;
1794         }
1795         return true;
1796 }
1797
1798 /*
1799  * choose_hashed_grouping - should we use hashed grouping?
1800  *
1801  * Note: this is only applied when both alternatives are actually feasible.
1802  */
1803 static bool
1804 choose_hashed_grouping(PlannerInfo *root,
1805                                            double tuple_fraction, double limit_tuples,
1806                                            Path *cheapest_path, Path *sorted_path,
1807                                            double dNumGroups, AggClauseCounts *agg_counts)
1808 {
1809         int                     numGroupCols = list_length(root->parse->groupClause);
1810         double          cheapest_path_rows;
1811         int                     cheapest_path_width;
1812         Size            hashentrysize;
1813         List       *target_pathkeys;
1814         List       *current_pathkeys;
1815         Path            hashed_p;
1816         Path            sorted_p;
1817
1818         /* Prefer sorting when enable_hashagg is off */
1819         if (!enable_hashagg)
1820                 return false;
1821
1822         /*
1823          * Don't do it if it doesn't look like the hashtable will fit into
1824          * work_mem.
1825          *
1826          * Beware here of the possibility that cheapest_path->parent is NULL. This
1827          * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
1828          */
1829         if (cheapest_path->parent)
1830         {
1831                 cheapest_path_rows = cheapest_path->parent->rows;
1832                 cheapest_path_width = cheapest_path->parent->width;
1833         }
1834         else
1835         {
1836                 cheapest_path_rows = 1; /* assume non-set result */
1837                 cheapest_path_width = 100;              /* arbitrary */
1838         }
1839
1840         /* Estimate per-hash-entry space at tuple width... */
1841         hashentrysize = MAXALIGN(cheapest_path_width) + MAXALIGN(sizeof(MinimalTupleData));
1842         /* plus space for pass-by-ref transition values... */
1843         hashentrysize += agg_counts->transitionSpace;
1844         /* plus the per-hash-entry overhead */
1845         hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1846
1847         if (hashentrysize * dNumGroups > work_mem * 1024L)
1848                 return false;
1849
1850         /*
1851          * When we have both GROUP BY and DISTINCT, use the more-rigorous of
1852          * DISTINCT and ORDER BY as the assumed required output sort order.
1853          * This is an oversimplification because the DISTINCT might get
1854          * implemented via hashing, but it's not clear that the case is common
1855          * enough (or that our estimates are good enough) to justify trying to
1856          * solve it exactly.
1857          */
1858         if (list_length(root->distinct_pathkeys) >
1859                 list_length(root->sort_pathkeys))
1860                 target_pathkeys = root->distinct_pathkeys;
1861         else
1862                 target_pathkeys = root->sort_pathkeys;
1863
1864         /*
1865          * See if the estimated cost is no more than doing it the other way. While
1866          * avoiding the need for sorted input is usually a win, the fact that the
1867          * output won't be sorted may be a loss; so we need to do an actual cost
1868          * comparison.
1869          *
1870          * We need to consider cheapest_path + hashagg [+ final sort] versus
1871          * either cheapest_path [+ sort] + group or agg [+ final sort] or
1872          * presorted_path + group or agg [+ final sort] where brackets indicate a
1873          * step that may not be needed. We assume query_planner() will have
1874          * returned a presorted path only if it's a winner compared to
1875          * cheapest_path for this purpose.
1876          *
1877          * These path variables are dummies that just hold cost fields; we don't
1878          * make actual Paths for these steps.
1879          */
1880         cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1881                          numGroupCols, dNumGroups,
1882                          cheapest_path->startup_cost, cheapest_path->total_cost,
1883                          cheapest_path_rows);
1884         /* Result of hashed agg is always unsorted */
1885         if (target_pathkeys)
1886                 cost_sort(&hashed_p, root, target_pathkeys, hashed_p.total_cost,
1887                                   dNumGroups, cheapest_path_width, limit_tuples);
1888
1889         if (sorted_path)
1890         {
1891                 sorted_p.startup_cost = sorted_path->startup_cost;
1892                 sorted_p.total_cost = sorted_path->total_cost;
1893                 current_pathkeys = sorted_path->pathkeys;
1894         }
1895         else
1896         {
1897                 sorted_p.startup_cost = cheapest_path->startup_cost;
1898                 sorted_p.total_cost = cheapest_path->total_cost;
1899                 current_pathkeys = cheapest_path->pathkeys;
1900         }
1901         if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1902         {
1903                 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
1904                                   cheapest_path_rows, cheapest_path_width, -1.0);
1905                 current_pathkeys = root->group_pathkeys;
1906         }
1907
1908         if (root->parse->hasAggs)
1909                 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1910                                  numGroupCols, dNumGroups,
1911                                  sorted_p.startup_cost, sorted_p.total_cost,
1912                                  cheapest_path_rows);
1913         else
1914                 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1915                                    sorted_p.startup_cost, sorted_p.total_cost,
1916                                    cheapest_path_rows);
1917         /* The Agg or Group node will preserve ordering */
1918         if (target_pathkeys &&
1919                 !pathkeys_contained_in(target_pathkeys, current_pathkeys))
1920                 cost_sort(&sorted_p, root, target_pathkeys, sorted_p.total_cost,
1921                                   dNumGroups, cheapest_path_width, limit_tuples);
1922
1923         /*
1924          * Now make the decision using the top-level tuple fraction.  First we
1925          * have to convert an absolute count (LIMIT) into fractional form.
1926          */
1927         if (tuple_fraction >= 1.0)
1928                 tuple_fraction /= dNumGroups;
1929
1930         if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1931                                                                           tuple_fraction) < 0)
1932         {
1933                 /* Hashed is cheaper, so use it */
1934                 return true;
1935         }
1936         return false;
1937 }
1938
1939 /*
1940  * choose_hashed_distinct - should we use hashing for DISTINCT?
1941  *
1942  * This is fairly similar to choose_hashed_grouping, but there are enough
1943  * differences that it doesn't seem worth trying to unify the two functions.
1944  *
1945  * But note that making the two choices independently is a bit bogus in
1946  * itself.  If the two could be combined into a single choice operation
1947  * it'd probably be better, but that seems far too unwieldy to be practical,
1948  * especially considering that the combination of GROUP BY and DISTINCT
1949  * isn't very common in real queries.  By separating them, we are giving
1950  * extra preference to using a sorting implementation when a common sort key
1951  * is available ... and that's not necessarily wrong anyway.
1952  *
1953  * Note: this is only applied when both alternatives are actually feasible.
1954  */
1955 static bool
1956 choose_hashed_distinct(PlannerInfo *root,
1957                                            Plan *input_plan, List *input_pathkeys,
1958                                            double tuple_fraction, double limit_tuples,
1959                                            double dNumDistinctRows)
1960 {
1961         int                     numDistinctCols = list_length(root->parse->distinctClause);
1962         Size            hashentrysize;
1963         List       *current_pathkeys;
1964         Path            hashed_p;
1965         Path            sorted_p;
1966
1967         /* Prefer sorting when enable_hashagg is off */
1968         if (!enable_hashagg)
1969                 return false;
1970
1971         /*
1972          * Don't do it if it doesn't look like the hashtable will fit into
1973          * work_mem.
1974          */
1975         hashentrysize = MAXALIGN(input_plan->plan_width) + MAXALIGN(sizeof(MinimalTupleData));
1976
1977         if (hashentrysize * dNumDistinctRows > work_mem * 1024L)
1978                 return false;
1979
1980         /*
1981          * See if the estimated cost is no more than doing it the other way. While
1982          * avoiding the need for sorted input is usually a win, the fact that the
1983          * output won't be sorted may be a loss; so we need to do an actual cost
1984          * comparison.
1985          *
1986          * We need to consider input_plan + hashagg [+ final sort] versus
1987          * input_plan [+ sort] + group [+ final sort] where brackets indicate
1988          * a step that may not be needed.
1989          *
1990          * These path variables are dummies that just hold cost fields; we don't
1991          * make actual Paths for these steps.
1992          */
1993         cost_agg(&hashed_p, root, AGG_HASHED, 0,
1994                          numDistinctCols, dNumDistinctRows,
1995                          input_plan->startup_cost, input_plan->total_cost,
1996                          input_plan->plan_rows);
1997         /*
1998          * Result of hashed agg is always unsorted, so if ORDER BY is present
1999          * we need to charge for the final sort.
2000          */
2001         if (root->parse->sortClause)
2002                 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
2003                                   dNumDistinctRows, input_plan->plan_width, limit_tuples);
2004
2005         /* Now for the GROUP case ... */
2006         sorted_p.startup_cost = input_plan->startup_cost;
2007         sorted_p.total_cost = input_plan->total_cost;
2008         current_pathkeys = input_pathkeys;
2009         if (!pathkeys_contained_in(root->distinct_pathkeys, current_pathkeys))
2010         {
2011                 /* We don't want to sort twice */
2012                 if (list_length(root->distinct_pathkeys) >=
2013                         list_length(root->sort_pathkeys))
2014                         current_pathkeys = root->distinct_pathkeys;
2015                 else
2016                         current_pathkeys = root->sort_pathkeys;
2017                 cost_sort(&sorted_p, root, current_pathkeys, sorted_p.total_cost,
2018                                   input_plan->plan_rows, input_plan->plan_width, -1.0);
2019         }
2020         cost_group(&sorted_p, root, numDistinctCols, dNumDistinctRows,
2021                            sorted_p.startup_cost, sorted_p.total_cost,
2022                            input_plan->plan_rows);
2023         if (root->parse->sortClause &&
2024                 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
2025                 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
2026                                   dNumDistinctRows, input_plan->plan_width, limit_tuples);
2027
2028         /*
2029          * Now make the decision using the top-level tuple fraction.  First we
2030          * have to convert an absolute count (LIMIT) into fractional form.
2031          */
2032         if (tuple_fraction >= 1.0)
2033                 tuple_fraction /= dNumDistinctRows;
2034
2035         if (compare_fractional_path_costs(&hashed_p, &sorted_p,
2036                                                                           tuple_fraction) < 0)
2037         {
2038                 /* Hashed is cheaper, so use it */
2039                 return true;
2040         }
2041         return false;
2042 }
2043
2044 /*---------------
2045  * make_subplanTargetList
2046  *        Generate appropriate target list when grouping is required.
2047  *
2048  * When grouping_planner inserts Aggregate, Group, or Result plan nodes
2049  * above the result of query_planner, we typically want to pass a different
2050  * target list to query_planner than the outer plan nodes should have.
2051  * This routine generates the correct target list for the subplan.
2052  *
2053  * The initial target list passed from the parser already contains entries
2054  * for all ORDER BY and GROUP BY expressions, but it will not have entries
2055  * for variables used only in HAVING clauses; so we need to add those
2056  * variables to the subplan target list.  Also, we flatten all expressions
2057  * except GROUP BY items into their component variables; the other expressions
2058  * will be computed by the inserted nodes rather than by the subplan.
2059  * For example, given a query like
2060  *              SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
2061  * we want to pass this targetlist to the subplan:
2062  *              a,b,c,d,a+b
2063  * where the a+b target will be used by the Sort/Group steps, and the
2064  * other targets will be used for computing the final results.  (In the
2065  * above example we could theoretically suppress the a and b targets and
2066  * pass down only c,d,a+b, but it's not really worth the trouble to
2067  * eliminate simple var references from the subplan.  We will avoid doing
2068  * the extra computation to recompute a+b at the outer level; see
2069  * fix_upper_expr() in setrefs.c.)
2070  *
2071  * If we are grouping or aggregating, *and* there are no non-Var grouping
2072  * expressions, then the returned tlist is effectively dummy; we do not
2073  * need to force it to be evaluated, because all the Vars it contains
2074  * should be present in the output of query_planner anyway.
2075  *
2076  * 'tlist' is the query's target list.
2077  * 'groupColIdx' receives an array of column numbers for the GROUP BY
2078  *                      expressions (if there are any) in the subplan's target list.
2079  * 'need_tlist_eval' is set true if we really need to evaluate the
2080  *                      result tlist.
2081  *
2082  * The result is the targetlist to be passed to the subplan.
2083  *---------------
2084  */
2085 static List *
2086 make_subplanTargetList(PlannerInfo *root,
2087                                            List *tlist,
2088                                            AttrNumber **groupColIdx,
2089                                            bool *need_tlist_eval)
2090 {
2091         Query      *parse = root->parse;
2092         List       *sub_tlist;
2093         List       *extravars;
2094         int                     numCols;
2095
2096         *groupColIdx = NULL;
2097
2098         /*
2099          * If we're not grouping or aggregating, there's nothing to do here;
2100          * query_planner should receive the unmodified target list.
2101          */
2102         if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
2103         {
2104                 *need_tlist_eval = true;
2105                 return tlist;
2106         }
2107
2108         /*
2109          * Otherwise, start with a "flattened" tlist (having just the vars
2110          * mentioned in the targetlist and HAVING qual --- but not upper-level
2111          * Vars; they will be replaced by Params later on).
2112          */
2113         sub_tlist = flatten_tlist(tlist);
2114         extravars = pull_var_clause(parse->havingQual, false);
2115         sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
2116         list_free(extravars);
2117         *need_tlist_eval = false;       /* only eval if not flat tlist */
2118
2119         /*
2120          * If grouping, create sub_tlist entries for all GROUP BY expressions
2121          * (GROUP BY items that are simple Vars should be in the list already),
2122          * and make an array showing where the group columns are in the sub_tlist.
2123          */
2124         numCols = list_length(parse->groupClause);
2125         if (numCols > 0)
2126         {
2127                 int                     keyno = 0;
2128                 AttrNumber *grpColIdx;
2129                 ListCell   *gl;
2130
2131                 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
2132                 *groupColIdx = grpColIdx;
2133
2134                 foreach(gl, parse->groupClause)
2135                 {
2136                         SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
2137                         Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
2138                         TargetEntry *te = NULL;
2139
2140                         /*
2141                          * Find or make a matching sub_tlist entry.  If the groupexpr
2142                          * isn't a Var, no point in searching.  (Note that the parser
2143                          * won't make multiple groupClause entries for the same TLE.)
2144                          */
2145                         if (groupexpr && IsA(groupexpr, Var))
2146                         {
2147                                 ListCell   *sl;
2148
2149                                 foreach(sl, sub_tlist)
2150                                 {
2151                                         TargetEntry *lte = (TargetEntry *) lfirst(sl);
2152
2153                                         if (equal(groupexpr, lte->expr))
2154                                         {
2155                                                 te = lte;
2156                                                 break;
2157                                         }
2158                                 }
2159                         }
2160                         if (!te)
2161                         {
2162                                 te = makeTargetEntry((Expr *) groupexpr,
2163                                                                          list_length(sub_tlist) + 1,
2164                                                                          NULL,
2165                                                                          false);
2166                                 sub_tlist = lappend(sub_tlist, te);
2167                                 *need_tlist_eval = true;                /* it's not flat anymore */
2168                         }
2169
2170                         /* and save its resno */
2171                         grpColIdx[keyno++] = te->resno;
2172                 }
2173         }
2174
2175         return sub_tlist;
2176 }
2177
2178 /*
2179  * locate_grouping_columns
2180  *              Locate grouping columns in the tlist chosen by query_planner.
2181  *
2182  * This is only needed if we don't use the sub_tlist chosen by
2183  * make_subplanTargetList.      We have to forget the column indexes found
2184  * by that routine and re-locate the grouping vars in the real sub_tlist.
2185  */
2186 static void
2187 locate_grouping_columns(PlannerInfo *root,
2188                                                 List *tlist,
2189                                                 List *sub_tlist,
2190                                                 AttrNumber *groupColIdx)
2191 {
2192         int                     keyno = 0;
2193         ListCell   *gl;
2194
2195         /*
2196          * No work unless grouping.
2197          */
2198         if (!root->parse->groupClause)
2199         {
2200                 Assert(groupColIdx == NULL);
2201                 return;
2202         }
2203         Assert(groupColIdx != NULL);
2204
2205         foreach(gl, root->parse->groupClause)
2206         {
2207                 SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
2208                 Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
2209                 TargetEntry *te = NULL;
2210                 ListCell   *sl;
2211
2212                 foreach(sl, sub_tlist)
2213                 {
2214                         te = (TargetEntry *) lfirst(sl);
2215                         if (equal(groupexpr, te->expr))
2216                                 break;
2217                 }
2218                 if (!sl)
2219                         elog(ERROR, "failed to locate grouping columns");
2220
2221                 groupColIdx[keyno++] = te->resno;
2222         }
2223 }
2224
2225 /*
2226  * postprocess_setop_tlist
2227  *        Fix up targetlist returned by plan_set_operations().
2228  *
2229  * We need to transpose sort key info from the orig_tlist into new_tlist.
2230  * NOTE: this would not be good enough if we supported resjunk sort keys
2231  * for results of set operations --- then, we'd need to project a whole
2232  * new tlist to evaluate the resjunk columns.  For now, just ereport if we
2233  * find any resjunk columns in orig_tlist.
2234  */
2235 static List *
2236 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
2237 {
2238         ListCell   *l;
2239         ListCell   *orig_tlist_item = list_head(orig_tlist);
2240
2241         foreach(l, new_tlist)
2242         {
2243                 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
2244                 TargetEntry *orig_tle;
2245
2246                 /* ignore resjunk columns in setop result */
2247                 if (new_tle->resjunk)
2248                         continue;
2249
2250                 Assert(orig_tlist_item != NULL);
2251                 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
2252                 orig_tlist_item = lnext(orig_tlist_item);
2253                 if (orig_tle->resjunk)  /* should not happen */
2254                         elog(ERROR, "resjunk output columns are not implemented");
2255                 Assert(new_tle->resno == orig_tle->resno);
2256                 new_tle->ressortgroupref = orig_tle->ressortgroupref;
2257         }
2258         if (orig_tlist_item != NULL)
2259                 elog(ERROR, "resjunk output columns are not implemented");
2260         return new_tlist;
2261 }