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