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