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