]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/planner.c
Teach planner about some cases where a restriction clause can be
[postgresql] / src / backend / optimizer / plan / planner.c
1 /*-------------------------------------------------------------------------
2  *
3  * planner.c
4  *        The query optimizer external interface.
5  *
6  * Portions Copyright (c) 1996-2005, 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.190 2005/07/02 23:00:41 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include <limits.h>
19
20 #include "catalog/pg_operator.h"
21 #include "catalog/pg_type.h"
22 #include "executor/executor.h"
23 #include "executor/nodeAgg.h"
24 #include "miscadmin.h"
25 #include "nodes/makefuncs.h"
26 #ifdef OPTIMIZER_DEBUG
27 #include "nodes/print.h"
28 #endif
29 #include "optimizer/clauses.h"
30 #include "optimizer/cost.h"
31 #include "optimizer/pathnode.h"
32 #include "optimizer/paths.h"
33 #include "optimizer/planmain.h"
34 #include "optimizer/planner.h"
35 #include "optimizer/prep.h"
36 #include "optimizer/subselect.h"
37 #include "optimizer/tlist.h"
38 #include "optimizer/var.h"
39 #include "parser/parsetree.h"
40 #include "parser/parse_expr.h"
41 #include "parser/parse_oper.h"
42 #include "utils/selfuncs.h"
43 #include "utils/syscache.h"
44
45
46 ParamListInfo PlannerBoundParamList = NULL;             /* current boundParams */
47
48
49 /* Expression kind codes for preprocess_expression */
50 #define EXPRKIND_QUAL   0
51 #define EXPRKIND_TARGET 1
52 #define EXPRKIND_RTFUNC 2
53 #define EXPRKIND_LIMIT  3
54 #define EXPRKIND_ININFO 4
55
56
57 static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
58 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
59 static Plan *inheritance_planner(PlannerInfo *root, List *inheritlist);
60 static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
61 static double adjust_tuple_fraction_for_limit(PlannerInfo *root,
62                                                                                           double tuple_fraction);
63 static bool choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
64                                            Path *cheapest_path, Path *sorted_path,
65                                            List *sort_pathkeys, List *group_pathkeys,
66                                            double dNumGroups, AggClauseCounts *agg_counts);
67 static bool hash_safe_grouping(PlannerInfo *root);
68 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
69                                            AttrNumber **groupColIdx, bool *need_tlist_eval);
70 static void locate_grouping_columns(PlannerInfo *root,
71                                                 List *tlist,
72                                                 List *sub_tlist,
73                                                 AttrNumber *groupColIdx);
74 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
75
76
77 /*****************************************************************************
78  *
79  *         Query optimizer entry point
80  *
81  *****************************************************************************/
82 Plan *
83 planner(Query *parse, bool isCursor, int cursorOptions,
84                 ParamListInfo boundParams)
85 {
86         double          tuple_fraction;
87         Plan       *result_plan;
88         Index           save_PlannerQueryLevel;
89         List       *save_PlannerParamList;
90         ParamListInfo save_PlannerBoundParamList;
91
92         /*
93          * The planner can be called recursively (an example is when
94          * eval_const_expressions tries to pre-evaluate an SQL function). So,
95          * these global state variables must be saved and restored.
96          *
97          * Query level and the param list cannot be moved into the per-query
98          * PlannerInfo structure since their whole purpose is communication
99          * across multiple sub-queries. Also, boundParams is explicitly info
100          * from outside the query, and so is likewise better handled as a global
101          * variable.
102          *
103          * Note we do NOT save and restore PlannerPlanId: it exists to assign
104          * unique IDs to SubPlan nodes, and we want those IDs to be unique for
105          * the life of a backend.  Also, PlannerInitPlan is saved/restored in
106          * subquery_planner, not here.
107          */
108         save_PlannerQueryLevel = PlannerQueryLevel;
109         save_PlannerParamList = PlannerParamList;
110         save_PlannerBoundParamList = PlannerBoundParamList;
111
112         /* Initialize state for handling outer-level references and params */
113         PlannerQueryLevel = 0;          /* will be 1 in top-level subquery_planner */
114         PlannerParamList = NIL;
115         PlannerBoundParamList = boundParams;
116
117         /* Determine what fraction of the plan is likely to be scanned */
118         if (isCursor)
119         {
120                 /*
121                  * We have no real idea how many tuples the user will ultimately
122                  * FETCH from a cursor, but it seems a good bet that he doesn't
123                  * want 'em all.  Optimize for 10% retrieval (you gotta better
124                  * number?      Should this be a SETtable parameter?)
125                  */
126                 tuple_fraction = 0.10;
127         }
128         else
129         {
130                 /* Default assumption is we need all the tuples */
131                 tuple_fraction = 0.0;
132         }
133
134         /* primary planning entry point (may recurse for subqueries) */
135         result_plan = subquery_planner(parse, tuple_fraction, NULL);
136
137         /* check we popped out the right number of levels */
138         Assert(PlannerQueryLevel == 0);
139
140         /*
141          * If creating a plan for a scrollable cursor, make sure it can run
142          * backwards on demand.  Add a Material node at the top at need.
143          */
144         if (isCursor && (cursorOptions & CURSOR_OPT_SCROLL))
145         {
146                 if (!ExecSupportsBackwardScan(result_plan))
147                         result_plan = materialize_finished_plan(result_plan);
148         }
149
150         /* final cleanup of the plan */
151         result_plan = set_plan_references(result_plan, parse->rtable);
152
153         /* executor wants to know total number of Params used overall */
154         result_plan->nParamExec = list_length(PlannerParamList);
155
156         /* restore state for outer planner, if any */
157         PlannerQueryLevel = save_PlannerQueryLevel;
158         PlannerParamList = save_PlannerParamList;
159         PlannerBoundParamList = save_PlannerBoundParamList;
160
161         return result_plan;
162 }
163
164
165 /*--------------------
166  * subquery_planner
167  *        Invokes the planner on a subquery.  We recurse to here for each
168  *        sub-SELECT found in the query tree.
169  *
170  * parse is the querytree produced by the parser & rewriter.
171  * tuple_fraction is the fraction of tuples we expect will be retrieved.
172  * tuple_fraction is interpreted as explained for grouping_planner, below.
173  *
174  * If subquery_pathkeys isn't NULL, it receives a list of pathkeys indicating
175  * the output sort ordering of the completed plan.
176  *
177  * Basically, this routine does the stuff that should only be done once
178  * per Query object.  It then calls grouping_planner.  At one time,
179  * grouping_planner could be invoked recursively on the same Query object;
180  * that's not currently true, but we keep the separation between the two
181  * routines anyway, in case we need it again someday.
182  *
183  * subquery_planner will be called recursively to handle sub-Query nodes
184  * found within the query's expressions and rangetable.
185  *
186  * Returns a query plan.
187  *--------------------
188  */
189 Plan *
190 subquery_planner(Query *parse, double tuple_fraction,
191                                  List **subquery_pathkeys)
192 {
193         List       *saved_initplan = PlannerInitPlan;
194         int                     saved_planid = PlannerPlanId;
195         PlannerInfo *root;
196         Plan       *plan;
197         List       *newHaving;
198         List       *lst;
199         ListCell   *l;
200
201         /* Set up for a new level of subquery */
202         PlannerQueryLevel++;
203         PlannerInitPlan = NIL;
204
205         /* Create a PlannerInfo data structure for this subquery */
206         root = makeNode(PlannerInfo);
207         root->parse = parse;
208
209         /*
210          * Look for IN clauses at the top level of WHERE, and transform them
211          * into joins.  Note that this step only handles IN clauses originally
212          * at top level of WHERE; if we pull up any subqueries in the next
213          * step, their INs are processed just before pulling them up.
214          */
215         root->in_info_list = NIL;
216         if (parse->hasSubLinks)
217                 parse->jointree->quals = pull_up_IN_clauses(root,
218                                                                                                         parse->jointree->quals);
219
220         /*
221          * Check to see if any subqueries in the rangetable can be merged into
222          * this query.
223          */
224         parse->jointree = (FromExpr *)
225                 pull_up_subqueries(root, (Node *) parse->jointree, false);
226
227         /*
228          * Detect whether any rangetable entries are RTE_JOIN kind; if not, we
229          * can avoid the expense of doing flatten_join_alias_vars().  Also
230          * check for outer joins --- if none, we can skip reduce_outer_joins()
231          * and some other processing.  This must be done after we have done
232          * pull_up_subqueries, of course.
233          *
234          * Note: if reduce_outer_joins manages to eliminate all outer joins,
235          * root->hasOuterJoins is not reset currently.  This is OK since its
236          * purpose is merely to suppress unnecessary processing in simple cases.
237          */
238         root->hasJoinRTEs = false;
239         root->hasOuterJoins = false;
240         foreach(l, parse->rtable)
241         {
242                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
243
244                 if (rte->rtekind == RTE_JOIN)
245                 {
246                         root->hasJoinRTEs = true;
247                         if (IS_OUTER_JOIN(rte->jointype))
248                         {
249                                 root->hasOuterJoins = true;
250                                 /* Can quit scanning once we find an outer join */
251                                 break;
252                         }
253                 }
254         }
255
256         /*
257          * Set hasHavingQual to remember if HAVING clause is present.  Needed
258          * because preprocess_expression will reduce a constant-true condition
259          * to an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
260          */
261         root->hasHavingQual = (parse->havingQual != NULL);
262
263         /*
264          * Do expression preprocessing on targetlist and quals.
265          */
266         parse->targetList = (List *)
267                 preprocess_expression(root, (Node *) parse->targetList,
268                                                           EXPRKIND_TARGET);
269
270         preprocess_qual_conditions(root, (Node *) parse->jointree);
271
272         parse->havingQual = preprocess_expression(root, parse->havingQual,
273                                                                                           EXPRKIND_QUAL);
274
275         parse->limitOffset = preprocess_expression(root, parse->limitOffset,
276                                                                                            EXPRKIND_LIMIT);
277         parse->limitCount = preprocess_expression(root, parse->limitCount,
278                                                                                           EXPRKIND_LIMIT);
279
280         root->in_info_list = (List *)
281                 preprocess_expression(root, (Node *) root->in_info_list,
282                                                           EXPRKIND_ININFO);
283
284         /* Also need to preprocess expressions for function RTEs */
285         foreach(l, parse->rtable)
286         {
287                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
288
289                 if (rte->rtekind == RTE_FUNCTION)
290                         rte->funcexpr = preprocess_expression(root, rte->funcexpr,
291                                                                                                   EXPRKIND_RTFUNC);
292         }
293
294         /*
295          * In some cases we may want to transfer a HAVING clause into WHERE.
296          * We cannot do so if the HAVING clause contains aggregates (obviously)
297          * or volatile functions (since a HAVING clause is supposed to be executed
298          * only once per group).  Also, it may be that the clause is so expensive
299          * to execute that we're better off doing it only once per group, despite
300          * the loss of selectivity.  This is hard to estimate short of doing the
301          * entire planning process twice, so we use a heuristic: clauses
302          * containing subplans are left in HAVING.  Otherwise, we move or copy
303          * the HAVING clause into WHERE, in hopes of eliminating tuples before
304          * aggregation instead of after.
305          *
306          * If the query has explicit grouping then we can simply move such a
307          * clause into WHERE; any group that fails the clause will not be
308          * in the output because none of its tuples will reach the grouping
309          * or aggregation stage.  Otherwise we must have a degenerate
310          * (variable-free) HAVING clause, which we put in WHERE so that
311          * query_planner() can use it in a gating Result node, but also keep
312          * in HAVING to ensure that we don't emit a bogus aggregated row.
313          * (This could be done better, but it seems not worth optimizing.)
314          *
315          * Note that both havingQual and parse->jointree->quals are in
316          * implicitly-ANDed-list form at this point, even though they are
317          * declared as Node *.
318          */
319         newHaving = NIL;
320         foreach(l, (List *) parse->havingQual)
321         {
322                 Node       *havingclause = (Node *) lfirst(l);
323
324                 if (contain_agg_clause(havingclause) ||
325                         contain_volatile_functions(havingclause) ||
326                         contain_subplans(havingclause))
327                 {
328                         /* keep it in HAVING */
329                         newHaving = lappend(newHaving, havingclause);
330                 }
331                 else if (parse->groupClause)
332                 {
333                         /* move it to WHERE */
334                         parse->jointree->quals = (Node *)
335                                 lappend((List *) parse->jointree->quals, havingclause);
336                 }
337                 else
338                 {
339                         /* put a copy in WHERE, keep it in HAVING */
340                         parse->jointree->quals = (Node *)
341                                 lappend((List *) parse->jointree->quals,
342                                                 copyObject(havingclause));
343                         newHaving = lappend(newHaving, havingclause);
344                 }
345         }
346         parse->havingQual = (Node *) newHaving;
347
348         /*
349          * If we have any outer joins, try to reduce them to plain inner
350          * joins. This step is most easily done after we've done expression
351          * preprocessing.
352          */
353         if (root->hasOuterJoins)
354                 reduce_outer_joins(root);
355
356         /*
357          * See if we can simplify the jointree; opportunities for this may
358          * come from having pulled up subqueries, or from flattening explicit
359          * JOIN syntax.  We must do this after flattening JOIN alias
360          * variables, since eliminating explicit JOIN nodes from the jointree
361          * will cause get_relids_for_join() to fail.  But it should happen
362          * after reduce_outer_joins, anyway.
363          */
364         parse->jointree = (FromExpr *)
365                 simplify_jointree(root, (Node *) parse->jointree);
366
367         /*
368          * Do the main planning.  If we have an inherited target relation,
369          * that needs special processing, else go straight to
370          * grouping_planner.
371          */
372         if (parse->resultRelation &&
373                 (lst = expand_inherited_rtentry(root, parse->resultRelation)) != NIL)
374                 plan = inheritance_planner(root, lst);
375         else
376                 plan = grouping_planner(root, tuple_fraction);
377
378         /*
379          * If any subplans were generated, or if we're inside a subplan, build
380          * initPlan list and extParam/allParam sets for plan nodes, and attach
381          * the initPlans to the top plan node.
382          */
383         if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
384                 SS_finalize_plan(plan, parse->rtable);
385
386         /* Return sort ordering info if caller wants it */
387         if (subquery_pathkeys)
388                 *subquery_pathkeys = root->query_pathkeys;
389
390         /* Return to outer subquery context */
391         PlannerQueryLevel--;
392         PlannerInitPlan = saved_initplan;
393         /* we do NOT restore PlannerPlanId; that's not an oversight! */
394
395         return plan;
396 }
397
398 /*
399  * preprocess_expression
400  *              Do subquery_planner's preprocessing work for an expression,
401  *              which can be a targetlist, a WHERE clause (including JOIN/ON
402  *              conditions), or a HAVING clause.
403  */
404 static Node *
405 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
406 {
407         /*
408          * Fall out quickly if expression is empty.  This occurs often enough
409          * to be worth checking.  Note that null->null is the correct conversion
410          * for implicit-AND result format, too.
411          */
412         if (expr == NULL)
413                 return NULL;
414
415         /*
416          * If the query has any join RTEs, replace join alias variables with
417          * base-relation variables. We must do this before sublink processing,
418          * else sublinks expanded out from join aliases wouldn't get
419          * processed.
420          */
421         if (root->hasJoinRTEs)
422                 expr = flatten_join_alias_vars(root, expr);
423
424         /*
425          * Simplify constant expressions.
426          *
427          * Note: this also flattens nested AND and OR expressions into N-argument
428          * form.  All processing of a qual expression after this point must be
429          * careful to maintain AND/OR flatness --- that is, do not generate a tree
430          * with AND directly under AND, nor OR directly under OR.
431          *
432          * Because this is a relatively expensive process, we skip it when the
433          * query is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()".
434          * The expression will only be evaluated once anyway, so no point in
435          * pre-simplifying; we can't execute it any faster than the executor can,
436          * and we will waste cycles copying the tree.  Notice however that we
437          * still must do it for quals (to get AND/OR flatness); and if we are
438          * in a subquery we should not assume it will be done only once.
439          */
440         if (root->parse->jointree->fromlist != NIL ||
441                 kind == EXPRKIND_QUAL ||
442                 PlannerQueryLevel > 1)
443                 expr = eval_const_expressions(expr);
444
445         /*
446          * If it's a qual or havingQual, canonicalize it.
447          */
448         if (kind == EXPRKIND_QUAL)
449         {
450                 expr = (Node *) canonicalize_qual((Expr *) expr);
451
452 #ifdef OPTIMIZER_DEBUG
453                 printf("After canonicalize_qual()\n");
454                 pprint(expr);
455 #endif
456         }
457
458         /* Expand SubLinks to SubPlans */
459         if (root->parse->hasSubLinks)
460                 expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL));
461
462         /*
463          * XXX do not insert anything here unless you have grokked the
464          * comments in SS_replace_correlation_vars ...
465          */
466
467         /* Replace uplevel vars with Param nodes */
468         if (PlannerQueryLevel > 1)
469                 expr = SS_replace_correlation_vars(expr);
470
471         /*
472          * If it's a qual or havingQual, convert it to implicit-AND format.
473          * (We don't want to do this before eval_const_expressions, since the
474          * latter would be unable to simplify a top-level AND correctly. Also,
475          * SS_process_sublinks expects explicit-AND format.)
476          */
477         if (kind == EXPRKIND_QUAL)
478                 expr = (Node *) make_ands_implicit((Expr *) expr);
479
480         return expr;
481 }
482
483 /*
484  * preprocess_qual_conditions
485  *              Recursively scan the query's jointree and do subquery_planner's
486  *              preprocessing work on each qual condition found therein.
487  */
488 static void
489 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
490 {
491         if (jtnode == NULL)
492                 return;
493         if (IsA(jtnode, RangeTblRef))
494         {
495                 /* nothing to do here */
496         }
497         else if (IsA(jtnode, FromExpr))
498         {
499                 FromExpr   *f = (FromExpr *) jtnode;
500                 ListCell   *l;
501
502                 foreach(l, f->fromlist)
503                         preprocess_qual_conditions(root, lfirst(l));
504
505                 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
506         }
507         else if (IsA(jtnode, JoinExpr))
508         {
509                 JoinExpr   *j = (JoinExpr *) jtnode;
510
511                 preprocess_qual_conditions(root, j->larg);
512                 preprocess_qual_conditions(root, j->rarg);
513
514                 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
515         }
516         else
517                 elog(ERROR, "unrecognized node type: %d",
518                          (int) nodeTag(jtnode));
519 }
520
521 /*--------------------
522  * inheritance_planner
523  *        Generate a plan in the case where the result relation is an
524  *        inheritance set.
525  *
526  * We have to handle this case differently from cases where a source
527  * relation is an inheritance set.      Source inheritance is expanded at
528  * the bottom of the plan tree (see allpaths.c), but target inheritance
529  * has to be expanded at the top.  The reason is that for UPDATE, each
530  * target relation needs a different targetlist matching its own column
531  * set.  (This is not so critical for DELETE, but for simplicity we treat
532  * inherited DELETE the same way.)      Fortunately, the UPDATE/DELETE target
533  * can never be the nullable side of an outer join, so it's OK to generate
534  * the plan this way.
535  *
536  * inheritlist is an integer list of RT indexes for the result relation set.
537  *
538  * Returns a query plan.
539  *--------------------
540  */
541 static Plan *
542 inheritance_planner(PlannerInfo *root, List *inheritlist)
543 {
544         Query      *parse = root->parse;
545         int                     parentRTindex = parse->resultRelation;
546         Oid                     parentOID = getrelid(parentRTindex, parse->rtable);
547         int                     mainrtlength = list_length(parse->rtable);
548         List       *subplans = NIL;
549         List       *tlist = NIL;
550         ListCell   *l;
551
552         foreach(l, inheritlist)
553         {
554                 int                     childRTindex = lfirst_int(l);
555                 Oid                     childOID = getrelid(childRTindex, parse->rtable);
556                 PlannerInfo subroot;
557                 Plan       *subplan;
558
559                 /*
560                  * Generate modified query with this rel as target.  We have to
561                  * be prepared to translate varnos in in_info_list as well as in
562                  * the Query proper.
563                  */
564                 memcpy(&subroot, root, sizeof(PlannerInfo));
565                 subroot.parse = (Query *)
566                         adjust_inherited_attrs((Node *) parse,
567                                                                    parentRTindex, parentOID,
568                                                                    childRTindex, childOID);
569                 subroot.in_info_list = (List *)
570                         adjust_inherited_attrs((Node *) root->in_info_list,
571                                                                    parentRTindex, parentOID,
572                                                                    childRTindex, childOID);
573
574                 /* Generate plan */
575                 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
576
577                 subplans = lappend(subplans, subplan);
578
579                 /*
580                  * XXX my goodness this next bit is ugly.  Really need to think about
581                  * ways to rein in planner's habit of scribbling on its input.
582                  *
583                  * Planning of the subquery might have modified the rangetable,
584                  * either by addition of RTEs due to expansion of inherited source
585                  * tables, or by changes of the Query structures inside subquery
586                  * RTEs.  We have to ensure that this gets propagated back to the
587                  * master copy.  However, if we aren't done planning yet, we also
588                  * need to ensure that subsequent calls to grouping_planner have
589                  * virgin sub-Queries to work from.  So, if we are at the last
590                  * list entry, just copy the subquery rangetable back to the master
591                  * copy; if we are not, then extend the master copy by adding
592                  * whatever the subquery added.  (We assume these added entries
593                  * will go untouched by the future grouping_planner calls.  We are
594                  * also effectively assuming that sub-Queries will get planned
595                  * identically each time, or at least that the impacts on their
596                  * rangetables will be the same each time.  Did I say this is ugly?)
597                  */
598                 if (lnext(l) == NULL)
599                         parse->rtable = subroot.parse->rtable;
600                 else
601                 {
602                         int             subrtlength = list_length(subroot.parse->rtable);
603
604                         if (subrtlength > mainrtlength)
605                         {
606                                 List       *subrt;
607
608                                 subrt = list_copy_tail(subroot.parse->rtable, mainrtlength);
609                                 parse->rtable = list_concat(parse->rtable, subrt);
610                                 mainrtlength = subrtlength;
611                         }
612                 }
613
614                 /* Save preprocessed tlist from first rel for use in Append */
615                 if (tlist == NIL)
616                         tlist = subplan->targetlist;
617         }
618
619         /* Save the target-relations list for the executor, too */
620         parse->resultRelations = inheritlist;
621
622         /* Mark result as unordered (probably unnecessary) */
623         root->query_pathkeys = NIL;
624
625         return (Plan *) make_append(subplans, true, tlist);
626 }
627
628 /*--------------------
629  * grouping_planner
630  *        Perform planning steps related to grouping, aggregation, etc.
631  *        This primarily means adding top-level processing to the basic
632  *        query plan produced by query_planner.
633  *
634  * tuple_fraction is the fraction of tuples we expect will be retrieved
635  *
636  * tuple_fraction is interpreted as follows:
637  *        0: expect all tuples to be retrieved (normal case)
638  *        0 < tuple_fraction < 1: expect the given fraction of tuples available
639  *              from the plan to be retrieved
640  *        tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
641  *              expected to be retrieved (ie, a LIMIT specification)
642  *
643  * Returns a query plan.  Also, root->query_pathkeys is returned as the
644  * actual output ordering of the plan (in pathkey format).
645  *--------------------
646  */
647 static Plan *
648 grouping_planner(PlannerInfo *root, double tuple_fraction)
649 {
650         Query      *parse = root->parse;
651         List       *tlist = parse->targetList;
652         Plan       *result_plan;
653         List       *current_pathkeys;
654         List       *sort_pathkeys;
655
656         /* Tweak caller-supplied tuple_fraction if have LIMIT */
657         if (parse->limitCount != NULL)
658                 tuple_fraction = adjust_tuple_fraction_for_limit(root, tuple_fraction);
659
660         if (parse->setOperations)
661         {
662                 List       *set_sortclauses;
663
664                 /*
665                  * If there's a top-level ORDER BY, assume we have to fetch all
666                  * the tuples.  This might seem too simplistic given all the
667                  * hackery below to possibly avoid the sort ... but a nonzero
668                  * tuple_fraction is only of use to plan_set_operations() when
669                  * the setop is UNION ALL, and the result of UNION ALL is always
670                  * unsorted.
671                  */
672                 if (parse->sortClause)
673                         tuple_fraction = 0.0;
674
675                 /*
676                  * Construct the plan for set operations.  The result will not
677                  * need any work except perhaps a top-level sort and/or LIMIT.
678                  */
679                 result_plan = plan_set_operations(root, tuple_fraction,
680                                                                                   &set_sortclauses);
681
682                 /*
683                  * Calculate pathkeys representing the sort order (if any) of the
684                  * set operation's result.  We have to do this before overwriting
685                  * the sort key information...
686                  */
687                 current_pathkeys = make_pathkeys_for_sortclauses(set_sortclauses,
688                                                                                                 result_plan->targetlist);
689                 current_pathkeys = canonicalize_pathkeys(root, current_pathkeys);
690
691                 /*
692                  * We should not need to call preprocess_targetlist, since we must
693                  * be in a SELECT query node.  Instead, use the targetlist
694                  * returned by plan_set_operations (since this tells whether it
695                  * returned any resjunk columns!), and transfer any sort key
696                  * information from the original tlist.
697                  */
698                 Assert(parse->commandType == CMD_SELECT);
699
700                 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
701
702                 /*
703                  * Can't handle FOR UPDATE/SHARE here (parser should have checked
704                  * already, but let's make sure).
705                  */
706                 if (parse->rowMarks)
707                         ereport(ERROR,
708                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
709                                          errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
710
711                 /*
712                  * Calculate pathkeys that represent result ordering requirements
713                  */
714                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
715                                                                                                           tlist);
716                 sort_pathkeys = canonicalize_pathkeys(root, sort_pathkeys);
717         }
718         else
719         {
720                 /* No set operations, do regular planning */
721                 List       *sub_tlist;
722                 List       *group_pathkeys;
723                 AttrNumber *groupColIdx = NULL;
724                 bool            need_tlist_eval = true;
725                 QualCost        tlist_cost;
726                 double          sub_tuple_fraction;
727                 Path       *cheapest_path;
728                 Path       *sorted_path;
729                 Path       *best_path;
730                 double          dNumGroups = 0;
731                 long            numGroups = 0;
732                 AggClauseCounts agg_counts;
733                 int                     numGroupCols = list_length(parse->groupClause);
734                 bool            use_hashed_grouping = false;
735
736                 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
737
738                 /* Preprocess targetlist */
739                 tlist = preprocess_targetlist(root, tlist);
740
741                 /*
742                  * Generate appropriate target list for subplan; may be different
743                  * from tlist if grouping or aggregation is needed.
744                  */
745                 sub_tlist = make_subplanTargetList(root, tlist,
746                                                                                  &groupColIdx, &need_tlist_eval);
747
748                 /*
749                  * Calculate pathkeys that represent grouping/ordering
750                  * requirements
751                  */
752                 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
753                                                                                                            tlist);
754                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
755                                                                                                           tlist);
756
757                 /*
758                  * Will need actual number of aggregates for estimating costs.
759                  *
760                  * Note: we do not attempt to detect duplicate aggregates here; a
761                  * somewhat-overestimated count is okay for our present purposes.
762                  *
763                  * Note: think not that we can turn off hasAggs if we find no aggs.
764                  * It is possible for constant-expression simplification to remove
765                  * all explicit references to aggs, but we still have to follow
766                  * the aggregate semantics (eg, producing only one output row).
767                  */
768                 if (parse->hasAggs)
769                 {
770                         count_agg_clauses((Node *) tlist, &agg_counts);
771                         count_agg_clauses(parse->havingQual, &agg_counts);
772                 }
773
774                 /*
775                  * Figure out whether we need a sorted result from query_planner.
776                  *
777                  * If we have a GROUP BY clause, then we want a result sorted
778                  * properly for grouping.  Otherwise, if there is an ORDER BY
779                  * clause, we want to sort by the ORDER BY clause.      (Note: if we
780                  * have both, and ORDER BY is a superset of GROUP BY, it would be
781                  * tempting to request sort by ORDER BY --- but that might just
782                  * leave us failing to exploit an available sort order at all.
783                  * Needs more thought...)
784                  */
785                 if (parse->groupClause)
786                         root->query_pathkeys = group_pathkeys;
787                 else if (parse->sortClause)
788                         root->query_pathkeys = sort_pathkeys;
789                 else
790                         root->query_pathkeys = NIL;
791
792                 /*
793                  * With grouping or aggregation, the tuple fraction to pass to
794                  * query_planner() may be different from what it is at top level.
795                  */
796                 sub_tuple_fraction = tuple_fraction;
797
798                 if (parse->groupClause)
799                 {
800                         /*
801                          * In GROUP BY mode, we have the little problem that we don't
802                          * really know how many input tuples will be needed to make a
803                          * group, so we can't translate an output LIMIT count into an
804                          * input count.  For lack of a better idea, assume 25% of the
805                          * input data will be processed if there is any output limit.
806                          * However, if the caller gave us a fraction rather than an
807                          * absolute count, we can keep using that fraction (which
808                          * amounts to assuming that all the groups are about the same
809                          * size).
810                          */
811                         if (sub_tuple_fraction >= 1.0)
812                                 sub_tuple_fraction = 0.25;
813
814                         /*
815                          * If both GROUP BY and ORDER BY are specified, we will need
816                          * two levels of sort --- and, therefore, certainly need to
817                          * read all the input tuples --- unless ORDER BY is a subset
818                          * of GROUP BY.  (We have not yet canonicalized the pathkeys,
819                          * so must use the slower noncanonical comparison method.)
820                          */
821                         if (parse->groupClause && parse->sortClause &&
822                                 !noncanonical_pathkeys_contained_in(sort_pathkeys,
823                                                                                                         group_pathkeys))
824                                 sub_tuple_fraction = 0.0;
825                 }
826                 else if (parse->hasAggs)
827                 {
828                         /*
829                          * Ungrouped aggregate will certainly want all the input
830                          * tuples.
831                          */
832                         sub_tuple_fraction = 0.0;
833                 }
834                 else if (parse->distinctClause)
835                 {
836                         /*
837                          * SELECT DISTINCT, like GROUP, will absorb an unpredictable
838                          * number of input tuples per output tuple.  Handle the same
839                          * way.
840                          */
841                         if (sub_tuple_fraction >= 1.0)
842                                 sub_tuple_fraction = 0.25;
843                 }
844
845                 /*
846                  * Generate the best unsorted and presorted paths for this Query
847                  * (but note there may not be any presorted path).
848                  */
849                 query_planner(root, sub_tlist, sub_tuple_fraction,
850                                           &cheapest_path, &sorted_path);
851
852                 /*
853                  * We couldn't canonicalize group_pathkeys and sort_pathkeys
854                  * before running query_planner(), so do it now.
855                  */
856                 group_pathkeys = canonicalize_pathkeys(root, group_pathkeys);
857                 sort_pathkeys = canonicalize_pathkeys(root, sort_pathkeys);
858
859                 /*
860                  * If grouping, estimate the number of groups.  (We can't do this
861                  * until after running query_planner(), either.)  Then decide
862                  * whether we want to use hashed grouping.
863                  */
864                 if (parse->groupClause)
865                 {
866                         List       *groupExprs;
867                         double          cheapest_path_rows;
868
869                         /*
870                          * Beware of the possibility that cheapest_path->parent is NULL.
871                          * This could happen if user does something silly like
872                          *              SELECT 'foo' GROUP BY 1;
873                          */
874                         if (cheapest_path->parent)
875                                 cheapest_path_rows = cheapest_path->parent->rows;
876                         else
877                                 cheapest_path_rows = 1; /* assume non-set result */
878
879                         groupExprs = get_sortgrouplist_exprs(parse->groupClause,
880                                                                                                  parse->targetList);
881                         dNumGroups = estimate_num_groups(root,
882                                                                                          groupExprs,
883                                                                                          cheapest_path_rows);
884                         /* Also want it as a long int --- but 'ware overflow! */
885                         numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
886
887                         use_hashed_grouping =
888                                 choose_hashed_grouping(root, tuple_fraction,
889                                                                            cheapest_path, sorted_path,
890                                                                            sort_pathkeys, group_pathkeys,
891                                                                            dNumGroups, &agg_counts);
892                 }
893
894                 /*
895                  * Select the best path.  If we are doing hashed grouping, we will
896                  * always read all the input tuples, so use the cheapest-total
897                  * path. Otherwise, trust query_planner's decision about which to use.
898                  */
899                 if (use_hashed_grouping || !sorted_path)
900                         best_path = cheapest_path;
901                 else
902                         best_path = sorted_path;
903
904                 /*
905                  * Check to see if it's possible to optimize MIN/MAX aggregates.
906                  * If so, we will forget all the work we did so far to choose a
907                  * "regular" path ... but we had to do it anyway to be able to
908                  * tell which way is cheaper.
909                  */
910                 result_plan = optimize_minmax_aggregates(root,
911                                                                                                  tlist,
912                                                                                                  best_path);
913                 if (result_plan != NULL)
914                 {
915                         /*
916                          * optimize_minmax_aggregates generated the full plan, with
917                          * the right tlist, and it has no sort order.
918                          */
919                         current_pathkeys = NIL;
920                 }
921                 else
922                 {
923                         /*
924                          * Normal case --- create a plan according to query_planner's
925                          * results.
926                          */
927                         result_plan = create_plan(root, best_path);
928                         current_pathkeys = best_path->pathkeys;
929
930                         /*
931                          * create_plan() returns a plan with just a "flat" tlist of
932                          * required Vars.  Usually we need to insert the sub_tlist as the
933                          * tlist of the top plan node.  However, we can skip that if we
934                          * determined that whatever query_planner chose to return will be
935                          * good enough.
936                          */
937                         if (need_tlist_eval)
938                         {
939                                 /*
940                                  * If the top-level plan node is one that cannot do expression
941                                  * evaluation, we must insert a Result node to project the
942                                  * desired tlist.
943                                  */
944                                 if (!is_projection_capable_plan(result_plan))
945                                 {
946                                         result_plan = (Plan *) make_result(sub_tlist, NULL,
947                                                                                                            result_plan);
948                                 }
949                                 else
950                                 {
951                                         /*
952                                          * Otherwise, just replace the subplan's flat tlist with
953                                          * the desired tlist.
954                                          */
955                                         result_plan->targetlist = sub_tlist;
956                                 }
957
958                                 /*
959                                  * Also, account for the cost of evaluation of the sub_tlist.
960                                  *
961                                  * Up to now, we have only been dealing with "flat" tlists,
962                                  * containing just Vars.  So their evaluation cost is zero
963                                  * according to the model used by cost_qual_eval() (or if you
964                                  * prefer, the cost is factored into cpu_tuple_cost).  Thus we
965                                  * can avoid accounting for tlist cost throughout
966                                  * query_planner() and subroutines.  But now we've inserted a
967                                  * tlist that might contain actual operators, sub-selects, etc
968                                  * --- so we'd better account for its cost.
969                                  *
970                                  * Below this point, any tlist eval cost for added-on nodes
971                                  * should be accounted for as we create those nodes.
972                                  * Presently, of the node types we can add on, only Agg and
973                                  * Group project new tlists (the rest just copy their input
974                                  * tuples) --- so make_agg() and make_group() are responsible
975                                  * for computing the added cost.
976                                  */
977                                 cost_qual_eval(&tlist_cost, sub_tlist);
978                                 result_plan->startup_cost += tlist_cost.startup;
979                                 result_plan->total_cost += tlist_cost.startup +
980                                         tlist_cost.per_tuple * result_plan->plan_rows;
981                         }
982                         else
983                         {
984                                 /*
985                                  * Since we're using query_planner's tlist and not the one
986                                  * make_subplanTargetList calculated, we have to refigure any
987                                  * grouping-column indexes make_subplanTargetList computed.
988                                  */
989                                 locate_grouping_columns(root, tlist, result_plan->targetlist,
990                                                                                 groupColIdx);
991                         }
992
993                         /*
994                          * Insert AGG or GROUP node if needed, plus an explicit sort step
995                          * if necessary.
996                          *
997                          * HAVING clause, if any, becomes qual of the Agg or Group node.
998                          */
999                         if (use_hashed_grouping)
1000                         {
1001                                 /* Hashed aggregate plan --- no sort needed */
1002                                 result_plan = (Plan *) make_agg(root,
1003                                                                                                 tlist,
1004                                                                                                 (List *) parse->havingQual,
1005                                                                                                 AGG_HASHED,
1006                                                                                                 numGroupCols,
1007                                                                                                 groupColIdx,
1008                                                                                                 numGroups,
1009                                                                                                 agg_counts.numAggs,
1010                                                                                                 result_plan);
1011                                 /* Hashed aggregation produces randomly-ordered results */
1012                                 current_pathkeys = NIL;
1013                         }
1014                         else if (parse->hasAggs)
1015                         {
1016                                 /* Plain aggregate plan --- sort if needed */
1017                                 AggStrategy aggstrategy;
1018
1019                                 if (parse->groupClause)
1020                                 {
1021                                         if (!pathkeys_contained_in(group_pathkeys,
1022                                                                                            current_pathkeys))
1023                                         {
1024                                                 result_plan = (Plan *)
1025                                                         make_sort_from_groupcols(root,
1026                                                                                                          parse->groupClause,
1027                                                                                                          groupColIdx,
1028                                                                                                          result_plan);
1029                                                 current_pathkeys = group_pathkeys;
1030                                         }
1031                                         aggstrategy = AGG_SORTED;
1032
1033                                         /*
1034                                          * The AGG node will not change the sort ordering of its
1035                                          * groups, so current_pathkeys describes the result too.
1036                                          */
1037                                 }
1038                                 else
1039                                 {
1040                                         aggstrategy = AGG_PLAIN;
1041                                         /* Result will be only one row anyway; no sort order */
1042                                         current_pathkeys = NIL;
1043                                 }
1044
1045                                 result_plan = (Plan *) make_agg(root,
1046                                                                                                 tlist,
1047                                                                                                 (List *) parse->havingQual,
1048                                                                                                 aggstrategy,
1049                                                                                                 numGroupCols,
1050                                                                                                 groupColIdx,
1051                                                                                                 numGroups,
1052                                                                                                 agg_counts.numAggs,
1053                                                                                                 result_plan);
1054                         }
1055                         else if (parse->groupClause)
1056                         {
1057                                 /*
1058                                  * GROUP BY without aggregation, so insert a group node (plus
1059                                  * the appropriate sort node, if necessary).
1060                                  *
1061                                  * Add an explicit sort if we couldn't make the path come
1062                                  * out the way the GROUP node needs it.
1063                                  */
1064                                 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1065                                 {
1066                                         result_plan = (Plan *)
1067                                                 make_sort_from_groupcols(root,
1068                                                                                                  parse->groupClause,
1069                                                                                                  groupColIdx,
1070                                                                                                  result_plan);
1071                                         current_pathkeys = group_pathkeys;
1072                                 }
1073
1074                                 result_plan = (Plan *) make_group(root,
1075                                                                                                   tlist,
1076                                                                                                   (List *) parse->havingQual,
1077                                                                                                   numGroupCols,
1078                                                                                                   groupColIdx,
1079                                                                                                   dNumGroups,
1080                                                                                                   result_plan);
1081                                 /* The Group node won't change sort ordering */
1082                         }
1083                         else if (root->hasHavingQual)
1084                         {
1085                                 /*
1086                                  * No aggregates, and no GROUP BY, but we have a HAVING qual.
1087                                  * This is a degenerate case in which we are supposed to emit
1088                                  * either 0 or 1 row depending on whether HAVING succeeds.
1089                                  * Furthermore, there cannot be any variables in either HAVING
1090                                  * or the targetlist, so we actually do not need the FROM table
1091                                  * at all!  We can just throw away the plan-so-far and generate
1092                                  * a Result node.  This is a sufficiently unusual corner case
1093                                  * that it's not worth contorting the structure of this routine
1094                                  * to avoid having to generate the plan in the first place.
1095                                  */
1096                                 result_plan = (Plan *) make_result(tlist,
1097                                                                                                    parse->havingQual,
1098                                                                                                    NULL);
1099                         }
1100                 }                                               /* end of non-minmax-aggregate case */
1101         }                                                       /* end of if (setOperations) */
1102
1103         /*
1104          * If we were not able to make the plan come out in the right order,
1105          * add an explicit sort step.
1106          */
1107         if (parse->sortClause)
1108         {
1109                 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1110                 {
1111                         result_plan = (Plan *)
1112                                 make_sort_from_sortclauses(root,
1113                                                                                    parse->sortClause,
1114                                                                                    result_plan);
1115                         current_pathkeys = sort_pathkeys;
1116                 }
1117         }
1118
1119         /*
1120          * If there is a DISTINCT clause, add the UNIQUE node.
1121          */
1122         if (parse->distinctClause)
1123         {
1124                 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1125
1126                 /*
1127                  * If there was grouping or aggregation, leave plan_rows as-is
1128                  * (ie, assume the result was already mostly unique).  If not,
1129                  * it's reasonable to assume the UNIQUE filter has effects
1130                  * comparable to GROUP BY.
1131                  */
1132                 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1133                 {
1134                         List       *distinctExprs;
1135
1136                         distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
1137                                                                                                         parse->targetList);
1138                         result_plan->plan_rows = estimate_num_groups(root,
1139                                                                                                                  distinctExprs,
1140                                                                                                  result_plan->plan_rows);
1141                 }
1142         }
1143
1144         /*
1145          * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1146          */
1147         if (parse->limitOffset || parse->limitCount)
1148         {
1149                 result_plan = (Plan *) make_limit(result_plan,
1150                                                                                   parse->limitOffset,
1151                                                                                   parse->limitCount);
1152         }
1153
1154         /*
1155          * Return the actual output ordering in query_pathkeys for possible
1156          * use by an outer query level.
1157          */
1158         root->query_pathkeys = current_pathkeys;
1159
1160         return result_plan;
1161 }
1162
1163 /*
1164  * adjust_tuple_fraction_for_limit - adjust tuple fraction for LIMIT
1165  *
1166  * If the query contains LIMIT, we adjust the caller-supplied tuple_fraction
1167  * accordingly.  This is not overridable by the caller, since it reflects plan
1168  * actions that grouping_planner() will certainly take, not assumptions about
1169  * context.
1170  */
1171 static double
1172 adjust_tuple_fraction_for_limit(PlannerInfo *root, double tuple_fraction)
1173 {
1174         Query      *parse = root->parse;
1175         double          limit_fraction = 0.0;
1176
1177         /* Should not be called unless LIMIT */
1178         Assert(parse->limitCount != NULL);
1179
1180         /*
1181          * A LIMIT clause limits the absolute number of tuples returned. However,
1182          * if it's not a constant LIMIT then we have to punt; for lack of a better
1183          * idea, assume 10% of the plan's result is wanted.
1184          */
1185         if (IsA(parse->limitCount, Const))
1186         {
1187                 Const      *limitc = (Const *) parse->limitCount;
1188                 int32           count = DatumGetInt32(limitc->constvalue);
1189
1190                 /*
1191                  * A NULL-constant LIMIT represents "LIMIT ALL", which we treat the
1192                  * same as no limit (ie, expect to retrieve all the tuples).
1193                  */
1194                 if (!limitc->constisnull && count > 0)
1195                 {
1196                         limit_fraction = (double) count;
1197                         /* We must also consider the OFFSET, if present */
1198                         if (parse->limitOffset != NULL)
1199                         {
1200                                 if (IsA(parse->limitOffset, Const))
1201                                 {
1202                                         int32           offset;
1203
1204                                         limitc = (Const *) parse->limitOffset;
1205                                         offset = DatumGetInt32(limitc->constvalue);
1206                                         if (!limitc->constisnull && offset > 0)
1207                                                 limit_fraction += (double) offset;
1208                                 }
1209                                 else
1210                                 {
1211                                         /* OFFSET is an expression ... punt ... */
1212                                         limit_fraction = 0.10;
1213                                 }
1214                         }
1215                 }
1216         }
1217         else
1218         {
1219                 /* LIMIT is an expression ... punt ... */
1220                 limit_fraction = 0.10;
1221         }
1222
1223         if (limit_fraction > 0.0)
1224         {
1225                 /*
1226                  * If we have absolute limits from both caller and LIMIT, use the
1227                  * smaller value; if one is fractional and the other absolute,
1228                  * treat the fraction as a fraction of the absolute value;
1229                  * else we can multiply the two fractions together.
1230                  */
1231                 if (tuple_fraction >= 1.0)
1232                 {
1233                         if (limit_fraction >= 1.0)
1234                         {
1235                                 /* both absolute */
1236                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
1237                         }
1238                         else
1239                         {
1240                                 /* caller absolute, limit fractional */
1241                                 tuple_fraction *= limit_fraction;
1242                                 if (tuple_fraction < 1.0)
1243                                         tuple_fraction = 1.0;
1244                         }
1245                 }
1246                 else if (tuple_fraction > 0.0)
1247                 {
1248                         if (limit_fraction >= 1.0)
1249                         {
1250                                 /* caller fractional, limit absolute */
1251                                 tuple_fraction *= limit_fraction;
1252                                 if (tuple_fraction < 1.0)
1253                                         tuple_fraction = 1.0;
1254                         }
1255                         else
1256                         {
1257                                 /* both fractional */
1258                                 tuple_fraction *= limit_fraction;
1259                         }
1260                 }
1261                 else
1262                 {
1263                         /* no info from caller, just use limit */
1264                         tuple_fraction = limit_fraction;
1265                 }
1266         }
1267
1268         return tuple_fraction;
1269 }
1270
1271 /*
1272  * choose_hashed_grouping - should we use hashed grouping?
1273  */
1274 static bool
1275 choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
1276                                            Path *cheapest_path, Path *sorted_path,
1277                                            List *sort_pathkeys, List *group_pathkeys,
1278                                            double dNumGroups, AggClauseCounts *agg_counts)
1279 {
1280         int                     numGroupCols = list_length(root->parse->groupClause);
1281         double          cheapest_path_rows;
1282         int                     cheapest_path_width;
1283         Size            hashentrysize;
1284         List       *current_pathkeys;
1285         Path            hashed_p;
1286         Path            sorted_p;
1287
1288         /*
1289          * Check can't-do-it conditions, including whether the grouping operators
1290          * are hashjoinable.
1291          *
1292          * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1293          * (Doing so would imply storing *all* the input values in the hash table,
1294          * which seems like a certain loser.)
1295          */
1296         if (!enable_hashagg)
1297                 return false;
1298         if (agg_counts->numDistinctAggs != 0)
1299                 return false;
1300         if (!hash_safe_grouping(root))
1301                 return false;
1302
1303         /*
1304          * Don't do it if it doesn't look like the hashtable will fit into
1305          * work_mem.
1306          *
1307          * Beware here of the possibility that cheapest_path->parent is NULL.
1308          * This could happen if user does something silly like
1309          *              SELECT 'foo' GROUP BY 1;
1310          */
1311         if (cheapest_path->parent)
1312         {
1313                 cheapest_path_rows = cheapest_path->parent->rows;
1314                 cheapest_path_width = cheapest_path->parent->width;
1315         }
1316         else
1317         {
1318                 cheapest_path_rows = 1;                         /* assume non-set result */
1319                 cheapest_path_width = 100;                      /* arbitrary */
1320         }
1321
1322         /* Estimate per-hash-entry space at tuple width... */
1323         hashentrysize = cheapest_path_width;
1324         /* plus space for pass-by-ref transition values... */
1325         hashentrysize += agg_counts->transitionSpace;
1326         /* plus the per-hash-entry overhead */
1327         hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1328
1329         if (hashentrysize * dNumGroups > work_mem * 1024L)
1330                 return false;
1331
1332         /*
1333          * See if the estimated cost is no more than doing it the other way.
1334          * While avoiding the need for sorted input is usually a win, the fact
1335          * that the output won't be sorted may be a loss; so we need to do an
1336          * actual cost comparison.
1337          *
1338          * We need to consider
1339          *              cheapest_path + hashagg [+ final sort]
1340          * versus either
1341          *              cheapest_path [+ sort] + group or agg [+ final sort]
1342          * or
1343          *              presorted_path + group or agg [+ final sort]
1344          * where brackets indicate a step that may not be needed. We assume
1345          * query_planner() will have returned a presorted path only if it's a
1346          * winner compared to cheapest_path for this purpose.
1347          *
1348          * These path variables are dummies that just hold cost fields; we don't
1349          * make actual Paths for these steps.
1350          */
1351         cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1352                          numGroupCols, dNumGroups,
1353                          cheapest_path->startup_cost, cheapest_path->total_cost,
1354                          cheapest_path_rows);
1355         /* Result of hashed agg is always unsorted */
1356         if (sort_pathkeys)
1357                 cost_sort(&hashed_p, root, sort_pathkeys, hashed_p.total_cost,
1358                                   dNumGroups, cheapest_path_width);
1359
1360         if (sorted_path)
1361         {
1362                 sorted_p.startup_cost = sorted_path->startup_cost;
1363                 sorted_p.total_cost = sorted_path->total_cost;
1364                 current_pathkeys = sorted_path->pathkeys;
1365         }
1366         else
1367         {
1368                 sorted_p.startup_cost = cheapest_path->startup_cost;
1369                 sorted_p.total_cost = cheapest_path->total_cost;
1370                 current_pathkeys = cheapest_path->pathkeys;
1371         }
1372         if (!pathkeys_contained_in(group_pathkeys,
1373                                                            current_pathkeys))
1374         {
1375                 cost_sort(&sorted_p, root, group_pathkeys, sorted_p.total_cost,
1376                                   cheapest_path_rows, cheapest_path_width);
1377                 current_pathkeys = group_pathkeys;
1378         }
1379
1380         if (root->parse->hasAggs)
1381                 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1382                                  numGroupCols, dNumGroups,
1383                                  sorted_p.startup_cost, sorted_p.total_cost,
1384                                  cheapest_path_rows);
1385         else
1386                 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1387                                    sorted_p.startup_cost, sorted_p.total_cost,
1388                                    cheapest_path_rows);
1389         /* The Agg or Group node will preserve ordering */
1390         if (sort_pathkeys &&
1391                 !pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1392                 cost_sort(&sorted_p, root, sort_pathkeys, sorted_p.total_cost,
1393                                   dNumGroups, cheapest_path_width);
1394
1395         /*
1396          * Now make the decision using the top-level tuple fraction.  First we
1397          * have to convert an absolute count (LIMIT) into fractional form.
1398          */
1399         if (tuple_fraction >= 1.0)
1400                 tuple_fraction /= dNumGroups;
1401
1402         if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1403                                                                           tuple_fraction) < 0)
1404         {
1405                 /* Hashed is cheaper, so use it */
1406                 return true;
1407         }
1408         return false;
1409 }
1410
1411 /*
1412  * hash_safe_grouping - are grouping operators hashable?
1413  *
1414  * We assume hashed aggregation will work if the datatype's equality operator
1415  * is marked hashjoinable.
1416  */
1417 static bool
1418 hash_safe_grouping(PlannerInfo *root)
1419 {
1420         ListCell   *gl;
1421
1422         foreach(gl, root->parse->groupClause)
1423         {
1424                 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1425                 TargetEntry *tle = get_sortgroupclause_tle(grpcl,
1426                                                                                                    root->parse->targetList);
1427                 Operator        optup;
1428                 bool            oprcanhash;
1429
1430                 optup = equality_oper(exprType((Node *) tle->expr), true);
1431                 if (!optup)
1432                         return false;
1433                 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1434                 ReleaseSysCache(optup);
1435                 if (!oprcanhash)
1436                         return false;
1437         }
1438         return true;
1439 }
1440
1441 /*---------------
1442  * make_subplanTargetList
1443  *        Generate appropriate target list when grouping is required.
1444  *
1445  * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1446  * above the result of query_planner, we typically want to pass a different
1447  * target list to query_planner than the outer plan nodes should have.
1448  * This routine generates the correct target list for the subplan.
1449  *
1450  * The initial target list passed from the parser already contains entries
1451  * for all ORDER BY and GROUP BY expressions, but it will not have entries
1452  * for variables used only in HAVING clauses; so we need to add those
1453  * variables to the subplan target list.  Also, we flatten all expressions
1454  * except GROUP BY items into their component variables; the other expressions
1455  * will be computed by the inserted nodes rather than by the subplan.
1456  * For example, given a query like
1457  *              SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1458  * we want to pass this targetlist to the subplan:
1459  *              a,b,c,d,a+b
1460  * where the a+b target will be used by the Sort/Group steps, and the
1461  * other targets will be used for computing the final results.  (In the
1462  * above example we could theoretically suppress the a and b targets and
1463  * pass down only c,d,a+b, but it's not really worth the trouble to
1464  * eliminate simple var references from the subplan.  We will avoid doing
1465  * the extra computation to recompute a+b at the outer level; see
1466  * replace_vars_with_subplan_refs() in setrefs.c.)
1467  *
1468  * If we are grouping or aggregating, *and* there are no non-Var grouping
1469  * expressions, then the returned tlist is effectively dummy; we do not
1470  * need to force it to be evaluated, because all the Vars it contains
1471  * should be present in the output of query_planner anyway.
1472  *
1473  * 'tlist' is the query's target list.
1474  * 'groupColIdx' receives an array of column numbers for the GROUP BY
1475  *                      expressions (if there are any) in the subplan's target list.
1476  * 'need_tlist_eval' is set true if we really need to evaluate the
1477  *                      result tlist.
1478  *
1479  * The result is the targetlist to be passed to the subplan.
1480  *---------------
1481  */
1482 static List *
1483 make_subplanTargetList(PlannerInfo *root,
1484                                            List *tlist,
1485                                            AttrNumber **groupColIdx,
1486                                            bool *need_tlist_eval)
1487 {
1488         Query      *parse = root->parse;
1489         List       *sub_tlist;
1490         List       *extravars;
1491         int                     numCols;
1492
1493         *groupColIdx = NULL;
1494
1495         /*
1496          * If we're not grouping or aggregating, there's nothing to do here;
1497          * query_planner should receive the unmodified target list.
1498          */
1499         if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1500         {
1501                 *need_tlist_eval = true;
1502                 return tlist;
1503         }
1504
1505         /*
1506          * Otherwise, start with a "flattened" tlist (having just the vars
1507          * mentioned in the targetlist and HAVING qual --- but not upper-
1508          * level Vars; they will be replaced by Params later on).
1509          */
1510         sub_tlist = flatten_tlist(tlist);
1511         extravars = pull_var_clause(parse->havingQual, false);
1512         sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1513         list_free(extravars);
1514         *need_tlist_eval = false;       /* only eval if not flat tlist */
1515
1516         /*
1517          * If grouping, create sub_tlist entries for all GROUP BY expressions
1518          * (GROUP BY items that are simple Vars should be in the list
1519          * already), and make an array showing where the group columns are in
1520          * the sub_tlist.
1521          */
1522         numCols = list_length(parse->groupClause);
1523         if (numCols > 0)
1524         {
1525                 int                     keyno = 0;
1526                 AttrNumber *grpColIdx;
1527                 ListCell   *gl;
1528
1529                 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1530                 *groupColIdx = grpColIdx;
1531
1532                 foreach(gl, parse->groupClause)
1533                 {
1534                         GroupClause *grpcl = (GroupClause *) lfirst(gl);
1535                         Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1536                         TargetEntry *te = NULL;
1537                         ListCell   *sl;
1538
1539                         /* Find or make a matching sub_tlist entry */
1540                         foreach(sl, sub_tlist)
1541                         {
1542                                 te = (TargetEntry *) lfirst(sl);
1543                                 if (equal(groupexpr, te->expr))
1544                                         break;
1545                         }
1546                         if (!sl)
1547                         {
1548                                 te = makeTargetEntry((Expr *) groupexpr,
1549                                                                          list_length(sub_tlist) + 1,
1550                                                                          NULL,
1551                                                                          false);
1552                                 sub_tlist = lappend(sub_tlist, te);
1553                                 *need_tlist_eval = true;                /* it's not flat anymore */
1554                         }
1555
1556                         /* and save its resno */
1557                         grpColIdx[keyno++] = te->resno;
1558                 }
1559         }
1560
1561         return sub_tlist;
1562 }
1563
1564 /*
1565  * locate_grouping_columns
1566  *              Locate grouping columns in the tlist chosen by query_planner.
1567  *
1568  * This is only needed if we don't use the sub_tlist chosen by
1569  * make_subplanTargetList.      We have to forget the column indexes found
1570  * by that routine and re-locate the grouping vars in the real sub_tlist.
1571  */
1572 static void
1573 locate_grouping_columns(PlannerInfo *root,
1574                                                 List *tlist,
1575                                                 List *sub_tlist,
1576                                                 AttrNumber *groupColIdx)
1577 {
1578         int                     keyno = 0;
1579         ListCell   *gl;
1580
1581         /*
1582          * No work unless grouping.
1583          */
1584         if (!root->parse->groupClause)
1585         {
1586                 Assert(groupColIdx == NULL);
1587                 return;
1588         }
1589         Assert(groupColIdx != NULL);
1590
1591         foreach(gl, root->parse->groupClause)
1592         {
1593                 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1594                 Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1595                 TargetEntry *te = NULL;
1596                 ListCell   *sl;
1597
1598                 foreach(sl, sub_tlist)
1599                 {
1600                         te = (TargetEntry *) lfirst(sl);
1601                         if (equal(groupexpr, te->expr))
1602                                 break;
1603                 }
1604                 if (!sl)
1605                         elog(ERROR, "failed to locate grouping columns");
1606
1607                 groupColIdx[keyno++] = te->resno;
1608         }
1609 }
1610
1611 /*
1612  * postprocess_setop_tlist
1613  *        Fix up targetlist returned by plan_set_operations().
1614  *
1615  * We need to transpose sort key info from the orig_tlist into new_tlist.
1616  * NOTE: this would not be good enough if we supported resjunk sort keys
1617  * for results of set operations --- then, we'd need to project a whole
1618  * new tlist to evaluate the resjunk columns.  For now, just ereport if we
1619  * find any resjunk columns in orig_tlist.
1620  */
1621 static List *
1622 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1623 {
1624         ListCell   *l;
1625         ListCell   *orig_tlist_item = list_head(orig_tlist);
1626
1627         foreach(l, new_tlist)
1628         {
1629                 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1630                 TargetEntry *orig_tle;
1631
1632                 /* ignore resjunk columns in setop result */
1633                 if (new_tle->resjunk)
1634                         continue;
1635
1636                 Assert(orig_tlist_item != NULL);
1637                 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1638                 orig_tlist_item = lnext(orig_tlist_item);
1639                 if (orig_tle->resjunk)                  /* should not happen */
1640                         elog(ERROR, "resjunk output columns are not implemented");
1641                 Assert(new_tle->resno == orig_tle->resno);
1642                 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1643         }
1644         if (orig_tlist_item != NULL)
1645                 elog(ERROR, "resjunk output columns are not implemented");
1646         return new_tlist;
1647 }