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