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