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