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