OSDN Git Service

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