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