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