]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/planner.c
Split out into a separate function the code in grouping_planner() that
[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.183 2005/04/10 19:50:08 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         /* executor wants to know total number of Params used overall */
148         result_plan->nParamExec = list_length(PlannerParamList);
149
150         /* final cleanup of the plan */
151         set_plan_references(result_plan, parse->rtable);
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.
366          */
367         if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
368         {
369                 Cost            initplan_cost = 0;
370
371                 /* Prepare extParam/allParam sets for all nodes in tree */
372                 SS_finalize_plan(plan, parse->rtable);
373
374                 /*
375                  * SS_finalize_plan doesn't handle initPlans, so we have to
376                  * manually attach them to the topmost plan node, and add their
377                  * extParams to the topmost node's, too.
378                  *
379                  * We also add the total_cost of each initPlan to the startup cost of
380                  * the top node.  This is a conservative overestimate, since in
381                  * fact each initPlan might be executed later than plan startup,
382                  * or even not at all.
383                  */
384                 plan->initPlan = PlannerInitPlan;
385
386                 foreach(l, plan->initPlan)
387                 {
388                         SubPlan    *initplan = (SubPlan *) lfirst(l);
389
390                         plan->extParam = bms_add_members(plan->extParam,
391                                                                                          initplan->plan->extParam);
392                         /* allParam must include all members of extParam */
393                         plan->allParam = bms_add_members(plan->allParam,
394                                                                                          plan->extParam);
395                         initplan_cost += initplan->plan->total_cost;
396                 }
397
398                 plan->startup_cost += initplan_cost;
399                 plan->total_cost += initplan_cost;
400         }
401
402         /* Return to outer subquery context */
403         PlannerQueryLevel--;
404         PlannerInitPlan = saved_initplan;
405         /* we do NOT restore PlannerPlanId; that's not an oversight! */
406
407         return plan;
408 }
409
410 /*
411  * preprocess_expression
412  *              Do subquery_planner's preprocessing work for an expression,
413  *              which can be a targetlist, a WHERE clause (including JOIN/ON
414  *              conditions), or a HAVING clause.
415  */
416 static Node *
417 preprocess_expression(Query *parse, Node *expr, int kind)
418 {
419         /*
420          * If the query has any join RTEs, replace join alias variables with
421          * base-relation variables. We must do this before sublink processing,
422          * else sublinks expanded out from join aliases wouldn't get
423          * processed.
424          */
425         if (parse->hasJoinRTEs)
426                 expr = flatten_join_alias_vars(parse, expr);
427
428         /*
429          * Simplify constant expressions.
430          *
431          * Note: this also flattens nested AND and OR expressions into N-argument
432          * form.  All processing of a qual expression after this point must be
433          * careful to maintain AND/OR flatness --- that is, do not generate a tree
434          * with AND directly under AND, nor OR directly under OR.
435          */
436         expr = eval_const_expressions(expr);
437
438         /*
439          * If it's a qual or havingQual, canonicalize it.
440          */
441         if (kind == EXPRKIND_QUAL)
442         {
443                 expr = (Node *) canonicalize_qual((Expr *) expr);
444
445 #ifdef OPTIMIZER_DEBUG
446                 printf("After canonicalize_qual()\n");
447                 pprint(expr);
448 #endif
449         }
450
451         /* Expand SubLinks to SubPlans */
452         if (parse->hasSubLinks)
453                 expr = SS_process_sublinks(expr, (kind == EXPRKIND_QUAL));
454
455         /*
456          * XXX do not insert anything here unless you have grokked the
457          * comments in SS_replace_correlation_vars ...
458          */
459
460         /* Replace uplevel vars with Param nodes */
461         if (PlannerQueryLevel > 1)
462                 expr = SS_replace_correlation_vars(expr);
463
464         /*
465          * If it's a qual or havingQual, convert it to implicit-AND format.
466          * (We don't want to do this before eval_const_expressions, since the
467          * latter would be unable to simplify a top-level AND correctly. Also,
468          * SS_process_sublinks expects explicit-AND format.)
469          */
470         if (kind == EXPRKIND_QUAL)
471                 expr = (Node *) make_ands_implicit((Expr *) expr);
472
473         return expr;
474 }
475
476 /*
477  * preprocess_qual_conditions
478  *              Recursively scan the query's jointree and do subquery_planner's
479  *              preprocessing work on each qual condition found therein.
480  */
481 static void
482 preprocess_qual_conditions(Query *parse, Node *jtnode)
483 {
484         if (jtnode == NULL)
485                 return;
486         if (IsA(jtnode, RangeTblRef))
487         {
488                 /* nothing to do here */
489         }
490         else if (IsA(jtnode, FromExpr))
491         {
492                 FromExpr   *f = (FromExpr *) jtnode;
493                 ListCell   *l;
494
495                 foreach(l, f->fromlist)
496                         preprocess_qual_conditions(parse, lfirst(l));
497
498                 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_QUAL);
499         }
500         else if (IsA(jtnode, JoinExpr))
501         {
502                 JoinExpr   *j = (JoinExpr *) jtnode;
503
504                 preprocess_qual_conditions(parse, j->larg);
505                 preprocess_qual_conditions(parse, j->rarg);
506
507                 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_QUAL);
508         }
509         else
510                 elog(ERROR, "unrecognized node type: %d",
511                          (int) nodeTag(jtnode));
512 }
513
514 /*--------------------
515  * inheritance_planner
516  *        Generate a plan in the case where the result relation is an
517  *        inheritance set.
518  *
519  * We have to handle this case differently from cases where a source
520  * relation is an inheritance set.      Source inheritance is expanded at
521  * the bottom of the plan tree (see allpaths.c), but target inheritance
522  * has to be expanded at the top.  The reason is that for UPDATE, each
523  * target relation needs a different targetlist matching its own column
524  * set.  (This is not so critical for DELETE, but for simplicity we treat
525  * inherited DELETE the same way.)      Fortunately, the UPDATE/DELETE target
526  * can never be the nullable side of an outer join, so it's OK to generate
527  * the plan this way.
528  *
529  * parse is the querytree produced by the parser & rewriter.
530  * inheritlist is an integer list of RT indexes for the result relation set.
531  *
532  * Returns a query plan.
533  *--------------------
534  */
535 static Plan *
536 inheritance_planner(Query *parse, List *inheritlist)
537 {
538         int                     parentRTindex = parse->resultRelation;
539         Oid                     parentOID = getrelid(parentRTindex, parse->rtable);
540         int                     mainrtlength = list_length(parse->rtable);
541         List       *subplans = NIL;
542         List       *tlist = NIL;
543         ListCell   *l;
544
545         foreach(l, inheritlist)
546         {
547                 int                     childRTindex = lfirst_int(l);
548                 Oid                     childOID = getrelid(childRTindex, parse->rtable);
549                 Query      *subquery;
550                 Plan       *subplan;
551
552                 /* Generate modified query with this rel as target */
553                 subquery = (Query *) adjust_inherited_attrs((Node *) parse,
554                                                                                                 parentRTindex, parentOID,
555                                                                                                  childRTindex, childOID);
556                 /* Generate plan */
557                 subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */ );
558                 subplans = lappend(subplans, subplan);
559
560                 /*
561                  * XXX my goodness this next bit is ugly.  Really need to think about
562                  * ways to rein in planner's habit of scribbling on its input.
563                  *
564                  * Planning of the subquery might have modified the rangetable,
565                  * either by addition of RTEs due to expansion of inherited source
566                  * tables, or by changes of the Query structures inside subquery
567                  * RTEs.  We have to ensure that this gets propagated back to the
568                  * master copy.  However, if we aren't done planning yet, we also
569                  * need to ensure that subsequent calls to grouping_planner have
570                  * virgin sub-Queries to work from.  So, if we are at the last
571                  * list entry, just copy the subquery rangetable back to the master
572                  * copy; if we are not, then extend the master copy by adding
573                  * whatever the subquery added.  (We assume these added entries
574                  * will go untouched by the future grouping_planner calls.  We are
575                  * also effectively assuming that sub-Queries will get planned
576                  * identically each time, or at least that the impacts on their
577                  * rangetables will be the same each time.  Did I say this is ugly?)
578                  */
579                 if (lnext(l) == NULL)
580                         parse->rtable = subquery->rtable;
581                 else
582                 {
583                         int             subrtlength = list_length(subquery->rtable);
584
585                         if (subrtlength > mainrtlength)
586                         {
587                                 List       *subrt;
588
589                                 subrt = list_copy_tail(subquery->rtable, mainrtlength);
590                                 parse->rtable = list_concat(parse->rtable, subrt);
591                                 mainrtlength = subrtlength;
592                         }
593                 }
594
595                 /* Save preprocessed tlist from first rel for use in Append */
596                 if (tlist == NIL)
597                         tlist = subplan->targetlist;
598         }
599
600         /* Save the target-relations list for the executor, too */
601         parse->resultRelations = inheritlist;
602
603         /* Mark result as unordered (probably unnecessary) */
604         parse->query_pathkeys = NIL;
605
606         return (Plan *) make_append(subplans, true, tlist);
607 }
608
609 /*--------------------
610  * grouping_planner
611  *        Perform planning steps related to grouping, aggregation, etc.
612  *        This primarily means adding top-level processing to the basic
613  *        query plan produced by query_planner.
614  *
615  * parse is the querytree produced by the parser & rewriter.
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, parse->query_pathkeys is returned as the
626  * actual output ordering of the plan (in pathkey format).
627  *--------------------
628  */
629 static Plan *
630 grouping_planner(Query *parse, double tuple_fraction)
631 {
632         List       *tlist = parse->targetList;
633         Plan       *result_plan;
634         List       *current_pathkeys;
635         List       *sort_pathkeys;
636
637         if (parse->setOperations)
638         {
639                 List       *set_sortclauses;
640
641                 /*
642                  * Construct the plan for set operations.  The result will not
643                  * need any work except perhaps a top-level sort and/or LIMIT.
644                  */
645                 result_plan = plan_set_operations(parse,
646                                                                                   &set_sortclauses);
647
648                 /*
649                  * Calculate pathkeys representing the sort order (if any) of the
650                  * set operation's result.  We have to do this before overwriting
651                  * the sort key information...
652                  */
653                 current_pathkeys = make_pathkeys_for_sortclauses(set_sortclauses,
654                                                                                                 result_plan->targetlist);
655                 current_pathkeys = canonicalize_pathkeys(parse, current_pathkeys);
656
657                 /*
658                  * We should not need to call preprocess_targetlist, since we must
659                  * be in a SELECT query node.  Instead, use the targetlist
660                  * returned by plan_set_operations (since this tells whether it
661                  * returned any resjunk columns!), and transfer any sort key
662                  * information from the original tlist.
663                  */
664                 Assert(parse->commandType == CMD_SELECT);
665
666                 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
667
668                 /*
669                  * Can't handle FOR UPDATE here (parser should have checked
670                  * already, but let's make sure).
671                  */
672                 if (parse->rowMarks)
673                         ereport(ERROR,
674                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
675                                          errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
676
677                 /*
678                  * Calculate pathkeys that represent result ordering requirements
679                  */
680                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
681                                                                                                           tlist);
682                 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
683         }
684         else
685         {
686                 /* No set operations, do regular planning */
687                 List       *sub_tlist;
688                 List       *group_pathkeys;
689                 AttrNumber *groupColIdx = NULL;
690                 bool            need_tlist_eval = true;
691                 QualCost        tlist_cost;
692                 double          sub_tuple_fraction;
693                 Path       *cheapest_path;
694                 Path       *sorted_path;
695                 double          dNumGroups = 0;
696                 long            numGroups = 0;
697                 AggClauseCounts agg_counts;
698                 int                     numGroupCols = list_length(parse->groupClause);
699                 bool            use_hashed_grouping = false;
700
701                 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
702
703                 /* Preprocess targetlist */
704                 tlist = preprocess_targetlist(parse, tlist);
705
706                 /*
707                  * Generate appropriate target list for subplan; may be different
708                  * from tlist if grouping or aggregation is needed.
709                  */
710                 sub_tlist = make_subplanTargetList(parse, tlist,
711                                                                                  &groupColIdx, &need_tlist_eval);
712
713                 /*
714                  * Calculate pathkeys that represent grouping/ordering
715                  * requirements
716                  */
717                 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
718                                                                                                            tlist);
719                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
720                                                                                                           tlist);
721
722                 /*
723                  * Will need actual number of aggregates for estimating costs.
724                  *
725                  * Note: we do not attempt to detect duplicate aggregates here; a
726                  * somewhat-overestimated count is okay for our present purposes.
727                  *
728                  * Note: think not that we can turn off hasAggs if we find no aggs.
729                  * It is possible for constant-expression simplification to remove
730                  * all explicit references to aggs, but we still have to follow
731                  * the aggregate semantics (eg, producing only one output row).
732                  */
733                 if (parse->hasAggs)
734                 {
735                         count_agg_clauses((Node *) tlist, &agg_counts);
736                         count_agg_clauses(parse->havingQual, &agg_counts);
737                 }
738
739                 /*
740                  * Figure out whether we need a sorted result from query_planner.
741                  *
742                  * If we have a GROUP BY clause, then we want a result sorted
743                  * properly for grouping.  Otherwise, if there is an ORDER BY
744                  * clause, we want to sort by the ORDER BY clause.      (Note: if we
745                  * have both, and ORDER BY is a superset of GROUP BY, it would be
746                  * tempting to request sort by ORDER BY --- but that might just
747                  * leave us failing to exploit an available sort order at all.
748                  * Needs more thought...)
749                  */
750                 if (parse->groupClause)
751                         parse->query_pathkeys = group_pathkeys;
752                 else if (parse->sortClause)
753                         parse->query_pathkeys = sort_pathkeys;
754                 else
755                         parse->query_pathkeys = NIL;
756
757                 /*
758                  * Adjust tuple_fraction if we see that we are going to apply
759                  * limiting/grouping/aggregation/etc.  This is not overridable by
760                  * the caller, since it reflects plan actions that this routine
761                  * will certainly take, not assumptions about context.
762                  */
763                 if (parse->limitCount != NULL)
764                 {
765                         /*
766                          * A LIMIT clause limits the absolute number of tuples
767                          * returned. However, if it's not a constant LIMIT then we
768                          * have to punt; for lack of a better idea, assume 10% of the
769                          * plan's result is wanted.
770                          */
771                         double          limit_fraction = 0.0;
772
773                         if (IsA(parse->limitCount, Const))
774                         {
775                                 Const      *limitc = (Const *) parse->limitCount;
776                                 int32           count = DatumGetInt32(limitc->constvalue);
777
778                                 /*
779                                  * A NULL-constant LIMIT represents "LIMIT ALL", which we
780                                  * treat the same as no limit (ie, expect to retrieve all
781                                  * the tuples).
782                                  */
783                                 if (!limitc->constisnull && count > 0)
784                                 {
785                                         limit_fraction = (double) count;
786                                         /* We must also consider the OFFSET, if present */
787                                         if (parse->limitOffset != NULL)
788                                         {
789                                                 if (IsA(parse->limitOffset, Const))
790                                                 {
791                                                         int32           offset;
792
793                                                         limitc = (Const *) parse->limitOffset;
794                                                         offset = DatumGetInt32(limitc->constvalue);
795                                                         if (!limitc->constisnull && offset > 0)
796                                                                 limit_fraction += (double) offset;
797                                                 }
798                                                 else
799                                                 {
800                                                         /* OFFSET is an expression ... punt ... */
801                                                         limit_fraction = 0.10;
802                                                 }
803                                         }
804                                 }
805                         }
806                         else
807                         {
808                                 /* LIMIT is an expression ... punt ... */
809                                 limit_fraction = 0.10;
810                         }
811
812                         if (limit_fraction > 0.0)
813                         {
814                                 /*
815                                  * If we have absolute limits from both caller and LIMIT,
816                                  * use the smaller value; if one is fractional and the
817                                  * other absolute, treat the fraction as a fraction of the
818                                  * absolute value; else we can multiply the two fractions
819                                  * together.
820                                  */
821                                 if (tuple_fraction >= 1.0)
822                                 {
823                                         if (limit_fraction >= 1.0)
824                                         {
825                                                 /* both absolute */
826                                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
827                                         }
828                                         else
829                                         {
830                                                 /* caller absolute, limit fractional */
831                                                 tuple_fraction *= limit_fraction;
832                                                 if (tuple_fraction < 1.0)
833                                                         tuple_fraction = 1.0;
834                                         }
835                                 }
836                                 else if (tuple_fraction > 0.0)
837                                 {
838                                         if (limit_fraction >= 1.0)
839                                         {
840                                                 /* caller fractional, limit absolute */
841                                                 tuple_fraction *= limit_fraction;
842                                                 if (tuple_fraction < 1.0)
843                                                         tuple_fraction = 1.0;
844                                         }
845                                         else
846                                         {
847                                                 /* both fractional */
848                                                 tuple_fraction *= limit_fraction;
849                                         }
850                                 }
851                                 else
852                                 {
853                                         /* no info from caller, just use limit */
854                                         tuple_fraction = limit_fraction;
855                                 }
856                         }
857                 }
858
859                 /*
860                  * With grouping or aggregation, the tuple fraction to pass to
861                  * query_planner() may be different from what it is at top level.
862                  */
863                 sub_tuple_fraction = tuple_fraction;
864
865                 if (parse->groupClause)
866                 {
867                         /*
868                          * In GROUP BY mode, we have the little problem that we don't
869                          * really know how many input tuples will be needed to make a
870                          * group, so we can't translate an output LIMIT count into an
871                          * input count.  For lack of a better idea, assume 25% of the
872                          * input data will be processed if there is any output limit.
873                          * However, if the caller gave us a fraction rather than an
874                          * absolute count, we can keep using that fraction (which
875                          * amounts to assuming that all the groups are about the same
876                          * size).
877                          */
878                         if (sub_tuple_fraction >= 1.0)
879                                 sub_tuple_fraction = 0.25;
880
881                         /*
882                          * If both GROUP BY and ORDER BY are specified, we will need
883                          * two levels of sort --- and, therefore, certainly need to
884                          * read all the input tuples --- unless ORDER BY is a subset
885                          * of GROUP BY.  (We have not yet canonicalized the pathkeys,
886                          * so must use the slower noncanonical comparison method.)
887                          */
888                         if (parse->groupClause && parse->sortClause &&
889                                 !noncanonical_pathkeys_contained_in(sort_pathkeys,
890                                                                                                         group_pathkeys))
891                                 sub_tuple_fraction = 0.0;
892                 }
893                 else if (parse->hasAggs)
894                 {
895                         /*
896                          * Ungrouped aggregate will certainly want all the input
897                          * tuples.
898                          */
899                         sub_tuple_fraction = 0.0;
900                 }
901                 else if (parse->distinctClause)
902                 {
903                         /*
904                          * SELECT DISTINCT, like GROUP, will absorb an unpredictable
905                          * number of input tuples per output tuple.  Handle the same
906                          * way.
907                          */
908                         if (sub_tuple_fraction >= 1.0)
909                                 sub_tuple_fraction = 0.25;
910                 }
911
912                 /*
913                  * Generate the best unsorted and presorted paths for this Query
914                  * (but note there may not be any presorted path).
915                  */
916                 query_planner(parse, sub_tlist, sub_tuple_fraction,
917                                           &cheapest_path, &sorted_path);
918
919                 /*
920                  * We couldn't canonicalize group_pathkeys and sort_pathkeys
921                  * before running query_planner(), so do it now.
922                  */
923                 group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
924                 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
925
926                 /*
927                  * If grouping, estimate the number of groups.  (We can't do this
928                  * until after running query_planner(), either.)  Then decide
929                  * whether we want to use hashed grouping.
930                  */
931                 if (parse->groupClause)
932                 {
933                         List       *groupExprs;
934                         double          cheapest_path_rows;
935
936                         /*
937                          * Beware of the possibility that cheapest_path->parent is NULL.
938                          * This could happen if user does something silly like
939                          *              SELECT 'foo' GROUP BY 1;
940                          */
941                         if (cheapest_path->parent)
942                                 cheapest_path_rows = cheapest_path->parent->rows;
943                         else
944                                 cheapest_path_rows = 1; /* assume non-set result */
945
946                         groupExprs = get_sortgrouplist_exprs(parse->groupClause,
947                                                                                                  parse->targetList);
948                         dNumGroups = estimate_num_groups(parse,
949                                                                                          groupExprs,
950                                                                                          cheapest_path_rows);
951                         /* Also want it as a long int --- but 'ware overflow! */
952                         numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
953
954                         use_hashed_grouping =
955                                 choose_hashed_grouping(parse, tuple_fraction,
956                                                                            cheapest_path, sorted_path,
957                                                                            sort_pathkeys, group_pathkeys,
958                                                                            dNumGroups, &agg_counts);
959                 }
960
961                 /*
962                  * Select the best path and create a plan to execute it.
963                  *
964                  * If we are doing hashed grouping, we will always read all the input
965                  * tuples, so use the cheapest-total path.      Otherwise, trust
966                  * query_planner's decision about which to use.
967                  */
968                 if (sorted_path && !use_hashed_grouping)
969                 {
970                         result_plan = create_plan(parse, sorted_path);
971                         current_pathkeys = sorted_path->pathkeys;
972                 }
973                 else
974                 {
975                         result_plan = create_plan(parse, cheapest_path);
976                         current_pathkeys = cheapest_path->pathkeys;
977                 }
978
979                 /*
980                  * create_plan() returns a plan with just a "flat" tlist of
981                  * required Vars.  Usually we need to insert the sub_tlist as the
982                  * tlist of the top plan node.  However, we can skip that if we
983                  * determined that whatever query_planner chose to return will be
984                  * good enough.
985                  */
986                 if (need_tlist_eval)
987                 {
988                         /*
989                          * If the top-level plan node is one that cannot do expression
990                          * evaluation, we must insert a Result node to project the
991                          * desired tlist.
992                          */
993                         if (!is_projection_capable_plan(result_plan))
994                         {
995                                 result_plan = (Plan *) make_result(sub_tlist, NULL,
996                                                                                                    result_plan);
997                         }
998                         else
999                         {
1000                                 /*
1001                                  * Otherwise, just replace the subplan's flat tlist with
1002                                  * the desired tlist.
1003                                  */
1004                                 result_plan->targetlist = sub_tlist;
1005                         }
1006
1007                         /*
1008                          * Also, account for the cost of evaluation of the sub_tlist.
1009                          *
1010                          * Up to now, we have only been dealing with "flat" tlists,
1011                          * containing just Vars.  So their evaluation cost is zero
1012                          * according to the model used by cost_qual_eval() (or if you
1013                          * prefer, the cost is factored into cpu_tuple_cost).  Thus we
1014                          * can avoid accounting for tlist cost throughout
1015                          * query_planner() and subroutines.  But now we've inserted a
1016                          * tlist that might contain actual operators, sub-selects, etc
1017                          * --- so we'd better account for its cost.
1018                          *
1019                          * Below this point, any tlist eval cost for added-on nodes
1020                          * should be accounted for as we create those nodes.
1021                          * Presently, of the node types we can add on, only Agg and
1022                          * Group project new tlists (the rest just copy their input
1023                          * tuples) --- so make_agg() and make_group() are responsible
1024                          * for computing the added cost.
1025                          */
1026                         cost_qual_eval(&tlist_cost, sub_tlist);
1027                         result_plan->startup_cost += tlist_cost.startup;
1028                         result_plan->total_cost += tlist_cost.startup +
1029                                 tlist_cost.per_tuple * result_plan->plan_rows;
1030                 }
1031                 else
1032                 {
1033                         /*
1034                          * Since we're using query_planner's tlist and not the one
1035                          * make_subplanTargetList calculated, we have to refigure any
1036                          * grouping-column indexes make_subplanTargetList computed.
1037                          */
1038                         locate_grouping_columns(parse, tlist, result_plan->targetlist,
1039                                                                         groupColIdx);
1040                 }
1041
1042                 /*
1043                  * Insert AGG or GROUP node if needed, plus an explicit sort step
1044                  * if necessary.
1045                  *
1046                  * HAVING clause, if any, becomes qual of the Agg or Group node.
1047                  */
1048                 if (use_hashed_grouping)
1049                 {
1050                         /* Hashed aggregate plan --- no sort needed */
1051                         result_plan = (Plan *) make_agg(parse,
1052                                                                                         tlist,
1053                                                                                         (List *) parse->havingQual,
1054                                                                                         AGG_HASHED,
1055                                                                                         numGroupCols,
1056                                                                                         groupColIdx,
1057                                                                                         numGroups,
1058                                                                                         agg_counts.numAggs,
1059                                                                                         result_plan);
1060                         /* Hashed aggregation produces randomly-ordered results */
1061                         current_pathkeys = NIL;
1062                 }
1063                 else if (parse->hasAggs)
1064                 {
1065                         /* Plain aggregate plan --- sort if needed */
1066                         AggStrategy aggstrategy;
1067
1068                         if (parse->groupClause)
1069                         {
1070                                 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1071                                 {
1072                                         result_plan = (Plan *)
1073                                                 make_sort_from_groupcols(parse,
1074                                                                                                  parse->groupClause,
1075                                                                                                  groupColIdx,
1076                                                                                                  result_plan);
1077                                         current_pathkeys = group_pathkeys;
1078                                 }
1079                                 aggstrategy = AGG_SORTED;
1080
1081                                 /*
1082                                  * The AGG node will not change the sort ordering of its
1083                                  * groups, so current_pathkeys describes the result too.
1084                                  */
1085                         }
1086                         else
1087                         {
1088                                 aggstrategy = AGG_PLAIN;
1089                                 /* Result will be only one row anyway; no sort order */
1090                                 current_pathkeys = NIL;
1091                         }
1092
1093                         result_plan = (Plan *) make_agg(parse,
1094                                                                                         tlist,
1095                                                                                         (List *) parse->havingQual,
1096                                                                                         aggstrategy,
1097                                                                                         numGroupCols,
1098                                                                                         groupColIdx,
1099                                                                                         numGroups,
1100                                                                                         agg_counts.numAggs,
1101                                                                                         result_plan);
1102                 }
1103                 else if (parse->groupClause)
1104                 {
1105                         /*
1106                          * GROUP BY without aggregation, so insert a group node (plus the
1107                          * appropriate sort node, if necessary).
1108                          *
1109                          * Add an explicit sort if we couldn't make the path come
1110                          * out the way the GROUP node needs it.
1111                          */
1112                         if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1113                         {
1114                                 result_plan = (Plan *)
1115                                         make_sort_from_groupcols(parse,
1116                                                                                          parse->groupClause,
1117                                                                                          groupColIdx,
1118                                                                                          result_plan);
1119                                 current_pathkeys = group_pathkeys;
1120                         }
1121
1122                         result_plan = (Plan *) make_group(parse,
1123                                                                                           tlist,
1124                                                                                           (List *) parse->havingQual,
1125                                                                                           numGroupCols,
1126                                                                                           groupColIdx,
1127                                                                                           dNumGroups,
1128                                                                                           result_plan);
1129                         /* The Group node won't change sort ordering */
1130                 }
1131                 else if (parse->hasHavingQual)
1132                 {
1133                         /*
1134                          * No aggregates, and no GROUP BY, but we have a HAVING qual.
1135                          * This is a degenerate case in which we are supposed to emit
1136                          * either 0 or 1 row depending on whether HAVING succeeds.
1137                          * Furthermore, there cannot be any variables in either HAVING
1138                          * or the targetlist, so we actually do not need the FROM table
1139                          * at all!  We can just throw away the plan-so-far and generate
1140                          * a Result node.  This is a sufficiently unusual corner case
1141                          * that it's not worth contorting the structure of this routine
1142                          * to avoid having to generate the plan in the first place.
1143                          */
1144                         result_plan = (Plan *) make_result(tlist,
1145                                                                                            parse->havingQual,
1146                                                                                            NULL);
1147                 }
1148         }                                                       /* end of if (setOperations) */
1149
1150         /*
1151          * If we were not able to make the plan come out in the right order,
1152          * add an explicit sort step.
1153          */
1154         if (parse->sortClause)
1155         {
1156                 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1157                 {
1158                         result_plan = (Plan *)
1159                                 make_sort_from_sortclauses(parse,
1160                                                                                    parse->sortClause,
1161                                                                                    result_plan);
1162                         current_pathkeys = sort_pathkeys;
1163                 }
1164         }
1165
1166         /*
1167          * If there is a DISTINCT clause, add the UNIQUE node.
1168          */
1169         if (parse->distinctClause)
1170         {
1171                 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1172
1173                 /*
1174                  * If there was grouping or aggregation, leave plan_rows as-is
1175                  * (ie, assume the result was already mostly unique).  If not,
1176                  * it's reasonable to assume the UNIQUE filter has effects
1177                  * comparable to GROUP BY.
1178                  */
1179                 if (!parse->groupClause && !parse->hasHavingQual && !parse->hasAggs)
1180                 {
1181                         List       *distinctExprs;
1182
1183                         distinctExprs = get_sortgrouplist_exprs(parse->distinctClause,
1184                                                                                                         parse->targetList);
1185                         result_plan->plan_rows = estimate_num_groups(parse,
1186                                                                                                                  distinctExprs,
1187                                                                                                  result_plan->plan_rows);
1188                 }
1189         }
1190
1191         /*
1192          * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1193          */
1194         if (parse->limitOffset || parse->limitCount)
1195         {
1196                 result_plan = (Plan *) make_limit(result_plan,
1197                                                                                   parse->limitOffset,
1198                                                                                   parse->limitCount);
1199         }
1200
1201         /*
1202          * Return the actual output ordering in query_pathkeys for possible
1203          * use by an outer query level.
1204          */
1205         parse->query_pathkeys = current_pathkeys;
1206
1207         return result_plan;
1208 }
1209
1210 /*
1211  * choose_hashed_grouping - should we use hashed grouping?
1212  */
1213 static bool
1214 choose_hashed_grouping(Query *parse, double tuple_fraction,
1215                                            Path *cheapest_path, Path *sorted_path,
1216                                            List *sort_pathkeys, List *group_pathkeys,
1217                                            double dNumGroups, AggClauseCounts *agg_counts)
1218 {
1219         int                     numGroupCols = list_length(parse->groupClause);
1220         double          cheapest_path_rows;
1221         int                     cheapest_path_width;
1222         Size            hashentrysize;
1223         List       *current_pathkeys;
1224         Path            hashed_p;
1225         Path            sorted_p;
1226
1227         /*
1228          * Check can't-do-it conditions, including whether the grouping operators
1229          * are hashjoinable.
1230          *
1231          * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1232          * (Doing so would imply storing *all* the input values in the hash table,
1233          * which seems like a certain loser.)
1234          */
1235         if (!enable_hashagg)
1236                 return false;
1237         if (agg_counts->numDistinctAggs != 0)
1238                 return false;
1239         if (!hash_safe_grouping(parse))
1240                 return false;
1241
1242         /*
1243          * Don't do it if it doesn't look like the hashtable will fit into
1244          * work_mem.
1245          *
1246          * Beware here of the possibility that cheapest_path->parent is NULL.
1247          * This could happen if user does something silly like
1248          *              SELECT 'foo' GROUP BY 1;
1249          */
1250         if (cheapest_path->parent)
1251         {
1252                 cheapest_path_rows = cheapest_path->parent->rows;
1253                 cheapest_path_width = cheapest_path->parent->width;
1254         }
1255         else
1256         {
1257                 cheapest_path_rows = 1;                         /* assume non-set result */
1258                 cheapest_path_width = 100;                      /* arbitrary */
1259         }
1260
1261         /* Estimate per-hash-entry space at tuple width... */
1262         hashentrysize = cheapest_path_width;
1263         /* plus space for pass-by-ref transition values... */
1264         hashentrysize += agg_counts->transitionSpace;
1265         /* plus the per-hash-entry overhead */
1266         hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1267
1268         if (hashentrysize * dNumGroups > work_mem * 1024L)
1269                 return false;
1270
1271         /*
1272          * See if the estimated cost is no more than doing it the other way.
1273          * While avoiding the need for sorted input is usually a win, the fact
1274          * that the output won't be sorted may be a loss; so we need to do an
1275          * actual cost comparison.
1276          *
1277          * We need to consider
1278          *              cheapest_path + hashagg [+ final sort]
1279          * versus either
1280          *              cheapest_path [+ sort] + group or agg [+ final sort]
1281          * or
1282          *              presorted_path + group or agg [+ final sort]
1283          * where brackets indicate a step that may not be needed. We assume
1284          * query_planner() will have returned a presorted path only if it's a
1285          * winner compared to cheapest_path for this purpose.
1286          *
1287          * These path variables are dummies that just hold cost fields; we don't
1288          * make actual Paths for these steps.
1289          */
1290         cost_agg(&hashed_p, parse, AGG_HASHED, agg_counts->numAggs,
1291                          numGroupCols, dNumGroups,
1292                          cheapest_path->startup_cost, cheapest_path->total_cost,
1293                          cheapest_path_rows);
1294         /* Result of hashed agg is always unsorted */
1295         if (sort_pathkeys)
1296                 cost_sort(&hashed_p, parse, sort_pathkeys, hashed_p.total_cost,
1297                                   dNumGroups, cheapest_path_width);
1298
1299         if (sorted_path)
1300         {
1301                 sorted_p.startup_cost = sorted_path->startup_cost;
1302                 sorted_p.total_cost = sorted_path->total_cost;
1303                 current_pathkeys = sorted_path->pathkeys;
1304         }
1305         else
1306         {
1307                 sorted_p.startup_cost = cheapest_path->startup_cost;
1308                 sorted_p.total_cost = cheapest_path->total_cost;
1309                 current_pathkeys = cheapest_path->pathkeys;
1310         }
1311         if (!pathkeys_contained_in(group_pathkeys,
1312                                                            current_pathkeys))
1313         {
1314                 cost_sort(&sorted_p, parse, group_pathkeys, sorted_p.total_cost,
1315                                   cheapest_path_rows, cheapest_path_width);
1316                 current_pathkeys = group_pathkeys;
1317         }
1318
1319         if (parse->hasAggs)
1320                 cost_agg(&sorted_p, parse, AGG_SORTED, agg_counts->numAggs,
1321                                  numGroupCols, dNumGroups,
1322                                  sorted_p.startup_cost, sorted_p.total_cost,
1323                                  cheapest_path_rows);
1324         else
1325                 cost_group(&sorted_p, parse, numGroupCols, dNumGroups,
1326                                    sorted_p.startup_cost, sorted_p.total_cost,
1327                                    cheapest_path_rows);
1328         /* The Agg or Group node will preserve ordering */
1329         if (sort_pathkeys &&
1330                 !pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1331                 cost_sort(&sorted_p, parse, sort_pathkeys, sorted_p.total_cost,
1332                                   dNumGroups, cheapest_path_width);
1333
1334         /*
1335          * Now make the decision using the top-level tuple fraction.  First we
1336          * have to convert an absolute count (LIMIT) into fractional form.
1337          */
1338         if (tuple_fraction >= 1.0)
1339                 tuple_fraction /= dNumGroups;
1340
1341         if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1342                                                                           tuple_fraction) < 0)
1343         {
1344                 /* Hashed is cheaper, so use it */
1345                 return true;
1346         }
1347         return false;
1348 }
1349
1350 /*
1351  * hash_safe_grouping - are grouping operators hashable?
1352  *
1353  * We assume hashed aggregation will work if the datatype's equality operator
1354  * is marked hashjoinable.
1355  */
1356 static bool
1357 hash_safe_grouping(Query *parse)
1358 {
1359         ListCell   *gl;
1360
1361         foreach(gl, parse->groupClause)
1362         {
1363                 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1364                 TargetEntry *tle = get_sortgroupclause_tle(grpcl, parse->targetList);
1365                 Operator        optup;
1366                 bool            oprcanhash;
1367
1368                 optup = equality_oper(exprType((Node *) tle->expr), true);
1369                 if (!optup)
1370                         return false;
1371                 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1372                 ReleaseSysCache(optup);
1373                 if (!oprcanhash)
1374                         return false;
1375         }
1376         return true;
1377 }
1378
1379 /*---------------
1380  * make_subplanTargetList
1381  *        Generate appropriate target list when grouping is required.
1382  *
1383  * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1384  * above the result of query_planner, we typically want to pass a different
1385  * target list to query_planner than the outer plan nodes should have.
1386  * This routine generates the correct target list for the subplan.
1387  *
1388  * The initial target list passed from the parser already contains entries
1389  * for all ORDER BY and GROUP BY expressions, but it will not have entries
1390  * for variables used only in HAVING clauses; so we need to add those
1391  * variables to the subplan target list.  Also, we flatten all expressions
1392  * except GROUP BY items into their component variables; the other expressions
1393  * will be computed by the inserted nodes rather than by the subplan.
1394  * For example, given a query like
1395  *              SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1396  * we want to pass this targetlist to the subplan:
1397  *              a,b,c,d,a+b
1398  * where the a+b target will be used by the Sort/Group steps, and the
1399  * other targets will be used for computing the final results.  (In the
1400  * above example we could theoretically suppress the a and b targets and
1401  * pass down only c,d,a+b, but it's not really worth the trouble to
1402  * eliminate simple var references from the subplan.  We will avoid doing
1403  * the extra computation to recompute a+b at the outer level; see
1404  * replace_vars_with_subplan_refs() in setrefs.c.)
1405  *
1406  * If we are grouping or aggregating, *and* there are no non-Var grouping
1407  * expressions, then the returned tlist is effectively dummy; we do not
1408  * need to force it to be evaluated, because all the Vars it contains
1409  * should be present in the output of query_planner anyway.
1410  *
1411  * 'parse' is the query being processed.
1412  * 'tlist' is the query's target list.
1413  * 'groupColIdx' receives an array of column numbers for the GROUP BY
1414  *                      expressions (if there are any) in the subplan's target list.
1415  * 'need_tlist_eval' is set true if we really need to evaluate the
1416  *                      result tlist.
1417  *
1418  * The result is the targetlist to be passed to the subplan.
1419  *---------------
1420  */
1421 static List *
1422 make_subplanTargetList(Query *parse,
1423                                            List *tlist,
1424                                            AttrNumber **groupColIdx,
1425                                            bool *need_tlist_eval)
1426 {
1427         List       *sub_tlist;
1428         List       *extravars;
1429         int                     numCols;
1430
1431         *groupColIdx = NULL;
1432
1433         /*
1434          * If we're not grouping or aggregating, there's nothing to do here;
1435          * query_planner should receive the unmodified target list.
1436          */
1437         if (!parse->hasAggs && !parse->groupClause && !parse->hasHavingQual)
1438         {
1439                 *need_tlist_eval = true;
1440                 return tlist;
1441         }
1442
1443         /*
1444          * Otherwise, start with a "flattened" tlist (having just the vars
1445          * mentioned in the targetlist and HAVING qual --- but not upper-
1446          * level Vars; they will be replaced by Params later on).
1447          */
1448         sub_tlist = flatten_tlist(tlist);
1449         extravars = pull_var_clause(parse->havingQual, false);
1450         sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1451         list_free(extravars);
1452         *need_tlist_eval = false;       /* only eval if not flat tlist */
1453
1454         /*
1455          * If grouping, create sub_tlist entries for all GROUP BY expressions
1456          * (GROUP BY items that are simple Vars should be in the list
1457          * already), and make an array showing where the group columns are in
1458          * the sub_tlist.
1459          */
1460         numCols = list_length(parse->groupClause);
1461         if (numCols > 0)
1462         {
1463                 int                     keyno = 0;
1464                 AttrNumber *grpColIdx;
1465                 ListCell   *gl;
1466
1467                 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1468                 *groupColIdx = grpColIdx;
1469
1470                 foreach(gl, parse->groupClause)
1471                 {
1472                         GroupClause *grpcl = (GroupClause *) lfirst(gl);
1473                         Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1474                         TargetEntry *te = NULL;
1475                         ListCell   *sl;
1476
1477                         /* Find or make a matching sub_tlist entry */
1478                         foreach(sl, sub_tlist)
1479                         {
1480                                 te = (TargetEntry *) lfirst(sl);
1481                                 if (equal(groupexpr, te->expr))
1482                                         break;
1483                         }
1484                         if (!sl)
1485                         {
1486                                 te = makeTargetEntry((Expr *) groupexpr,
1487                                                                          list_length(sub_tlist) + 1,
1488                                                                          NULL,
1489                                                                          false);
1490                                 sub_tlist = lappend(sub_tlist, te);
1491                                 *need_tlist_eval = true;                /* it's not flat anymore */
1492                         }
1493
1494                         /* and save its resno */
1495                         grpColIdx[keyno++] = te->resno;
1496                 }
1497         }
1498
1499         return sub_tlist;
1500 }
1501
1502 /*
1503  * locate_grouping_columns
1504  *              Locate grouping columns in the tlist chosen by query_planner.
1505  *
1506  * This is only needed if we don't use the sub_tlist chosen by
1507  * make_subplanTargetList.      We have to forget the column indexes found
1508  * by that routine and re-locate the grouping vars in the real sub_tlist.
1509  */
1510 static void
1511 locate_grouping_columns(Query *parse,
1512                                                 List *tlist,
1513                                                 List *sub_tlist,
1514                                                 AttrNumber *groupColIdx)
1515 {
1516         int                     keyno = 0;
1517         ListCell   *gl;
1518
1519         /*
1520          * No work unless grouping.
1521          */
1522         if (!parse->groupClause)
1523         {
1524                 Assert(groupColIdx == NULL);
1525                 return;
1526         }
1527         Assert(groupColIdx != NULL);
1528
1529         foreach(gl, parse->groupClause)
1530         {
1531                 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1532                 Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1533                 TargetEntry *te = NULL;
1534                 ListCell   *sl;
1535
1536                 foreach(sl, sub_tlist)
1537                 {
1538                         te = (TargetEntry *) lfirst(sl);
1539                         if (equal(groupexpr, te->expr))
1540                                 break;
1541                 }
1542                 if (!sl)
1543                         elog(ERROR, "failed to locate grouping columns");
1544
1545                 groupColIdx[keyno++] = te->resno;
1546         }
1547 }
1548
1549 /*
1550  * postprocess_setop_tlist
1551  *        Fix up targetlist returned by plan_set_operations().
1552  *
1553  * We need to transpose sort key info from the orig_tlist into new_tlist.
1554  * NOTE: this would not be good enough if we supported resjunk sort keys
1555  * for results of set operations --- then, we'd need to project a whole
1556  * new tlist to evaluate the resjunk columns.  For now, just ereport if we
1557  * find any resjunk columns in orig_tlist.
1558  */
1559 static List *
1560 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1561 {
1562         ListCell   *l;
1563         ListCell   *orig_tlist_item = list_head(orig_tlist);
1564
1565         foreach(l, new_tlist)
1566         {
1567                 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1568                 TargetEntry *orig_tle;
1569
1570                 /* ignore resjunk columns in setop result */
1571                 if (new_tle->resjunk)
1572                         continue;
1573
1574                 Assert(orig_tlist_item != NULL);
1575                 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1576                 orig_tlist_item = lnext(orig_tlist_item);
1577                 if (orig_tle->resjunk)                  /* should not happen */
1578                         elog(ERROR, "resjunk output columns are not implemented");
1579                 Assert(new_tle->resno == orig_tle->resno);
1580                 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1581         }
1582         if (orig_tlist_item != NULL)
1583                 elog(ERROR, "resjunk output columns are not implemented");
1584         return new_tlist;
1585 }