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