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