]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/planner.c
If a LIMIT is applied to a UNION ALL query, plan each UNION arm as
[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.189 2005/06/10 02:21:04 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         bool            hasOuterJoins;
198         List       *newHaving;
199         List       *lst;
200         ListCell   *l;
201
202         /* Set up for a new level of subquery */
203         PlannerQueryLevel++;
204         PlannerInitPlan = NIL;
205
206         /* Create a PlannerInfo data structure for this subquery */
207         root = makeNode(PlannerInfo);
208         root->parse = parse;
209
210         /*
211          * Look for IN clauses at the top level of WHERE, and transform them
212          * into joins.  Note that this step only handles IN clauses originally
213          * at top level of WHERE; if we pull up any subqueries in the next
214          * step, their INs are processed just before pulling them up.
215          */
216         root->in_info_list = NIL;
217         if (parse->hasSubLinks)
218                 parse->jointree->quals = pull_up_IN_clauses(root,
219                                                                                                         parse->jointree->quals);
220
221         /*
222          * Check to see if any subqueries in the rangetable can be merged into
223          * this query.
224          */
225         parse->jointree = (FromExpr *)
226                 pull_up_subqueries(root, (Node *) parse->jointree, false);
227
228         /*
229          * Detect whether any rangetable entries are RTE_JOIN kind; if not, we
230          * can avoid the expense of doing flatten_join_alias_vars().  Also
231          * check for outer joins --- if none, we can skip
232          * reduce_outer_joins(). This must be done after we have done
233          * pull_up_subqueries, of course.
234          */
235         root->hasJoinRTEs = false;
236         hasOuterJoins = false;
237         foreach(l, parse->rtable)
238         {
239                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
240
241                 if (rte->rtekind == RTE_JOIN)
242                 {
243                         root->hasJoinRTEs = true;
244                         if (IS_OUTER_JOIN(rte->jointype))
245                         {
246                                 hasOuterJoins = true;
247                                 /* Can quit scanning once we find an outer join */
248                                 break;
249                         }
250                 }
251         }
252
253         /*
254          * Set hasHavingQual to remember if HAVING clause is present.  Needed
255          * because preprocess_expression will reduce a constant-true condition
256          * to an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
257          */
258         root->hasHavingQual = (parse->havingQual != NULL);
259
260         /*
261          * Do expression preprocessing on targetlist and quals.
262          */
263         parse->targetList = (List *)
264                 preprocess_expression(root, (Node *) parse->targetList,
265                                                           EXPRKIND_TARGET);
266
267         preprocess_qual_conditions(root, (Node *) parse->jointree);
268
269         parse->havingQual = preprocess_expression(root, parse->havingQual,
270                                                                                           EXPRKIND_QUAL);
271
272         parse->limitOffset = preprocess_expression(root, parse->limitOffset,
273                                                                                            EXPRKIND_LIMIT);
274         parse->limitCount = preprocess_expression(root, parse->limitCount,
275                                                                                           EXPRKIND_LIMIT);
276
277         root->in_info_list = (List *)
278                 preprocess_expression(root, (Node *) root->in_info_list,
279                                                           EXPRKIND_ININFO);
280
281         /* Also need to preprocess expressions for function RTEs */
282         foreach(l, parse->rtable)
283         {
284                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
285
286                 if (rte->rtekind == RTE_FUNCTION)
287                         rte->funcexpr = preprocess_expression(root, rte->funcexpr,
288                                                                                                   EXPRKIND_RTFUNC);
289         }
290
291         /*
292          * In some cases we may want to transfer a HAVING clause into WHERE.
293          * We cannot do so if the HAVING clause contains aggregates (obviously)
294          * or volatile functions (since a HAVING clause is supposed to be executed
295          * only once per group).  Also, it may be that the clause is so expensive
296          * to execute that we're better off doing it only once per group, despite
297          * the loss of selectivity.  This is hard to estimate short of doing the
298          * entire planning process twice, so we use a heuristic: clauses
299          * containing subplans are left in HAVING.  Otherwise, we move or copy
300          * the HAVING clause into WHERE, in hopes of eliminating tuples before
301          * aggregation instead of after.
302          *
303          * If the query has explicit grouping then we can simply move such a
304          * clause into WHERE; any group that fails the clause will not be
305          * in the output because none of its tuples will reach the grouping
306          * or aggregation stage.  Otherwise we must have a degenerate
307          * (variable-free) HAVING clause, which we put in WHERE so that
308          * query_planner() can use it in a gating Result node, but also keep
309          * in HAVING to ensure that we don't emit a bogus aggregated row.
310          * (This could be done better, but it seems not worth optimizing.)
311          *
312          * Note that both havingQual and parse->jointree->quals are in
313          * implicitly-ANDed-list form at this point, even though they are
314          * declared as Node *.
315          */
316         newHaving = NIL;
317         foreach(l, (List *) parse->havingQual)
318         {
319                 Node       *havingclause = (Node *) lfirst(l);
320
321                 if (contain_agg_clause(havingclause) ||
322                         contain_volatile_functions(havingclause) ||
323                         contain_subplans(havingclause))
324                 {
325                         /* keep it in HAVING */
326                         newHaving = lappend(newHaving, havingclause);
327                 }
328                 else if (parse->groupClause)
329                 {
330                         /* move it to WHERE */
331                         parse->jointree->quals = (Node *)
332                                 lappend((List *) parse->jointree->quals, havingclause);
333                 }
334                 else
335                 {
336                         /* put a copy in WHERE, keep it in HAVING */
337                         parse->jointree->quals = (Node *)
338                                 lappend((List *) parse->jointree->quals,
339                                                 copyObject(havingclause));
340                         newHaving = lappend(newHaving, havingclause);
341                 }
342         }
343         parse->havingQual = (Node *) newHaving;
344
345         /*
346          * If we have any outer joins, try to reduce them to plain inner
347          * joins. This step is most easily done after we've done expression
348          * preprocessing.
349          */
350         if (hasOuterJoins)
351                 reduce_outer_joins(root);
352
353         /*
354          * See if we can simplify the jointree; opportunities for this may
355          * come from having pulled up subqueries, or from flattening explicit
356          * JOIN syntax.  We must do this after flattening JOIN alias
357          * variables, since eliminating explicit JOIN nodes from the jointree
358          * will cause get_relids_for_join() to fail.  But it should happen
359          * after reduce_outer_joins, anyway.
360          */
361         parse->jointree = (FromExpr *)
362                 simplify_jointree(root, (Node *) parse->jointree);
363
364         /*
365          * Do the main planning.  If we have an inherited target relation,
366          * that needs special processing, else go straight to
367          * grouping_planner.
368          */
369         if (parse->resultRelation &&
370                 (lst = expand_inherited_rtentry(root, parse->resultRelation)) != NIL)
371                 plan = inheritance_planner(root, lst);
372         else
373                 plan = grouping_planner(root, tuple_fraction);
374
375         /*
376          * If any subplans were generated, or if we're inside a subplan, build
377          * initPlan list and extParam/allParam sets for plan nodes, and attach
378          * the initPlans to the top plan node.
379          */
380         if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
381                 SS_finalize_plan(plan, parse->rtable);
382
383         /* Return sort ordering info if caller wants it */
384         if (subquery_pathkeys)
385                 *subquery_pathkeys = root->query_pathkeys;
386
387         /* Return to outer subquery context */
388         PlannerQueryLevel--;
389         PlannerInitPlan = saved_initplan;
390         /* we do NOT restore PlannerPlanId; that's not an oversight! */
391
392         return plan;
393 }
394
395 /*
396  * preprocess_expression
397  *              Do subquery_planner's preprocessing work for an expression,
398  *              which can be a targetlist, a WHERE clause (including JOIN/ON
399  *              conditions), or a HAVING clause.
400  */
401 static Node *
402 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
403 {
404         /*
405          * Fall out quickly if expression is empty.  This occurs often enough
406          * to be worth checking.  Note that null->null is the correct conversion
407          * for implicit-AND result format, too.
408          */
409         if (expr == NULL)
410                 return NULL;
411
412         /*
413          * If the query has any join RTEs, replace join alias variables with
414          * base-relation variables. We must do this before sublink processing,
415          * else sublinks expanded out from join aliases wouldn't get
416          * 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
430          * query is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()".
431          * The 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
435          * in a 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
461          * comments in 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.
470          * (We don't want to do this before eval_const_expressions, since the
471          * latter 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
558                  * be prepared to translate varnos in in_info_list as well as in
559                  * the 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,
581                  * either by addition of RTEs due to expansion of inherited source
582                  * tables, or by changes of the Query structures inside subquery
583                  * RTEs.  We have to ensure that this gets propagated back to the
584                  * master copy.  However, if we aren't done planning yet, we also
585                  * need to ensure that subsequent calls to grouping_planner have
586                  * virgin sub-Queries to work from.  So, if we are at the last
587                  * list entry, just copy the subquery rangetable back to the master
588                  * copy; if we are not, then extend the master copy by adding
589                  * whatever the subquery added.  (We assume these added entries
590                  * will go untouched by the future grouping_planner calls.  We are
591                  * also effectively assuming that sub-Queries will get planned
592                  * identically each time, or at least that the impacts on their
593                  * rangetables will be the same each time.  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         Plan       *result_plan;
650         List       *current_pathkeys;
651         List       *sort_pathkeys;
652
653         /* Tweak caller-supplied tuple_fraction if have LIMIT */
654         if (parse->limitCount != NULL)
655                 tuple_fraction = adjust_tuple_fraction_for_limit(root, tuple_fraction);
656
657         if (parse->setOperations)
658         {
659                 List       *set_sortclauses;
660
661                 /*
662                  * If there's a top-level ORDER BY, assume we have to fetch all
663                  * the tuples.  This might seem too simplistic given all the
664                  * hackery below to possibly avoid the sort ... but a nonzero
665                  * tuple_fraction is only of use to plan_set_operations() when
666                  * the setop is UNION ALL, and the result of UNION ALL is always
667                  * unsorted.
668                  */
669                 if (parse->sortClause)
670                         tuple_fraction = 0.0;
671
672                 /*
673                  * Construct the plan for set operations.  The result will not
674                  * need any work except perhaps a top-level sort and/or LIMIT.
675                  */
676                 result_plan = plan_set_operations(root, tuple_fraction,
677                                                                                   &set_sortclauses);
678
679                 /*
680                  * Calculate pathkeys representing the sort order (if any) of the
681                  * set operation's result.  We have to do this before overwriting
682                  * the sort key information...
683                  */
684                 current_pathkeys = make_pathkeys_for_sortclauses(set_sortclauses,
685                                                                                                 result_plan->targetlist);
686                 current_pathkeys = canonicalize_pathkeys(root, current_pathkeys);
687
688                 /*
689                  * We should not need to call preprocess_targetlist, since we must
690                  * be in a SELECT query node.  Instead, use the targetlist
691                  * returned by plan_set_operations (since this tells whether it
692                  * returned any resjunk columns!), and transfer any sort key
693                  * information from the original tlist.
694                  */
695                 Assert(parse->commandType == CMD_SELECT);
696
697                 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
698
699                 /*
700                  * Can't handle FOR UPDATE/SHARE here (parser should have checked
701                  * already, but let's make sure).
702                  */
703                 if (parse->rowMarks)
704                         ereport(ERROR,
705                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
706                                          errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
707
708                 /*
709                  * Calculate pathkeys that represent result ordering requirements
710                  */
711                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
712                                                                                                           tlist);
713                 sort_pathkeys = canonicalize_pathkeys(root, sort_pathkeys);
714         }
715         else
716         {
717                 /* No set operations, do regular planning */
718                 List       *sub_tlist;
719                 List       *group_pathkeys;
720                 AttrNumber *groupColIdx = NULL;
721                 bool            need_tlist_eval = true;
722                 QualCost        tlist_cost;
723                 double          sub_tuple_fraction;
724                 Path       *cheapest_path;
725                 Path       *sorted_path;
726                 Path       *best_path;
727                 double          dNumGroups = 0;
728                 long            numGroups = 0;
729                 AggClauseCounts agg_counts;
730                 int                     numGroupCols = list_length(parse->groupClause);
731                 bool            use_hashed_grouping = false;
732
733                 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
734
735                 /* Preprocess targetlist */
736                 tlist = preprocess_targetlist(root, tlist);
737
738                 /*
739                  * Generate appropriate target list for subplan; may be different
740                  * from tlist if grouping or aggregation is needed.
741                  */
742                 sub_tlist = make_subplanTargetList(root, tlist,
743                                                                                  &groupColIdx, &need_tlist_eval);
744
745                 /*
746                  * Calculate pathkeys that represent grouping/ordering
747                  * requirements
748                  */
749                 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
750                                                                                                            tlist);
751                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
752                                                                                                           tlist);
753
754                 /*
755                  * Will need actual number of aggregates for estimating costs.
756                  *
757                  * Note: we do not attempt to detect duplicate aggregates here; a
758                  * somewhat-overestimated count is okay for our present purposes.
759                  *
760                  * Note: think not that we can turn off hasAggs if we find no aggs.
761                  * It is possible for constant-expression simplification to remove
762                  * all explicit references to aggs, but we still have to follow
763                  * the aggregate semantics (eg, producing only one output row).
764                  */
765                 if (parse->hasAggs)
766                 {
767                         count_agg_clauses((Node *) tlist, &agg_counts);
768                         count_agg_clauses(parse->havingQual, &agg_counts);
769                 }
770
771                 /*
772                  * Figure out whether we need a sorted result from query_planner.
773                  *
774                  * If we have a GROUP BY clause, then we want a result sorted
775                  * properly for grouping.  Otherwise, if there is an ORDER BY
776                  * clause, we want to sort by the ORDER BY clause.      (Note: if we
777                  * have both, and ORDER BY is a superset of GROUP BY, it would be
778                  * tempting to request sort by ORDER BY --- but that might just
779                  * leave us failing to exploit an available sort order at all.
780                  * Needs more thought...)
781                  */
782                 if (parse->groupClause)
783                         root->query_pathkeys = group_pathkeys;
784                 else if (parse->sortClause)
785                         root->query_pathkeys = sort_pathkeys;
786                 else
787                         root->query_pathkeys = NIL;
788
789                 /*
790                  * With grouping or aggregation, the tuple fraction to pass to
791                  * query_planner() may be different from what it is at top level.
792                  */
793                 sub_tuple_fraction = tuple_fraction;
794
795                 if (parse->groupClause)
796                 {
797                         /*
798                          * In GROUP BY mode, we have the little problem that we don't
799                          * really know how many input tuples will be needed to make a
800                          * group, so we can't translate an output LIMIT count into an
801                          * input count.  For lack of a better idea, assume 25% of the
802                          * input data will be processed if there is any output limit.
803                          * However, if the caller gave us a fraction rather than an
804                          * absolute count, we can keep using that fraction (which
805                          * amounts to assuming that all the groups are about the same
806                          * size).
807                          */
808                         if (sub_tuple_fraction >= 1.0)
809                                 sub_tuple_fraction = 0.25;
810
811                         /*
812                          * If both GROUP BY and ORDER BY are specified, we will need
813                          * two levels of sort --- and, therefore, certainly need to
814                          * read all the input tuples --- unless ORDER BY is a subset
815                          * of GROUP BY.  (We have not yet canonicalized the pathkeys,
816                          * so must use the slower noncanonical comparison method.)
817                          */
818                         if (parse->groupClause && parse->sortClause &&
819                                 !noncanonical_pathkeys_contained_in(sort_pathkeys,
820                                                                                                         group_pathkeys))
821                                 sub_tuple_fraction = 0.0;
822                 }
823                 else if (parse->hasAggs)
824                 {
825                         /*
826                          * Ungrouped aggregate will certainly want all the input
827                          * tuples.
828                          */
829                         sub_tuple_fraction = 0.0;
830                 }
831                 else if (parse->distinctClause)
832                 {
833                         /*
834                          * SELECT DISTINCT, like GROUP, will absorb an unpredictable
835                          * number of input tuples per output tuple.  Handle the same
836                          * way.
837                          */
838                         if (sub_tuple_fraction >= 1.0)
839                                 sub_tuple_fraction = 0.25;
840                 }
841
842                 /*
843                  * Generate the best unsorted and presorted paths for this Query
844                  * (but note there may not be any presorted path).
845                  */
846                 query_planner(root, sub_tlist, sub_tuple_fraction,
847                                           &cheapest_path, &sorted_path);
848
849                 /*
850                  * We couldn't canonicalize group_pathkeys and sort_pathkeys
851                  * before running query_planner(), so do it now.
852                  */
853                 group_pathkeys = canonicalize_pathkeys(root, group_pathkeys);
854                 sort_pathkeys = canonicalize_pathkeys(root, sort_pathkeys);
855
856                 /*
857                  * If grouping, estimate the number of groups.  (We can't do this
858                  * until after running query_planner(), either.)  Then decide
859                  * whether we want to use hashed grouping.
860                  */
861                 if (parse->groupClause)
862                 {
863                         List       *groupExprs;
864                         double          cheapest_path_rows;
865
866                         /*
867                          * Beware of the possibility that cheapest_path->parent is NULL.
868                          * This could happen if user does something silly like
869                          *              SELECT 'foo' GROUP BY 1;
870                          */
871                         if (cheapest_path->parent)
872                                 cheapest_path_rows = cheapest_path->parent->rows;
873                         else
874                                 cheapest_path_rows = 1; /* assume non-set result */
875
876                         groupExprs = get_sortgrouplist_exprs(parse->groupClause,
877                                                                                                  parse->targetList);
878                         dNumGroups = estimate_num_groups(root,
879                                                                                          groupExprs,
880                                                                                          cheapest_path_rows);
881                         /* Also want it as a long int --- but 'ware overflow! */
882                         numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
883
884                         use_hashed_grouping =
885                                 choose_hashed_grouping(root, tuple_fraction,
886                                                                            cheapest_path, sorted_path,
887                                                                            sort_pathkeys, group_pathkeys,
888                                                                            dNumGroups, &agg_counts);
889                 }
890
891                 /*
892                  * Select the best path.  If we are doing hashed grouping, we will
893                  * always read all the input tuples, so use the cheapest-total
894                  * path. Otherwise, trust query_planner's decision about which to use.
895                  */
896                 if (use_hashed_grouping || !sorted_path)
897                         best_path = cheapest_path;
898                 else
899                         best_path = sorted_path;
900
901                 /*
902                  * Check to see if it's possible to optimize MIN/MAX aggregates.
903                  * If so, we will forget all the work we did so far to choose a
904                  * "regular" path ... but we had to do it anyway to be able to
905                  * tell which way is cheaper.
906                  */
907                 result_plan = optimize_minmax_aggregates(root,
908                                                                                                  tlist,
909                                                                                                  best_path);
910                 if (result_plan != NULL)
911                 {
912                         /*
913                          * optimize_minmax_aggregates generated the full plan, with
914                          * the right tlist, and it has no sort order.
915                          */
916                         current_pathkeys = NIL;
917                 }
918                 else
919                 {
920                         /*
921                          * Normal case --- create a plan according to query_planner's
922                          * results.
923                          */
924                         result_plan = create_plan(root, best_path);
925                         current_pathkeys = best_path->pathkeys;
926
927                         /*
928                          * create_plan() returns a plan with just a "flat" tlist of
929                          * required Vars.  Usually we need to insert the sub_tlist as the
930                          * tlist of the top plan node.  However, we can skip that if we
931                          * determined that whatever query_planner chose to return will be
932                          * good enough.
933                          */
934                         if (need_tlist_eval)
935                         {
936                                 /*
937                                  * If the top-level plan node is one that cannot do expression
938                                  * evaluation, we must insert a Result node to project the
939                                  * desired tlist.
940                                  */
941                                 if (!is_projection_capable_plan(result_plan))
942                                 {
943                                         result_plan = (Plan *) make_result(sub_tlist, NULL,
944                                                                                                            result_plan);
945                                 }
946                                 else
947                                 {
948                                         /*
949                                          * Otherwise, just replace the subplan's flat tlist with
950                                          * the desired tlist.
951                                          */
952                                         result_plan->targetlist = sub_tlist;
953                                 }
954
955                                 /*
956                                  * Also, account for the cost of evaluation of the sub_tlist.
957                                  *
958                                  * Up to now, we have only been dealing with "flat" tlists,
959                                  * containing just Vars.  So their evaluation cost is zero
960                                  * according to the model used by cost_qual_eval() (or if you
961                                  * prefer, the cost is factored into cpu_tuple_cost).  Thus we
962                                  * can avoid accounting for tlist cost throughout
963                                  * query_planner() and subroutines.  But now we've inserted a
964                                  * tlist that might contain actual operators, sub-selects, etc
965                                  * --- so we'd better account for its cost.
966                                  *
967                                  * Below this point, any tlist eval cost for added-on nodes
968                                  * should be accounted for as we create those nodes.
969                                  * Presently, of the node types we can add on, only Agg and
970                                  * Group project new tlists (the rest just copy their input
971                                  * tuples) --- so make_agg() and make_group() are responsible
972                                  * for computing the added cost.
973                                  */
974                                 cost_qual_eval(&tlist_cost, sub_tlist);
975                                 result_plan->startup_cost += tlist_cost.startup;
976                                 result_plan->total_cost += tlist_cost.startup +
977                                         tlist_cost.per_tuple * result_plan->plan_rows;
978                         }
979                         else
980                         {
981                                 /*
982                                  * Since we're using query_planner's tlist and not the one
983                                  * make_subplanTargetList calculated, we have to refigure any
984                                  * grouping-column indexes make_subplanTargetList computed.
985                                  */
986                                 locate_grouping_columns(root, tlist, result_plan->targetlist,
987                                                                                 groupColIdx);
988                         }
989
990                         /*
991                          * Insert AGG or GROUP node if needed, plus an explicit sort step
992                          * if necessary.
993                          *
994                          * HAVING clause, if any, becomes qual of the Agg or Group node.
995                          */
996                         if (use_hashed_grouping)
997                         {
998                                 /* Hashed aggregate plan --- no sort needed */
999                                 result_plan = (Plan *) make_agg(root,
1000                                                                                                 tlist,
1001                                                                                                 (List *) parse->havingQual,
1002                                                                                                 AGG_HASHED,
1003                                                                                                 numGroupCols,
1004                                                                                                 groupColIdx,
1005                                                                                                 numGroups,
1006                                                                                                 agg_counts.numAggs,
1007                                                                                                 result_plan);
1008                                 /* Hashed aggregation produces randomly-ordered results */
1009                                 current_pathkeys = NIL;
1010                         }
1011                         else if (parse->hasAggs)
1012                         {
1013                                 /* Plain aggregate plan --- sort if needed */
1014                                 AggStrategy aggstrategy;
1015
1016                                 if (parse->groupClause)
1017                                 {
1018                                         if (!pathkeys_contained_in(group_pathkeys,
1019                                                                                            current_pathkeys))
1020                                         {
1021                                                 result_plan = (Plan *)
1022                                                         make_sort_from_groupcols(root,
1023                                                                                                          parse->groupClause,
1024                                                                                                          groupColIdx,
1025                                                                                                          result_plan);
1026                                                 current_pathkeys = group_pathkeys;
1027                                         }
1028                                         aggstrategy = AGG_SORTED;
1029
1030                                         /*
1031                                          * The AGG node will not change the sort ordering of its
1032                                          * groups, so current_pathkeys describes the result too.
1033                                          */
1034                                 }
1035                                 else
1036                                 {
1037                                         aggstrategy = AGG_PLAIN;
1038                                         /* Result will be only one row anyway; no sort order */
1039                                         current_pathkeys = NIL;
1040                                 }
1041
1042                                 result_plan = (Plan *) make_agg(root,
1043                                                                                                 tlist,
1044                                                                                                 (List *) parse->havingQual,
1045                                                                                                 aggstrategy,
1046                                                                                                 numGroupCols,
1047                                                                                                 groupColIdx,
1048                                                                                                 numGroups,
1049                                                                                                 agg_counts.numAggs,
1050                                                                                                 result_plan);
1051                         }
1052                         else if (parse->groupClause)
1053                         {
1054                                 /*
1055                                  * GROUP BY without aggregation, so insert a group node (plus
1056                                  * the appropriate sort node, if necessary).
1057                                  *
1058                                  * Add an explicit sort if we couldn't make the path come
1059                                  * out the way the GROUP node needs it.
1060                                  */
1061                                 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1062                                 {
1063                                         result_plan = (Plan *)
1064                                                 make_sort_from_groupcols(root,
1065                                                                                                  parse->groupClause,
1066                                                                                                  groupColIdx,
1067                                                                                                  result_plan);
1068                                         current_pathkeys = group_pathkeys;
1069                                 }
1070
1071                                 result_plan = (Plan *) make_group(root,
1072                                                                                                   tlist,
1073                                                                                                   (List *) parse->havingQual,
1074                                                                                                   numGroupCols,
1075                                                                                                   groupColIdx,
1076                                                                                                   dNumGroups,
1077                                                                                                   result_plan);
1078                                 /* The Group node won't change sort ordering */
1079                         }
1080                         else if (root->hasHavingQual)
1081                         {
1082                                 /*
1083                                  * No aggregates, and no GROUP BY, but we have a HAVING qual.
1084                                  * This is a degenerate case in which we are supposed to emit
1085                                  * either 0 or 1 row depending on whether HAVING succeeds.
1086                                  * Furthermore, there cannot be any variables in either HAVING
1087                                  * or the targetlist, so we actually do not need the FROM table
1088                                  * at all!  We can just throw away the plan-so-far and generate
1089                                  * a Result node.  This is a sufficiently unusual corner case
1090                                  * that it's not worth contorting the structure of this routine
1091                                  * to avoid having to generate the plan in the first place.
1092                                  */
1093                                 result_plan = (Plan *) make_result(tlist,
1094                                                                                                    parse->havingQual,
1095                                                                                                    NULL);
1096                         }
1097                 }                                               /* end of non-minmax-aggregate case */
1098         }                                                       /* end of if (setOperations) */
1099
1100         /*
1101          * If we were not able to make the plan come out in the right order,
1102          * add an explicit sort step.
1103          */
1104         if (parse->sortClause)
1105         {
1106                 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1107                 {
1108                         result_plan = (Plan *)
1109                                 make_sort_from_sortclauses(root,
1110                                                                                    parse->sortClause,
1111                                                                                    result_plan);
1112                         current_pathkeys = sort_pathkeys;
1113                 }
1114         }
1115
1116         /*
1117          * If there is a DISTINCT clause, add the UNIQUE node.
1118          */
1119         if (parse->distinctClause)
1120         {
1121                 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1122
1123                 /*
1124                  * If there was grouping or aggregation, leave plan_rows as-is
1125                  * (ie, assume the result was already mostly unique).  If not,
1126                  * it's reasonable to assume the UNIQUE filter has effects
1127                  * comparable to GROUP BY.
1128                  */
1129                 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1130                 {
1131                         List       *distinctExprs;
1132
1133                         distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
1134                                                                                                         parse->targetList);
1135                         result_plan->plan_rows = estimate_num_groups(root,
1136                                                                                                                  distinctExprs,
1137                                                                                                  result_plan->plan_rows);
1138                 }
1139         }
1140
1141         /*
1142          * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1143          */
1144         if (parse->limitOffset || parse->limitCount)
1145         {
1146                 result_plan = (Plan *) make_limit(result_plan,
1147                                                                                   parse->limitOffset,
1148                                                                                   parse->limitCount);
1149         }
1150
1151         /*
1152          * Return the actual output ordering in query_pathkeys for possible
1153          * use by an outer query level.
1154          */
1155         root->query_pathkeys = current_pathkeys;
1156
1157         return result_plan;
1158 }
1159
1160 /*
1161  * adjust_tuple_fraction_for_limit - adjust tuple fraction for LIMIT
1162  *
1163  * If the query contains LIMIT, we adjust the caller-supplied tuple_fraction
1164  * accordingly.  This is not overridable by the caller, since it reflects plan
1165  * actions that grouping_planner() will certainly take, not assumptions about
1166  * context.
1167  */
1168 static double
1169 adjust_tuple_fraction_for_limit(PlannerInfo *root, double tuple_fraction)
1170 {
1171         Query      *parse = root->parse;
1172         double          limit_fraction = 0.0;
1173
1174         /* Should not be called unless LIMIT */
1175         Assert(parse->limitCount != NULL);
1176
1177         /*
1178          * A LIMIT clause limits the absolute number of tuples returned. However,
1179          * if it's not a constant LIMIT then we have to punt; for lack of a better
1180          * idea, assume 10% of the plan's result is wanted.
1181          */
1182         if (IsA(parse->limitCount, Const))
1183         {
1184                 Const      *limitc = (Const *) parse->limitCount;
1185                 int32           count = DatumGetInt32(limitc->constvalue);
1186
1187                 /*
1188                  * A NULL-constant LIMIT represents "LIMIT ALL", which we treat the
1189                  * same as no limit (ie, expect to retrieve all the tuples).
1190                  */
1191                 if (!limitc->constisnull && count > 0)
1192                 {
1193                         limit_fraction = (double) count;
1194                         /* We must also consider the OFFSET, if present */
1195                         if (parse->limitOffset != NULL)
1196                         {
1197                                 if (IsA(parse->limitOffset, Const))
1198                                 {
1199                                         int32           offset;
1200
1201                                         limitc = (Const *) parse->limitOffset;
1202                                         offset = DatumGetInt32(limitc->constvalue);
1203                                         if (!limitc->constisnull && offset > 0)
1204                                                 limit_fraction += (double) offset;
1205                                 }
1206                                 else
1207                                 {
1208                                         /* OFFSET is an expression ... punt ... */
1209                                         limit_fraction = 0.10;
1210                                 }
1211                         }
1212                 }
1213         }
1214         else
1215         {
1216                 /* LIMIT is an expression ... punt ... */
1217                 limit_fraction = 0.10;
1218         }
1219
1220         if (limit_fraction > 0.0)
1221         {
1222                 /*
1223                  * If we have absolute limits from both caller and LIMIT, use the
1224                  * smaller value; if one is fractional and the other absolute,
1225                  * treat the fraction as a fraction of the absolute value;
1226                  * else we can multiply the two fractions together.
1227                  */
1228                 if (tuple_fraction >= 1.0)
1229                 {
1230                         if (limit_fraction >= 1.0)
1231                         {
1232                                 /* both absolute */
1233                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
1234                         }
1235                         else
1236                         {
1237                                 /* caller absolute, limit fractional */
1238                                 tuple_fraction *= limit_fraction;
1239                                 if (tuple_fraction < 1.0)
1240                                         tuple_fraction = 1.0;
1241                         }
1242                 }
1243                 else if (tuple_fraction > 0.0)
1244                 {
1245                         if (limit_fraction >= 1.0)
1246                         {
1247                                 /* caller fractional, limit absolute */
1248                                 tuple_fraction *= limit_fraction;
1249                                 if (tuple_fraction < 1.0)
1250                                         tuple_fraction = 1.0;
1251                         }
1252                         else
1253                         {
1254                                 /* both fractional */
1255                                 tuple_fraction *= limit_fraction;
1256                         }
1257                 }
1258                 else
1259                 {
1260                         /* no info from caller, just use limit */
1261                         tuple_fraction = limit_fraction;
1262                 }
1263         }
1264
1265         return tuple_fraction;
1266 }
1267
1268 /*
1269  * choose_hashed_grouping - should we use hashed grouping?
1270  */
1271 static bool
1272 choose_hashed_grouping(PlannerInfo *root, double tuple_fraction,
1273                                            Path *cheapest_path, Path *sorted_path,
1274                                            List *sort_pathkeys, List *group_pathkeys,
1275                                            double dNumGroups, AggClauseCounts *agg_counts)
1276 {
1277         int                     numGroupCols = list_length(root->parse->groupClause);
1278         double          cheapest_path_rows;
1279         int                     cheapest_path_width;
1280         Size            hashentrysize;
1281         List       *current_pathkeys;
1282         Path            hashed_p;
1283         Path            sorted_p;
1284
1285         /*
1286          * Check can't-do-it conditions, including whether the grouping operators
1287          * are hashjoinable.
1288          *
1289          * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1290          * (Doing so would imply storing *all* the input values in the hash table,
1291          * which seems like a certain loser.)
1292          */
1293         if (!enable_hashagg)
1294                 return false;
1295         if (agg_counts->numDistinctAggs != 0)
1296                 return false;
1297         if (!hash_safe_grouping(root))
1298                 return false;
1299
1300         /*
1301          * Don't do it if it doesn't look like the hashtable will fit into
1302          * work_mem.
1303          *
1304          * Beware here of the possibility that cheapest_path->parent is NULL.
1305          * This could happen if user does something silly like
1306          *              SELECT 'foo' GROUP BY 1;
1307          */
1308         if (cheapest_path->parent)
1309         {
1310                 cheapest_path_rows = cheapest_path->parent->rows;
1311                 cheapest_path_width = cheapest_path->parent->width;
1312         }
1313         else
1314         {
1315                 cheapest_path_rows = 1;                         /* assume non-set result */
1316                 cheapest_path_width = 100;                      /* arbitrary */
1317         }
1318
1319         /* Estimate per-hash-entry space at tuple width... */
1320         hashentrysize = cheapest_path_width;
1321         /* plus space for pass-by-ref transition values... */
1322         hashentrysize += agg_counts->transitionSpace;
1323         /* plus the per-hash-entry overhead */
1324         hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1325
1326         if (hashentrysize * dNumGroups > work_mem * 1024L)
1327                 return false;
1328
1329         /*
1330          * See if the estimated cost is no more than doing it the other way.
1331          * While avoiding the need for sorted input is usually a win, the fact
1332          * that the output won't be sorted may be a loss; so we need to do an
1333          * actual cost comparison.
1334          *
1335          * We need to consider
1336          *              cheapest_path + hashagg [+ final sort]
1337          * versus either
1338          *              cheapest_path [+ sort] + group or agg [+ final sort]
1339          * or
1340          *              presorted_path + group or agg [+ final sort]
1341          * where brackets indicate a step that may not be needed. We assume
1342          * query_planner() will have returned a presorted path only if it's a
1343          * winner compared to cheapest_path for this purpose.
1344          *
1345          * These path variables are dummies that just hold cost fields; we don't
1346          * make actual Paths for these steps.
1347          */
1348         cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1349                          numGroupCols, dNumGroups,
1350                          cheapest_path->startup_cost, cheapest_path->total_cost,
1351                          cheapest_path_rows);
1352         /* Result of hashed agg is always unsorted */
1353         if (sort_pathkeys)
1354                 cost_sort(&hashed_p, root, sort_pathkeys, hashed_p.total_cost,
1355                                   dNumGroups, cheapest_path_width);
1356
1357         if (sorted_path)
1358         {
1359                 sorted_p.startup_cost = sorted_path->startup_cost;
1360                 sorted_p.total_cost = sorted_path->total_cost;
1361                 current_pathkeys = sorted_path->pathkeys;
1362         }
1363         else
1364         {
1365                 sorted_p.startup_cost = cheapest_path->startup_cost;
1366                 sorted_p.total_cost = cheapest_path->total_cost;
1367                 current_pathkeys = cheapest_path->pathkeys;
1368         }
1369         if (!pathkeys_contained_in(group_pathkeys,
1370                                                            current_pathkeys))
1371         {
1372                 cost_sort(&sorted_p, root, group_pathkeys, sorted_p.total_cost,
1373                                   cheapest_path_rows, cheapest_path_width);
1374                 current_pathkeys = group_pathkeys;
1375         }
1376
1377         if (root->parse->hasAggs)
1378                 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1379                                  numGroupCols, dNumGroups,
1380                                  sorted_p.startup_cost, sorted_p.total_cost,
1381                                  cheapest_path_rows);
1382         else
1383                 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1384                                    sorted_p.startup_cost, sorted_p.total_cost,
1385                                    cheapest_path_rows);
1386         /* The Agg or Group node will preserve ordering */
1387         if (sort_pathkeys &&
1388                 !pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1389                 cost_sort(&sorted_p, root, sort_pathkeys, sorted_p.total_cost,
1390                                   dNumGroups, cheapest_path_width);
1391
1392         /*
1393          * Now make the decision using the top-level tuple fraction.  First we
1394          * have to convert an absolute count (LIMIT) into fractional form.
1395          */
1396         if (tuple_fraction >= 1.0)
1397                 tuple_fraction /= dNumGroups;
1398
1399         if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1400                                                                           tuple_fraction) < 0)
1401         {
1402                 /* Hashed is cheaper, so use it */
1403                 return true;
1404         }
1405         return false;
1406 }
1407
1408 /*
1409  * hash_safe_grouping - are grouping operators hashable?
1410  *
1411  * We assume hashed aggregation will work if the datatype's equality operator
1412  * is marked hashjoinable.
1413  */
1414 static bool
1415 hash_safe_grouping(PlannerInfo *root)
1416 {
1417         ListCell   *gl;
1418
1419         foreach(gl, root->parse->groupClause)
1420         {
1421                 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1422                 TargetEntry *tle = get_sortgroupclause_tle(grpcl,
1423                                                                                                    root->parse->targetList);
1424                 Operator        optup;
1425                 bool            oprcanhash;
1426
1427                 optup = equality_oper(exprType((Node *) tle->expr), true);
1428                 if (!optup)
1429                         return false;
1430                 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1431                 ReleaseSysCache(optup);
1432                 if (!oprcanhash)
1433                         return false;
1434         }
1435         return true;
1436 }
1437
1438 /*---------------
1439  * make_subplanTargetList
1440  *        Generate appropriate target list when grouping is required.
1441  *
1442  * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1443  * above the result of query_planner, we typically want to pass a different
1444  * target list to query_planner than the outer plan nodes should have.
1445  * This routine generates the correct target list for the subplan.
1446  *
1447  * The initial target list passed from the parser already contains entries
1448  * for all ORDER BY and GROUP BY expressions, but it will not have entries
1449  * for variables used only in HAVING clauses; so we need to add those
1450  * variables to the subplan target list.  Also, we flatten all expressions
1451  * except GROUP BY items into their component variables; the other expressions
1452  * will be computed by the inserted nodes rather than by the subplan.
1453  * For example, given a query like
1454  *              SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1455  * we want to pass this targetlist to the subplan:
1456  *              a,b,c,d,a+b
1457  * where the a+b target will be used by the Sort/Group steps, and the
1458  * other targets will be used for computing the final results.  (In the
1459  * above example we could theoretically suppress the a and b targets and
1460  * pass down only c,d,a+b, but it's not really worth the trouble to
1461  * eliminate simple var references from the subplan.  We will avoid doing
1462  * the extra computation to recompute a+b at the outer level; see
1463  * replace_vars_with_subplan_refs() in setrefs.c.)
1464  *
1465  * If we are grouping or aggregating, *and* there are no non-Var grouping
1466  * expressions, then the returned tlist is effectively dummy; we do not
1467  * need to force it to be evaluated, because all the Vars it contains
1468  * should be present in the output of query_planner anyway.
1469  *
1470  * 'tlist' is the query's target list.
1471  * 'groupColIdx' receives an array of column numbers for the GROUP BY
1472  *                      expressions (if there are any) in the subplan's target list.
1473  * 'need_tlist_eval' is set true if we really need to evaluate the
1474  *                      result tlist.
1475  *
1476  * The result is the targetlist to be passed to the subplan.
1477  *---------------
1478  */
1479 static List *
1480 make_subplanTargetList(PlannerInfo *root,
1481                                            List *tlist,
1482                                            AttrNumber **groupColIdx,
1483                                            bool *need_tlist_eval)
1484 {
1485         Query      *parse = root->parse;
1486         List       *sub_tlist;
1487         List       *extravars;
1488         int                     numCols;
1489
1490         *groupColIdx = NULL;
1491
1492         /*
1493          * If we're not grouping or aggregating, there's nothing to do here;
1494          * query_planner should receive the unmodified target list.
1495          */
1496         if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1497         {
1498                 *need_tlist_eval = true;
1499                 return tlist;
1500         }
1501
1502         /*
1503          * Otherwise, start with a "flattened" tlist (having just the vars
1504          * mentioned in the targetlist and HAVING qual --- but not upper-
1505          * level Vars; they will be replaced by Params later on).
1506          */
1507         sub_tlist = flatten_tlist(tlist);
1508         extravars = pull_var_clause(parse->havingQual, false);
1509         sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1510         list_free(extravars);
1511         *need_tlist_eval = false;       /* only eval if not flat tlist */
1512
1513         /*
1514          * If grouping, create sub_tlist entries for all GROUP BY expressions
1515          * (GROUP BY items that are simple Vars should be in the list
1516          * already), and make an array showing where the group columns are in
1517          * the sub_tlist.
1518          */
1519         numCols = list_length(parse->groupClause);
1520         if (numCols > 0)
1521         {
1522                 int                     keyno = 0;
1523                 AttrNumber *grpColIdx;
1524                 ListCell   *gl;
1525
1526                 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1527                 *groupColIdx = grpColIdx;
1528
1529                 foreach(gl, parse->groupClause)
1530                 {
1531                         GroupClause *grpcl = (GroupClause *) lfirst(gl);
1532                         Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1533                         TargetEntry *te = NULL;
1534                         ListCell   *sl;
1535
1536                         /* Find or make a matching sub_tlist entry */
1537                         foreach(sl, sub_tlist)
1538                         {
1539                                 te = (TargetEntry *) lfirst(sl);
1540                                 if (equal(groupexpr, te->expr))
1541                                         break;
1542                         }
1543                         if (!sl)
1544                         {
1545                                 te = makeTargetEntry((Expr *) groupexpr,
1546                                                                          list_length(sub_tlist) + 1,
1547                                                                          NULL,
1548                                                                          false);
1549                                 sub_tlist = lappend(sub_tlist, te);
1550                                 *need_tlist_eval = true;                /* it's not flat anymore */
1551                         }
1552
1553                         /* and save its resno */
1554                         grpColIdx[keyno++] = te->resno;
1555                 }
1556         }
1557
1558         return sub_tlist;
1559 }
1560
1561 /*
1562  * locate_grouping_columns
1563  *              Locate grouping columns in the tlist chosen by query_planner.
1564  *
1565  * This is only needed if we don't use the sub_tlist chosen by
1566  * make_subplanTargetList.      We have to forget the column indexes found
1567  * by that routine and re-locate the grouping vars in the real sub_tlist.
1568  */
1569 static void
1570 locate_grouping_columns(PlannerInfo *root,
1571                                                 List *tlist,
1572                                                 List *sub_tlist,
1573                                                 AttrNumber *groupColIdx)
1574 {
1575         int                     keyno = 0;
1576         ListCell   *gl;
1577
1578         /*
1579          * No work unless grouping.
1580          */
1581         if (!root->parse->groupClause)
1582         {
1583                 Assert(groupColIdx == NULL);
1584                 return;
1585         }
1586         Assert(groupColIdx != NULL);
1587
1588         foreach(gl, root->parse->groupClause)
1589         {
1590                 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1591                 Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1592                 TargetEntry *te = NULL;
1593                 ListCell   *sl;
1594
1595                 foreach(sl, sub_tlist)
1596                 {
1597                         te = (TargetEntry *) lfirst(sl);
1598                         if (equal(groupexpr, te->expr))
1599                                 break;
1600                 }
1601                 if (!sl)
1602                         elog(ERROR, "failed to locate grouping columns");
1603
1604                 groupColIdx[keyno++] = te->resno;
1605         }
1606 }
1607
1608 /*
1609  * postprocess_setop_tlist
1610  *        Fix up targetlist returned by plan_set_operations().
1611  *
1612  * We need to transpose sort key info from the orig_tlist into new_tlist.
1613  * NOTE: this would not be good enough if we supported resjunk sort keys
1614  * for results of set operations --- then, we'd need to project a whole
1615  * new tlist to evaluate the resjunk columns.  For now, just ereport if we
1616  * find any resjunk columns in orig_tlist.
1617  */
1618 static List *
1619 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1620 {
1621         ListCell   *l;
1622         ListCell   *orig_tlist_item = list_head(orig_tlist);
1623
1624         foreach(l, new_tlist)
1625         {
1626                 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1627                 TargetEntry *orig_tle;
1628
1629                 /* ignore resjunk columns in setop result */
1630                 if (new_tle->resjunk)
1631                         continue;
1632
1633                 Assert(orig_tlist_item != NULL);
1634                 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1635                 orig_tlist_item = lnext(orig_tlist_item);
1636                 if (orig_tle->resjunk)                  /* should not happen */
1637                         elog(ERROR, "resjunk output columns are not implemented");
1638                 Assert(new_tle->resno == orig_tle->resno);
1639                 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1640         }
1641         if (orig_tlist_item != NULL)
1642                 elog(ERROR, "resjunk output columns are not implemented");
1643         return new_tlist;
1644 }