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