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