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