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