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