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