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