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