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