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