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