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