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