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