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