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