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