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