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