]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/planner.c
Rewrite of planner statistics-gathering code. ANALYZE is now available as
[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.106 2001/05/07 00:43:21 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                 /*
367                  * At the moment, we can't pull up subqueries that are inside the
368                  * nullable side of an outer join, because substituting their target
369                  * list entries for upper Var references wouldn't do the right thing
370                  * (the entries wouldn't go to NULL when they're supposed to).
371                  * Suppressing the pullup is an ugly, performance-losing hack, but
372                  * I see no alternative for now.  Find a better way to handle this
373                  * when we redesign query trees --- tgl 4/30/01.
374                  */
375                 switch (j->jointype)
376                 {
377                         case JOIN_INNER:
378                                 j->larg = pull_up_subqueries(parse, j->larg);
379                                 j->rarg = pull_up_subqueries(parse, j->rarg);
380                                 break;
381                         case JOIN_LEFT:
382                                 j->larg = pull_up_subqueries(parse, j->larg);
383                                 break;
384                         case JOIN_FULL:
385                                 break;
386                         case JOIN_RIGHT:
387                                 j->rarg = pull_up_subqueries(parse, j->rarg);
388                                 break;
389                         case JOIN_UNION:
390                                 /*
391                                  * This is where we fail if upper levels of planner
392                                  * haven't rewritten UNION JOIN as an Append ...
393                                  */
394                                 elog(ERROR, "UNION JOIN is not implemented yet");
395                                 break;
396                         default:
397                                 elog(ERROR, "pull_up_subqueries: unexpected join type %d",
398                                          j->jointype);
399                                 break;
400                 }
401         }
402         else
403                 elog(ERROR, "pull_up_subqueries: unexpected node type %d",
404                          nodeTag(jtnode));
405         return jtnode;
406 }
407
408 /*
409  * is_simple_subquery
410  *        Check a subquery in the range table to see if it's simple enough
411  *        to pull up into the parent query.
412  */
413 static bool
414 is_simple_subquery(Query *subquery)
415 {
416
417         /*
418          * Let's just make sure it's a valid subselect ...
419          */
420         if (!IsA(subquery, Query) ||
421                 subquery->commandType != CMD_SELECT ||
422                 subquery->resultRelation != 0 ||
423                 subquery->into != NULL ||
424                 subquery->isPortal)
425                 elog(ERROR, "is_simple_subquery: subquery is bogus");
426
427         /*
428          * Can't currently pull up a query with setops. Maybe after querytree
429          * redesign...
430          */
431         if (subquery->setOperations)
432                 return false;
433
434         /*
435          * Can't pull up a subquery involving grouping, aggregation, sorting,
436          * or limiting.
437          */
438         if (subquery->hasAggs ||
439                 subquery->groupClause ||
440                 subquery->havingQual ||
441                 subquery->sortClause ||
442                 subquery->distinctClause ||
443                 subquery->limitOffset ||
444                 subquery->limitCount)
445                 return false;
446
447         /*
448          * Hack: don't try to pull up a subquery with an empty jointree.
449          * query_planner() will correctly generate a Result plan for a
450          * jointree that's totally empty, but I don't think the right things
451          * happen if an empty FromExpr appears lower down in a jointree. Not
452          * worth working hard on this, just to collapse SubqueryScan/Result
453          * into Result...
454          */
455         if (subquery->jointree->fromlist == NIL)
456                 return false;
457
458         return true;
459 }
460
461 /*
462  * Helper routine for pull_up_subqueries: do ResolveNew on every expression
463  * in the jointree, without changing the jointree structure itself.  Ugly,
464  * but there's no other way...
465  */
466 static void
467 resolvenew_in_jointree(Node *jtnode, int varno, List *subtlist)
468 {
469         if (jtnode == NULL)
470                 return;
471         if (IsA(jtnode, RangeTblRef))
472         {
473                 /* nothing to do here */
474         }
475         else if (IsA(jtnode, FromExpr))
476         {
477                 FromExpr   *f = (FromExpr *) jtnode;
478                 List       *l;
479
480                 foreach(l, f->fromlist)
481                         resolvenew_in_jointree(lfirst(l), varno, subtlist);
482                 f->quals = ResolveNew(f->quals,
483                                                           varno, 0, subtlist, CMD_SELECT, 0);
484         }
485         else if (IsA(jtnode, JoinExpr))
486         {
487                 JoinExpr   *j = (JoinExpr *) jtnode;
488
489                 resolvenew_in_jointree(j->larg, varno, subtlist);
490                 resolvenew_in_jointree(j->rarg, varno, subtlist);
491                 j->quals = ResolveNew(j->quals,
492                                                           varno, 0, subtlist, CMD_SELECT, 0);
493
494                 /*
495                  * We don't bother to update the colvars list, since it won't be
496                  * used again ...
497                  */
498         }
499         else
500                 elog(ERROR, "resolvenew_in_jointree: unexpected node type %d",
501                          nodeTag(jtnode));
502 }
503
504 /*
505  * preprocess_jointree
506  *              Attempt to simplify a query's jointree.
507  *
508  * If we succeed in pulling up a subquery then we might form a jointree
509  * in which a FromExpr is a direct child of another FromExpr.  In that
510  * case we can consider collapsing the two FromExprs into one.  This is
511  * an optional conversion, since the planner will work correctly either
512  * way.  But we may find a better plan (at the cost of more planning time)
513  * if we merge the two nodes.
514  *
515  * NOTE: don't try to do this in the same jointree scan that does subquery
516  * pullup!      Since we're changing the jointree structure here, that wouldn't
517  * work reliably --- see comments for pull_up_subqueries().
518  */
519 static Node *
520 preprocess_jointree(Query *parse, Node *jtnode)
521 {
522         if (jtnode == NULL)
523                 return NULL;
524         if (IsA(jtnode, RangeTblRef))
525         {
526                 /* nothing to do here... */
527         }
528         else if (IsA(jtnode, FromExpr))
529         {
530                 FromExpr   *f = (FromExpr *) jtnode;
531                 List       *newlist = NIL;
532                 List       *l;
533
534                 foreach(l, f->fromlist)
535                 {
536                         Node       *child = (Node *) lfirst(l);
537
538                         /* Recursively simplify the child... */
539                         child = preprocess_jointree(parse, child);
540                         /* Now, is it a FromExpr? */
541                         if (child && IsA(child, FromExpr))
542                         {
543
544                                 /*
545                                  * Yes, so do we want to merge it into parent?  Always do
546                                  * so if child has just one element (since that doesn't
547                                  * make the parent's list any longer).  Otherwise we have
548                                  * to be careful about the increase in planning time
549                                  * caused by combining the two join search spaces into
550                                  * one.  Our heuristic is to merge if the merge will
551                                  * produce a join list no longer than GEQO_RELS/2.
552                                  * (Perhaps need an additional user parameter?)
553                                  */
554                                 FromExpr   *subf = (FromExpr *) child;
555                                 int                     childlen = length(subf->fromlist);
556                                 int                     myothers = length(newlist) + length(lnext(l));
557
558                                 if (childlen <= 1 || (childlen + myothers) <= geqo_rels / 2)
559                                 {
560                                         newlist = nconc(newlist, subf->fromlist);
561                                         f->quals = make_and_qual(f->quals, subf->quals);
562                                 }
563                                 else
564                                         newlist = lappend(newlist, child);
565                         }
566                         else
567                                 newlist = lappend(newlist, child);
568                 }
569                 f->fromlist = newlist;
570         }
571         else if (IsA(jtnode, JoinExpr))
572         {
573                 JoinExpr   *j = (JoinExpr *) jtnode;
574
575                 /* Can't usefully change the JoinExpr, but recurse on children */
576                 j->larg = preprocess_jointree(parse, j->larg);
577                 j->rarg = preprocess_jointree(parse, j->rarg);
578         }
579         else
580                 elog(ERROR, "preprocess_jointree: unexpected node type %d",
581                          nodeTag(jtnode));
582         return jtnode;
583 }
584
585 /*
586  * preprocess_expression
587  *              Do subquery_planner's preprocessing work for an expression,
588  *              which can be a targetlist, a WHERE clause (including JOIN/ON
589  *              conditions), or a HAVING clause.
590  */
591 static Node *
592 preprocess_expression(Query *parse, Node *expr, int kind)
593 {
594
595         /*
596          * Simplify constant expressions.
597          *
598          * Note that at this point quals have not yet been converted to
599          * implicit-AND form, so we can apply eval_const_expressions directly.
600          * Also note that we need to do this before SS_process_sublinks,
601          * because that routine inserts bogus "Const" nodes.
602          */
603         expr = eval_const_expressions(expr);
604
605         /*
606          * If it's a qual or havingQual, canonicalize it, and convert it to
607          * implicit-AND format.
608          *
609          * XXX Is there any value in re-applying eval_const_expressions after
610          * canonicalize_qual?
611          */
612         if (kind != EXPRKIND_TARGET)
613         {
614                 expr = (Node *) canonicalize_qual((Expr *) expr, true);
615
616 #ifdef OPTIMIZER_DEBUG
617                 printf("After canonicalize_qual()\n");
618                 pprint(expr);
619 #endif
620         }
621
622         if (parse->hasSubLinks)
623         {
624                 /* Expand SubLinks to SubPlans */
625                 expr = SS_process_sublinks(expr);
626
627                 if (kind != EXPRKIND_WHERE &&
628                         (parse->groupClause != NIL || parse->hasAggs))
629                 {
630
631                         /*
632                          * Check for ungrouped variables passed to subplans.  Note we
633                          * do NOT do this for subplans in WHERE (or JOIN/ON); it's
634                          * legal there because WHERE is evaluated pre-GROUP.
635                          */
636                         check_subplans_for_ungrouped_vars(expr, parse);
637                 }
638         }
639
640         /* Replace uplevel vars with Param nodes */
641         if (PlannerQueryLevel > 1)
642                 expr = SS_replace_correlation_vars(expr);
643
644         return expr;
645 }
646
647 /*
648  * preprocess_qual_conditions
649  *              Recursively scan the query's jointree and do subquery_planner's
650  *              preprocessing work on each qual condition found therein.
651  */
652 static void
653 preprocess_qual_conditions(Query *parse, Node *jtnode)
654 {
655         if (jtnode == NULL)
656                 return;
657         if (IsA(jtnode, RangeTblRef))
658         {
659                 /* nothing to do here */
660         }
661         else if (IsA(jtnode, FromExpr))
662         {
663                 FromExpr   *f = (FromExpr *) jtnode;
664                 List       *l;
665
666                 foreach(l, f->fromlist)
667                         preprocess_qual_conditions(parse, lfirst(l));
668
669                 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_WHERE);
670         }
671         else if (IsA(jtnode, JoinExpr))
672         {
673                 JoinExpr   *j = (JoinExpr *) jtnode;
674
675                 preprocess_qual_conditions(parse, j->larg);
676                 preprocess_qual_conditions(parse, j->rarg);
677
678                 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_WHERE);
679         }
680         else
681                 elog(ERROR, "preprocess_qual_conditions: unexpected node type %d",
682                          nodeTag(jtnode));
683 }
684
685 /*--------------------
686  * inheritance_planner
687  *        Generate a plan in the case where the result relation is an
688  *        inheritance set.
689  *
690  * We have to handle this case differently from cases where a source
691  * relation is an inheritance set.      Source inheritance is expanded at
692  * the bottom of the plan tree (see allpaths.c), but target inheritance
693  * has to be expanded at the top.  The reason is that for UPDATE, each
694  * target relation needs a different targetlist matching its own column
695  * set.  (This is not so critical for DELETE, but for simplicity we treat
696  * inherited DELETE the same way.)      Fortunately, the UPDATE/DELETE target
697  * can never be the nullable side of an outer join, so it's OK to generate
698  * the plan this way.
699  *
700  * parse is the querytree produced by the parser & rewriter.
701  * inheritlist is an integer list of RT indexes for the result relation set.
702  *
703  * Returns a query plan.
704  *--------------------
705  */
706 static Plan *
707 inheritance_planner(Query *parse, List *inheritlist)
708 {
709         int                     parentRTindex = parse->resultRelation;
710         Oid                     parentOID = getrelid(parentRTindex, parse->rtable);
711         List       *subplans = NIL;
712         List       *tlist = NIL;
713         List       *l;
714
715         foreach(l, inheritlist)
716         {
717                 int                     childRTindex = lfirsti(l);
718                 Oid                     childOID = getrelid(childRTindex, parse->rtable);
719                 Query      *subquery;
720                 Plan       *subplan;
721
722                 /* Generate modified query with this rel as target */
723                 subquery = (Query *) adjust_inherited_attrs((Node *) parse,
724                                                                                                 parentRTindex, parentOID,
725                                                                                                  childRTindex, childOID);
726                 /* Generate plan */
727                 subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */ );
728                 subplans = lappend(subplans, subplan);
729                 /* Save preprocessed tlist from first rel for use in Append */
730                 if (tlist == NIL)
731                         tlist = subplan->targetlist;
732         }
733
734         /* Save the target-relations list for the executor, too */
735         parse->resultRelations = inheritlist;
736
737         return (Plan *) make_append(subplans, true, tlist);
738 }
739
740 /*--------------------
741  * grouping_planner
742  *        Perform planning steps related to grouping, aggregation, etc.
743  *        This primarily means adding top-level processing to the basic
744  *        query plan produced by query_planner.
745  *
746  * parse is the querytree produced by the parser & rewriter.
747  * tuple_fraction is the fraction of tuples we expect will be retrieved
748  *
749  * tuple_fraction is interpreted as follows:
750  *        < 0: determine fraction by inspection of query (normal case)
751  *        0: expect all tuples to be retrieved
752  *        0 < tuple_fraction < 1: expect the given fraction of tuples available
753  *              from the plan to be retrieved
754  *        tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
755  *              expected to be retrieved (ie, a LIMIT specification)
756  * The normal case is to pass -1, but some callers pass values >= 0 to
757  * override this routine's determination of the appropriate fraction.
758  *
759  * Returns a query plan.
760  *--------------------
761  */
762 static Plan *
763 grouping_planner(Query *parse, double tuple_fraction)
764 {
765         List       *tlist = parse->targetList;
766         Plan       *result_plan;
767         List       *current_pathkeys;
768         List       *group_pathkeys;
769         List       *sort_pathkeys;
770         AttrNumber *groupColIdx = NULL;
771
772         if (parse->setOperations)
773         {
774
775                 /*
776                  * Construct the plan for set operations.  The result will not
777                  * need any work except perhaps a top-level sort and/or LIMIT.
778                  */
779                 result_plan = plan_set_operations(parse);
780
781                 /*
782                  * We should not need to call preprocess_targetlist, since we must
783                  * be in a SELECT query node.  Instead, use the targetlist
784                  * returned by plan_set_operations (since this tells whether it
785                  * returned any resjunk columns!), and transfer any sort key
786                  * information from the original tlist.
787                  */
788                 Assert(parse->commandType == CMD_SELECT);
789
790                 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
791
792                 /*
793                  * Can't handle FOR UPDATE here (parser should have checked
794                  * already, but let's make sure).
795                  */
796                 if (parse->rowMarks)
797                         elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
798
799                 /*
800                  * We set current_pathkeys NIL indicating we do not know sort
801                  * order.  This is correct when the top set operation is UNION
802                  * ALL, since the appended-together results are unsorted even if
803                  * the subplans were sorted.  For other set operations we could be
804                  * smarter --- room for future improvement!
805                  */
806                 current_pathkeys = NIL;
807
808                 /*
809                  * Calculate pathkeys that represent grouping/ordering
810                  * requirements (grouping should always be null, but...)
811                  */
812                 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
813                                                                                                            tlist);
814                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
815                                                                                                           tlist);
816         }
817         else
818         {
819                 List       *sub_tlist;
820
821                 /* Preprocess targetlist in case we are inside an INSERT/UPDATE. */
822                 tlist = preprocess_targetlist(tlist,
823                                                                           parse->commandType,
824                                                                           parse->resultRelation,
825                                                                           parse->rtable);
826
827                 /*
828                  * Add TID targets for rels selected FOR UPDATE (should this be
829                  * done in preprocess_targetlist?).  The executor uses the TID to
830                  * know which rows to lock, much as for UPDATE or DELETE.
831                  */
832                 if (parse->rowMarks)
833                 {
834                         List       *l;
835
836                         /*
837                          * We've got trouble if the FOR UPDATE appears inside
838                          * grouping, since grouping renders a reference to individual
839                          * tuple CTIDs invalid.  This is also checked at parse time,
840                          * but that's insufficient because of rule substitution, query
841                          * pullup, etc.
842                          */
843                         CheckSelectForUpdate(parse);
844
845                         /*
846                          * Currently the executor only supports FOR UPDATE at top
847                          * level
848                          */
849                         if (PlannerQueryLevel > 1)
850                                 elog(ERROR, "SELECT FOR UPDATE is not allowed in subselects");
851
852                         foreach(l, parse->rowMarks)
853                         {
854                                 Index           rti = lfirsti(l);
855                                 char       *resname;
856                                 Resdom     *resdom;
857                                 Var                *var;
858                                 TargetEntry *ctid;
859
860                                 resname = (char *) palloc(32);
861                                 sprintf(resname, "ctid%u", rti);
862                                 resdom = makeResdom(length(tlist) + 1,
863                                                                         TIDOID,
864                                                                         -1,
865                                                                         resname,
866                                                                         true);
867
868                                 var = makeVar(rti,
869                                                           SelfItemPointerAttributeNumber,
870                                                           TIDOID,
871                                                           -1,
872                                                           0);
873
874                                 ctid = makeTargetEntry(resdom, (Node *) var);
875                                 tlist = lappend(tlist, ctid);
876                         }
877                 }
878
879                 /*
880                  * Generate appropriate target list for subplan; may be different
881                  * from tlist if grouping or aggregation is needed.
882                  */
883                 sub_tlist = make_subplanTargetList(parse, tlist, &groupColIdx);
884
885                 /*
886                  * Calculate pathkeys that represent grouping/ordering
887                  * requirements
888                  */
889                 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
890                                                                                                            tlist);
891                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
892                                                                                                           tlist);
893
894                 /*
895                  * Figure out whether we need a sorted result from query_planner.
896                  *
897                  * If we have a GROUP BY clause, then we want a result sorted
898                  * properly for grouping.  Otherwise, if there is an ORDER BY
899                  * clause, we want to sort by the ORDER BY clause.      (Note: if we
900                  * have both, and ORDER BY is a superset of GROUP BY, it would be
901                  * tempting to request sort by ORDER BY --- but that might just
902                  * leave us failing to exploit an available sort order at all.
903                  * Needs more thought...)
904                  */
905                 if (parse->groupClause)
906                         parse->query_pathkeys = group_pathkeys;
907                 else if (parse->sortClause)
908                         parse->query_pathkeys = sort_pathkeys;
909                 else
910                         parse->query_pathkeys = NIL;
911
912                 /*
913                  * Figure out whether we expect to retrieve all the tuples that
914                  * the plan can generate, or to stop early due to outside factors
915                  * such as a cursor.  If the caller passed a value >= 0, believe
916                  * that value, else do our own examination of the query context.
917                  */
918                 if (tuple_fraction < 0.0)
919                 {
920                         /* Initial assumption is we need all the tuples */
921                         tuple_fraction = 0.0;
922
923                         /*
924                          * Check for retrieve-into-portal, ie DECLARE CURSOR.
925                          *
926                          * We have no real idea how many tuples the user will ultimately
927                          * FETCH from a cursor, but it seems a good bet that he
928                          * doesn't want 'em all.  Optimize for 10% retrieval (you
929                          * gotta better number?  Should this be a SETtable parameter?)
930                          */
931                         if (parse->isPortal)
932                                 tuple_fraction = 0.10;
933                 }
934
935                 /*
936                  * Adjust tuple_fraction if we see that we are going to apply
937                  * limiting/grouping/aggregation/etc.  This is not overridable by
938                  * the caller, since it reflects plan actions that this routine
939                  * will certainly take, not assumptions about context.
940                  */
941                 if (parse->limitCount != NULL)
942                 {
943                         /*
944                          * A LIMIT clause limits the absolute number of tuples returned.
945                          * However, if it's not a constant LIMIT then we have to punt;
946                          * for lack of a better idea, assume 10% of the plan's result
947                          * is wanted.
948                          */
949                         double  limit_fraction = 0.0;
950
951                         if (IsA(parse->limitCount, Const))
952                         {
953                                 Const      *limitc = (Const *) parse->limitCount;
954                                 int32           count = DatumGetInt32(limitc->constvalue);
955
956                                 /*
957                                  * A NULL-constant LIMIT represents "LIMIT ALL", which
958                                  * we treat the same as no limit (ie, expect to
959                                  * retrieve all the tuples).
960                                  */
961                                 if (!limitc->constisnull && count > 0)
962                                 {
963                                         limit_fraction = (double) count;
964                                         /* We must also consider the OFFSET, if present */
965                                         if (parse->limitOffset != NULL)
966                                         {
967                                                 if (IsA(parse->limitOffset, Const))
968                                                 {
969                                                         int32           offset;
970
971                                                         limitc = (Const *) parse->limitOffset;
972                                                         offset = DatumGetInt32(limitc->constvalue);
973                                                         if (!limitc->constisnull && offset > 0)
974                                                                 limit_fraction += (double) offset;
975                                                 }
976                                                 else
977                                                 {
978                                                         /* OFFSET is an expression ... punt ... */
979                                                         limit_fraction = 0.10;
980                                                 }
981                                         }
982                                 }
983                         }
984                         else
985                         {
986                                 /* LIMIT is an expression ... punt ... */
987                                 limit_fraction = 0.10;
988                         }
989
990                         if (limit_fraction > 0.0)
991                         {
992                                 /*
993                                  * If we have absolute limits from both caller and LIMIT,
994                                  * use the smaller value; if one is fractional and the other
995                                  * absolute, treat the fraction as a fraction of the absolute
996                                  * value; else we can multiply the two fractions together.
997                                  */
998                                 if (tuple_fraction >= 1.0)
999                                 {
1000                                         if (limit_fraction >= 1.0)
1001                                         {
1002                                                 /* both absolute */
1003                                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
1004                                         }
1005                                         else
1006                                         {
1007                                                 /* caller absolute, limit fractional */
1008                                                 tuple_fraction *= limit_fraction;
1009                                                 if (tuple_fraction < 1.0)
1010                                                         tuple_fraction = 1.0;
1011                                         }
1012                                 }
1013                                 else if (tuple_fraction > 0.0)
1014                                 {
1015                                         if (limit_fraction >= 1.0)
1016                                         {
1017                                                 /* caller fractional, limit absolute */
1018                                                 tuple_fraction *= limit_fraction;
1019                                                 if (tuple_fraction < 1.0)
1020                                                         tuple_fraction = 1.0;
1021                                         }
1022                                         else
1023                                         {
1024                                                 /* both fractional */
1025                                                 tuple_fraction *= limit_fraction;
1026                                         }
1027                                 }
1028                                 else
1029                                 {
1030                                         /* no info from caller, just use limit */
1031                                         tuple_fraction = limit_fraction;
1032                                 }
1033                         }
1034                 }
1035
1036                 if (parse->groupClause)
1037                 {
1038
1039                         /*
1040                          * In GROUP BY mode, we have the little problem that we don't
1041                          * really know how many input tuples will be needed to make a
1042                          * group, so we can't translate an output LIMIT count into an
1043                          * input count.  For lack of a better idea, assume 25% of the
1044                          * input data will be processed if there is any output limit.
1045                          * However, if the caller gave us a fraction rather than an
1046                          * absolute count, we can keep using that fraction (which
1047                          * amounts to assuming that all the groups are about the same
1048                          * size).
1049                          */
1050                         if (tuple_fraction >= 1.0)
1051                                 tuple_fraction = 0.25;
1052
1053                         /*
1054                          * If both GROUP BY and ORDER BY are specified, we will need
1055                          * two levels of sort --- and, therefore, certainly need to
1056                          * read all the input tuples --- unless ORDER BY is a subset
1057                          * of GROUP BY.  (We have not yet canonicalized the pathkeys,
1058                          * so must use the slower noncanonical comparison method.)
1059                          */
1060                         if (parse->groupClause && parse->sortClause &&
1061                                 !noncanonical_pathkeys_contained_in(sort_pathkeys,
1062                                                                                                         group_pathkeys))
1063                                 tuple_fraction = 0.0;
1064                 }
1065                 else if (parse->hasAggs)
1066                 {
1067
1068                         /*
1069                          * Ungrouped aggregate will certainly want all the input
1070                          * tuples.
1071                          */
1072                         tuple_fraction = 0.0;
1073                 }
1074                 else if (parse->distinctClause)
1075                 {
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                         /*
1147                          * We will need to do an explicit sort by the GROUP BY clause.
1148                          * make_groupplan will do the work, but set current_pathkeys
1149                          * to indicate the resulting order.
1150                          */
1151                         is_sorted = false;
1152                         current_pathkeys = group_pathkeys;
1153                 }
1154
1155                 result_plan = make_groupplan(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(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(List *group_tlist,
1332                            bool tuplePerGroup,
1333                            List *groupClause,
1334                            AttrNumber *grpColIdx,
1335                            bool is_presorted,
1336                            Plan *subplan)
1337 {
1338         int                     numCols = length(groupClause);
1339
1340         if (!is_presorted)
1341         {
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(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(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(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 }