]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/planner.c
Ye-old pgindent run. Same 4-space tabs.
[postgresql] / src / backend / optimizer / plan / planner.c
1 /*-------------------------------------------------------------------------
2  *
3  * planner.c
4  *        The query optimizer external interface.
5  *
6  * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
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.79 2000/04/12 17:15:22 momjian Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include <sys/types.h>
16
17 #include "postgres.h"
18
19 #include "access/genam.h"
20 #include "access/heapam.h"
21 #include "catalog/pg_type.h"
22 #include "executor/executor.h"
23 #include "nodes/makefuncs.h"
24 #include "optimizer/clauses.h"
25 #include "optimizer/internal.h"
26 #include "optimizer/paths.h"
27 #include "optimizer/planmain.h"
28 #include "optimizer/planner.h"
29 #include "optimizer/prep.h"
30 #include "optimizer/subselect.h"
31 #include "optimizer/tlist.h"
32 #include "optimizer/var.h"
33 #include "parser/parse_expr.h"
34 #include "parser/parse_oper.h"
35 #include "utils/builtins.h"
36 #include "utils/lsyscache.h"
37 #include "utils/syscache.h"
38
39
40 static List *make_subplanTargetList(Query *parse, List *tlist,
41                                            AttrNumber **groupColIdx);
42 static Plan *make_groupplan(List *group_tlist, bool tuplePerGroup,
43                            List *groupClause, AttrNumber *grpColIdx,
44                            bool is_presorted, Plan *subplan);
45 static Plan *make_sortplan(List *tlist, List *sortcls, Plan *plannode);
46
47 /*****************************************************************************
48  *
49  *         Query optimizer entry point
50  *
51  *****************************************************************************/
52 Plan *
53 planner(Query *parse)
54 {
55         Plan       *result_plan;
56
57         /* Initialize state for subselects */
58         PlannerQueryLevel = 1;
59         PlannerInitPlan = NULL;
60         PlannerParamVar = NULL;
61         PlannerPlanId = 0;
62
63         /* this should go away sometime soon */
64         transformKeySetQuery(parse);
65
66         /* primary planning entry point (may recurse for subplans) */
67         result_plan = subquery_planner(parse, -1.0 /* default case */ );
68
69         Assert(PlannerQueryLevel == 1);
70
71         /* if top-level query had subqueries, do housekeeping for them */
72         if (PlannerPlanId > 0)
73         {
74                 (void) SS_finalize_plan(result_plan);
75                 result_plan->initPlan = PlannerInitPlan;
76         }
77
78         /* executor wants to know total number of Params used overall */
79         result_plan->nParamExec = length(PlannerParamVar);
80
81         /* final cleanup of the plan */
82         set_plan_references(result_plan);
83
84         return result_plan;
85 }
86
87
88 /*--------------------
89  * subquery_planner
90  *        Invokes the planner on a subquery.  We recurse to here for each
91  *        sub-SELECT found in the query tree.
92  *
93  * parse is the querytree produced by the parser & rewriter.
94  * tuple_fraction is the fraction of tuples we expect will be retrieved.
95  * tuple_fraction is interpreted as explained for union_planner, below.
96  *
97  * Basically, this routine does the stuff that should only be done once
98  * per Query object.  It then calls union_planner, which may be called
99  * recursively on the same Query node in order to handle UNIONs and/or
100  * inheritance.  subquery_planner is called recursively from subselect.c.
101  *
102  * prepunion.c uses an unholy combination of calling union_planner when
103  * recursing on the primary Query node, or subquery_planner when recursing
104  * on a UNION'd Query node that hasn't previously been seen by
105  * subquery_planner.  That whole chunk of code needs rewritten from scratch.
106  *
107  * Returns a query plan.
108  *--------------------
109  */
110 Plan *
111 subquery_planner(Query *parse, double tuple_fraction)
112 {
113
114         /*
115          * A HAVING clause without aggregates is equivalent to a WHERE clause
116          * (except it can only refer to grouped fields).  If there are no aggs
117          * anywhere in the query, then we don't want to create an Agg plan
118          * node, so merge the HAVING condition into WHERE.      (We used to
119          * consider this an error condition, but it seems to be legal SQL.)
120          */
121         if (parse->havingQual != NULL && !parse->hasAggs)
122         {
123                 if (parse->qual == NULL)
124                         parse->qual = parse->havingQual;
125                 else
126                         parse->qual = (Node *) make_andclause(lappend(lcons(parse->qual,
127                                                                                                                                 NIL),
128                                                                                                          parse->havingQual));
129                 parse->havingQual = NULL;
130         }
131
132         /*
133          * Simplify constant expressions in targetlist and quals.
134          *
135          * Note that at this point the qual has not yet been converted to
136          * implicit-AND form, so we can apply eval_const_expressions directly.
137          * Also note that we need to do this before SS_process_sublinks,
138          * because that routine inserts bogus "Const" nodes.
139          */
140         parse->targetList = (List *)
141                 eval_const_expressions((Node *) parse->targetList);
142         parse->qual = eval_const_expressions(parse->qual);
143         parse->havingQual = eval_const_expressions(parse->havingQual);
144
145         /*
146          * Canonicalize the qual, and convert it to implicit-AND format.
147          *
148          * XXX Is there any value in re-applying eval_const_expressions after
149          * canonicalize_qual?
150          */
151         parse->qual = (Node *) canonicalize_qual((Expr *) parse->qual, true);
152 #ifdef OPTIMIZER_DEBUG
153         printf("After canonicalize_qual()\n");
154         pprint(parse->qual);
155 #endif
156
157         /*
158          * Ditto for the havingQual
159          */
160         parse->havingQual = (Node *) canonicalize_qual((Expr *) parse->havingQual,
161                                                                                                    true);
162
163         /* Expand SubLinks to SubPlans */
164         if (parse->hasSubLinks)
165         {
166                 parse->targetList = (List *)
167                         SS_process_sublinks((Node *) parse->targetList);
168                 parse->qual = SS_process_sublinks(parse->qual);
169                 parse->havingQual = SS_process_sublinks(parse->havingQual);
170
171                 if (parse->groupClause != NIL)
172                 {
173
174                         /*
175                          * Check for ungrouped variables passed to subplans. Note we
176                          * do NOT do this for subplans in WHERE; it's legal there
177                          * because WHERE is evaluated pre-GROUP.
178                          *
179                          * An interesting fine point: if we reassigned a HAVING qual into
180                          * WHERE above, then we will accept references to ungrouped
181                          * vars from subplans in the HAVING qual.  This is not
182                          * entirely consistent, but it doesn't seem particularly
183                          * harmful...
184                          */
185                         check_subplans_for_ungrouped_vars((Node *) parse->targetList,
186                                                                                           parse);
187                         check_subplans_for_ungrouped_vars(parse->havingQual, parse);
188                 }
189         }
190
191         /* Replace uplevel vars with Param nodes */
192         if (PlannerQueryLevel > 1)
193         {
194                 parse->targetList = (List *)
195                         SS_replace_correlation_vars((Node *) parse->targetList);
196                 parse->qual = SS_replace_correlation_vars(parse->qual);
197                 parse->havingQual = SS_replace_correlation_vars(parse->havingQual);
198         }
199
200         /* Do the main planning (potentially recursive) */
201
202         return union_planner(parse, tuple_fraction);
203
204         /*
205          * XXX should any more of union_planner's activity be moved here?
206          *
207          * That would take careful study of the interactions with prepunion.c,
208          * but I suspect it would pay off in simplicity and avoidance of
209          * wasted cycles.
210          */
211 }
212
213
214 /*--------------------
215  * union_planner
216  *        Invokes the planner on union-type queries (both regular UNIONs and
217  *        appends produced by inheritance), recursing if necessary to get them
218  *        all, then processes normal plans.
219  *
220  * parse is the querytree produced by the parser & rewriter.
221  * tuple_fraction is the fraction of tuples we expect will be retrieved
222  *
223  * tuple_fraction is interpreted as follows:
224  *        < 0: determine fraction by inspection of query (normal case)
225  *        0: expect all tuples to be retrieved
226  *        0 < tuple_fraction < 1: expect the given fraction of tuples available
227  *              from the plan to be retrieved
228  *        tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
229  *              expected to be retrieved (ie, a LIMIT specification)
230  * The normal case is to pass -1, but some callers pass values >= 0 to
231  * override this routine's determination of the appropriate fraction.
232  *
233  * Returns a query plan.
234  *--------------------
235  */
236 Plan *
237 union_planner(Query *parse,
238                           double tuple_fraction)
239 {
240         List       *tlist = parse->targetList;
241         List       *rangetable = parse->rtable;
242         Plan       *result_plan = (Plan *) NULL;
243         AttrNumber *groupColIdx = NULL;
244         List       *current_pathkeys = NIL;
245         List       *group_pathkeys;
246         List       *sort_pathkeys;
247         Index           rt_index;
248
249         if (parse->unionClause)
250         {
251                 result_plan = (Plan *) plan_union_queries(parse);
252                 /* XXX do we need to do this? bjm 12/19/97 */
253                 tlist = preprocess_targetlist(tlist,
254                                                                           parse->commandType,
255                                                                           parse->resultRelation,
256                                                                           parse->rtable);
257
258                 /*
259                  * We leave current_pathkeys NIL indicating we do not know sort
260                  * order. Actually, for a normal UNION we have done an explicit
261                  * sort; ought to change interface to plan_union_queries to pass
262                  * that info back!
263                  */
264
265                 /*
266                  * Calculate pathkeys that represent grouping/ordering
267                  * requirements
268                  */
269                 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
270                                                                                                            tlist);
271                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
272                                                                                                           tlist);
273         }
274         else if ((rt_index = first_inherit_rt_entry(rangetable)) != -1)
275         {
276                 List       *sub_tlist;
277
278                 /*
279                  * Generate appropriate target list for subplan; may be different
280                  * from tlist if grouping or aggregation is needed.
281                  */
282                 sub_tlist = make_subplanTargetList(parse, tlist, &groupColIdx);
283
284                 /*
285                  * Recursively plan the subqueries needed for inheritance
286                  */
287                 result_plan = (Plan *) plan_inherit_queries(parse, sub_tlist,
288                                                                                                         rt_index);
289
290                 /*
291                  * Fix up outer target list.  NOTE: unlike the case for
292                  * non-inherited query, we pass the unfixed tlist to subplans,
293                  * which do their own fixing.  But we still want to fix the outer
294                  * target list afterwards. I *think* this is correct --- doing the
295                  * fix before recursing is definitely wrong, because
296                  * preprocess_targetlist() will do the wrong thing if invoked
297                  * twice on the same list. Maybe that is a bug? tgl 6/6/99
298                  */
299                 tlist = preprocess_targetlist(tlist,
300                                                                           parse->commandType,
301                                                                           parse->resultRelation,
302                                                                           parse->rtable);
303
304                 if (parse->rowMark != NULL)
305                         elog(ERROR, "SELECT FOR UPDATE is not supported for inherit queries");
306
307                 /*
308                  * We leave current_pathkeys NIL indicating we do not know sort
309                  * order of the Append-ed results.
310                  */
311
312                 /*
313                  * Calculate pathkeys that represent grouping/ordering
314                  * requirements
315                  */
316                 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
317                                                                                                            tlist);
318                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
319                                                                                                           tlist);
320         }
321         else
322         {
323                 List       *sub_tlist;
324
325                 /* Preprocess targetlist in case we are inside an INSERT/UPDATE. */
326                 tlist = preprocess_targetlist(tlist,
327                                                                           parse->commandType,
328                                                                           parse->resultRelation,
329                                                                           parse->rtable);
330
331                 /*
332                  * Add row-mark targets for UPDATE (should this be done in
333                  * preprocess_targetlist?)
334                  */
335                 if (parse->rowMark != NULL)
336                 {
337                         List       *l;
338
339                         foreach(l, parse->rowMark)
340                         {
341                                 RowMark    *rowmark = (RowMark *) lfirst(l);
342                                 TargetEntry *ctid;
343                                 Resdom     *resdom;
344                                 Var                *var;
345                                 char       *resname;
346
347                                 if (!(rowmark->info & ROW_MARK_FOR_UPDATE))
348                                         continue;
349
350                                 resname = (char *) palloc(32);
351                                 sprintf(resname, "ctid%u", rowmark->rti);
352                                 resdom = makeResdom(length(tlist) + 1,
353                                                                         TIDOID,
354                                                                         -1,
355                                                                         resname,
356                                                                         0,
357                                                                         0,
358                                                                         true);
359
360                                 var = makeVar(rowmark->rti, -1, TIDOID, -1, 0);
361
362                                 ctid = makeTargetEntry(resdom, (Node *) var);
363                                 tlist = lappend(tlist, ctid);
364                         }
365                 }
366
367                 /*
368                  * Generate appropriate target list for subplan; may be different
369                  * from tlist if grouping or aggregation is needed.
370                  */
371                 sub_tlist = make_subplanTargetList(parse, tlist, &groupColIdx);
372
373                 /*
374                  * Calculate pathkeys that represent grouping/ordering
375                  * requirements
376                  */
377                 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
378                                                                                                            tlist);
379                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
380                                                                                                           tlist);
381
382                 /*
383                  * Figure out whether we need a sorted result from query_planner.
384                  *
385                  * If we have a GROUP BY clause, then we want a result sorted
386                  * properly for grouping.  Otherwise, if there is an ORDER BY
387                  * clause, we want to sort by the ORDER BY clause.      (Note: if we
388                  * have both, and ORDER BY is a superset of GROUP BY, it would be
389                  * tempting to request sort by ORDER BY --- but that might just
390                  * leave us failing to exploit an available sort order at all.
391                  * Needs more thought...)
392                  */
393                 if (parse->groupClause)
394                         parse->query_pathkeys = group_pathkeys;
395                 else if (parse->sortClause)
396                         parse->query_pathkeys = sort_pathkeys;
397                 else
398                         parse->query_pathkeys = NIL;
399
400                 /*
401                  * Figure out whether we expect to retrieve all the tuples that
402                  * the plan can generate, or to stop early due to a LIMIT or other
403                  * factors.  If the caller passed a value >= 0, believe that
404                  * value, else do our own examination of the query context.
405                  */
406                 if (tuple_fraction < 0.0)
407                 {
408                         /* Initial assumption is we need all the tuples */
409                         tuple_fraction = 0.0;
410
411                         /*
412                          * Check for a LIMIT clause.
413                          */
414                         if (parse->limitCount != NULL)
415                         {
416                                 if (IsA(parse->limitCount, Const))
417                                 {
418                                         Const      *limitc = (Const *) parse->limitCount;
419                                         int                     count = (int) (limitc->constvalue);
420
421                                         /*
422                                          * The constant can legally be either 0 ("ALL") or a
423                                          * positive integer.  If it is not ALL, we also need
424                                          * to consider the OFFSET part of LIMIT.
425                                          */
426                                         if (count > 0)
427                                         {
428                                                 tuple_fraction = (double) count;
429                                                 if (parse->limitOffset != NULL)
430                                                 {
431                                                         if (IsA(parse->limitOffset, Const))
432                                                         {
433                                                                 int                     offset;
434
435                                                                 limitc = (Const *) parse->limitOffset;
436                                                                 offset = (int) (limitc->constvalue);
437                                                                 if (offset > 0)
438                                                                         tuple_fraction += (double) offset;
439                                                         }
440                                                         else
441                                                         {
442                                                                 /* It's a PARAM ... punt ... */
443                                                                 tuple_fraction = 0.10;
444                                                         }
445                                                 }
446                                         }
447                                 }
448                                 else
449                                 {
450
451                                         /*
452                                          * COUNT is a PARAM ... don't know exactly what the
453                                          * limit will be, but for lack of a better idea assume
454                                          * 10% of the plan's result is wanted.
455                                          */
456                                         tuple_fraction = 0.10;
457                                 }
458                         }
459
460                         /*
461                          * Check for a retrieve-into-portal, ie DECLARE CURSOR.
462                          *
463                          * We have no real idea how many tuples the user will ultimately
464                          * FETCH from a cursor, but it seems a good bet that he
465                          * doesn't want 'em all.  Optimize for 10% retrieval (you
466                          * gotta better number?)
467                          */
468                         if (parse->isPortal)
469                                 tuple_fraction = 0.10;
470                 }
471
472                 /*
473                  * Adjust tuple_fraction if we see that we are going to apply
474                  * grouping/aggregation/etc.  This is not overridable by the
475                  * caller, since it reflects plan actions that this routine will
476                  * certainly take, not assumptions about context.
477                  */
478                 if (parse->groupClause)
479                 {
480
481                         /*
482                          * In GROUP BY mode, we have the little problem that we don't
483                          * really know how many input tuples will be needed to make a
484                          * group, so we can't translate an output LIMIT count into an
485                          * input count.  For lack of a better idea, assume 25% of the
486                          * input data will be processed if there is any output limit.
487                          * However, if the caller gave us a fraction rather than an
488                          * absolute count, we can keep using that fraction (which
489                          * amounts to assuming that all the groups are about the same
490                          * size).
491                          */
492                         if (tuple_fraction >= 1.0)
493                                 tuple_fraction = 0.25;
494
495                         /*
496                          * If both GROUP BY and ORDER BY are specified, we will need
497                          * two levels of sort --- and, therefore, certainly need to
498                          * read all the input tuples --- unless ORDER BY is a subset
499                          * of GROUP BY.  (Although we are comparing non-canonicalized
500                          * pathkeys here, it should be OK since they will both contain
501                          * only single-element sublists at this point.  See
502                          * pathkeys.c.)
503                          */
504                         if (parse->groupClause && parse->sortClause &&
505                                 !pathkeys_contained_in(sort_pathkeys, group_pathkeys))
506                                 tuple_fraction = 0.0;
507                 }
508                 else if (parse->hasAggs)
509                 {
510
511                         /*
512                          * Ungrouped aggregate will certainly want all the input
513                          * tuples.
514                          */
515                         tuple_fraction = 0.0;
516                 }
517                 else if (parse->distinctClause)
518                 {
519
520                         /*
521                          * SELECT DISTINCT, like GROUP, will absorb an unpredictable
522                          * number of input tuples per output tuple.  Handle the same
523                          * way.
524                          */
525                         if (tuple_fraction >= 1.0)
526                                 tuple_fraction = 0.25;
527                 }
528
529                 /* Generate the (sub) plan */
530                 result_plan = query_planner(parse,
531                                                                         sub_tlist,
532                                                                         (List *) parse->qual,
533                                                                         tuple_fraction);
534
535                 /*
536                  * query_planner returns actual sort order (which is not
537                  * necessarily what we requested) in query_pathkeys.
538                  */
539                 current_pathkeys = parse->query_pathkeys;
540         }
541
542         /* query_planner returns NULL if it thinks plan is bogus */
543         if (!result_plan)
544                 elog(ERROR, "union_planner: failed to create plan");
545
546         /*
547          * We couldn't canonicalize group_pathkeys and sort_pathkeys before
548          * running query_planner(), so do it now.
549          */
550         group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
551         sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
552
553         /*
554          * If we have a GROUP BY clause, insert a group node (plus the
555          * appropriate sort node, if necessary).
556          */
557         if (parse->groupClause)
558         {
559                 bool            tuplePerGroup;
560                 List       *group_tlist;
561                 bool            is_sorted;
562
563                 /*
564                  * Decide whether how many tuples per group the Group node needs
565                  * to return. (Needs only one tuple per group if no aggregate is
566                  * present. Otherwise, need every tuple from the group to do the
567                  * aggregation.)  Note tuplePerGroup is named backwards :-(
568                  */
569                 tuplePerGroup = parse->hasAggs;
570
571                 /*
572                  * If there are aggregates then the Group node should just return
573                  * the same set of vars as the subplan did (but we can exclude any
574                  * GROUP BY expressions).  If there are no aggregates then the
575                  * Group node had better compute the final tlist.
576                  */
577                 if (parse->hasAggs)
578                         group_tlist = flatten_tlist(result_plan->targetlist);
579                 else
580                         group_tlist = tlist;
581
582                 /*
583                  * Figure out whether the path result is already ordered the way
584                  * we need it --- if so, no need for an explicit sort step.
585                  */
586                 if (pathkeys_contained_in(group_pathkeys, current_pathkeys))
587                 {
588                         is_sorted = true;       /* no sort needed now */
589                         /* current_pathkeys remains unchanged */
590                 }
591                 else
592                 {
593
594                         /*
595                          * We will need to do an explicit sort by the GROUP BY clause.
596                          * make_groupplan will do the work, but set current_pathkeys
597                          * to indicate the resulting order.
598                          */
599                         is_sorted = false;
600                         current_pathkeys = group_pathkeys;
601                 }
602
603                 result_plan = make_groupplan(group_tlist,
604                                                                          tuplePerGroup,
605                                                                          parse->groupClause,
606                                                                          groupColIdx,
607                                                                          is_sorted,
608                                                                          result_plan);
609         }
610
611         /*
612          * If aggregate is present, insert the Agg node
613          *
614          * HAVING clause, if any, becomes qual of the Agg node
615          */
616         if (parse->hasAggs)
617         {
618                 result_plan = (Plan *) make_agg(tlist,
619                                                                                 (List *) parse->havingQual,
620                                                                                 result_plan);
621                 /* Note: Agg does not affect any existing sort order of the tuples */
622         }
623
624         /*
625          * If we were not able to make the plan come out in the right order,
626          * add an explicit sort step.
627          */
628         if (parse->sortClause)
629         {
630                 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
631                         result_plan = make_sortplan(tlist, parse->sortClause, result_plan);
632         }
633
634         /*
635          * Finally, if there is a DISTINCT clause, add the UNIQUE node.
636          */
637         if (parse->distinctClause)
638         {
639                 result_plan = (Plan *) make_unique(tlist, result_plan,
640                                                                                    parse->distinctClause);
641         }
642
643         return result_plan;
644 }
645
646 /*---------------
647  * make_subplanTargetList
648  *        Generate appropriate target list when grouping is required.
649  *
650  * When union_planner inserts Aggregate and/or Group plan nodes above
651  * the result of query_planner, we typically want to pass a different
652  * target list to query_planner than the outer plan nodes should have.
653  * This routine generates the correct target list for the subplan.
654  *
655  * The initial target list passed from the parser already contains entries
656  * for all ORDER BY and GROUP BY expressions, but it will not have entries
657  * for variables used only in HAVING clauses; so we need to add those
658  * variables to the subplan target list.  Also, if we are doing either
659  * grouping or aggregation, we flatten all expressions except GROUP BY items
660  * into their component variables; the other expressions will be computed by
661  * the inserted nodes rather than by the subplan.  For example,
662  * given a query like
663  *              SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
664  * we want to pass this targetlist to the subplan:
665  *              a,b,c,d,a+b
666  * where the a+b target will be used by the Sort/Group steps, and the
667  * other targets will be used for computing the final results.  (In the
668  * above example we could theoretically suppress the a and b targets and
669  * use only a+b, but it's not really worth the trouble.)
670  *
671  * 'parse' is the query being processed.
672  * 'tlist' is the query's target list.
673  * 'groupColIdx' receives an array of column numbers for the GROUP BY
674  * expressions (if there are any) in the subplan's target list.
675  *
676  * The result is the targetlist to be passed to the subplan.
677  *---------------
678  */
679 static List *
680 make_subplanTargetList(Query *parse,
681                                            List *tlist,
682                                            AttrNumber **groupColIdx)
683 {
684         List       *sub_tlist;
685         List       *extravars;
686         int                     numCols;
687
688         *groupColIdx = NULL;
689
690         /*
691          * If we're not grouping or aggregating, nothing to do here;
692          * query_planner should receive the unmodified target list.
693          */
694         if (!parse->hasAggs && !parse->groupClause && !parse->havingQual)
695                 return tlist;
696
697         /*
698          * Otherwise, start with a "flattened" tlist (having just the vars
699          * mentioned in the targetlist and HAVING qual --- but not upper-
700          * level Vars; they will be replaced by Params later on).
701          */
702         sub_tlist = flatten_tlist(tlist);
703         extravars = pull_var_clause(parse->havingQual, false);
704         sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
705         freeList(extravars);
706
707         /*
708          * If grouping, create sub_tlist entries for all GROUP BY expressions
709          * (GROUP BY items that are simple Vars should be in the list
710          * already), and make an array showing where the group columns are in
711          * the sub_tlist.
712          */
713         numCols = length(parse->groupClause);
714         if (numCols > 0)
715         {
716                 int                     keyno = 0;
717                 AttrNumber *grpColIdx;
718                 List       *gl;
719
720                 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
721                 *groupColIdx = grpColIdx;
722
723                 foreach(gl, parse->groupClause)
724                 {
725                         GroupClause *grpcl = (GroupClause *) lfirst(gl);
726                         Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
727                         TargetEntry *te = NULL;
728                         List       *sl;
729
730                         /* Find or make a matching sub_tlist entry */
731                         foreach(sl, sub_tlist)
732                         {
733                                 te = (TargetEntry *) lfirst(sl);
734                                 if (equal(groupexpr, te->expr))
735                                         break;
736                         }
737                         if (!sl)
738                         {
739                                 te = makeTargetEntry(makeResdom(length(sub_tlist) + 1,
740                                                                                                 exprType(groupexpr),
741                                                                                                 exprTypmod(groupexpr),
742                                                                                                 NULL,
743                                                                                                 (Index) 0,
744                                                                                                 (Oid) 0,
745                                                                                                 false),
746                                                                          groupexpr);
747                                 sub_tlist = lappend(sub_tlist, te);
748                         }
749
750                         /* and save its resno */
751                         grpColIdx[keyno++] = te->resdom->resno;
752                 }
753         }
754
755         return sub_tlist;
756 }
757
758 /*
759  * make_groupplan
760  *              Add a Group node for GROUP BY processing.
761  *              If we couldn't make the subplan produce presorted output for grouping,
762  *              first add an explicit Sort node.
763  */
764 static Plan *
765 make_groupplan(List *group_tlist,
766                            bool tuplePerGroup,
767                            List *groupClause,
768                            AttrNumber *grpColIdx,
769                            bool is_presorted,
770                            Plan *subplan)
771 {
772         int                     numCols = length(groupClause);
773
774         if (!is_presorted)
775         {
776
777                 /*
778                  * The Sort node always just takes a copy of the subplan's tlist
779                  * plus ordering information.  (This might seem inefficient if the
780                  * subplan contains complex GROUP BY expressions, but in fact Sort
781                  * does not evaluate its targetlist --- it only outputs the same
782                  * tuples in a new order.  So the expressions we might be copying
783                  * are just dummies with no extra execution cost.)
784                  */
785                 List       *sort_tlist = new_unsorted_tlist(subplan->targetlist);
786                 int                     keyno = 0;
787                 List       *gl;
788
789                 foreach(gl, groupClause)
790                 {
791                         GroupClause *grpcl = (GroupClause *) lfirst(gl);
792                         TargetEntry *te = nth(grpColIdx[keyno] - 1, sort_tlist);
793                         Resdom     *resdom = te->resdom;
794
795                         /*
796                          * Check for the possibility of duplicate group-by clauses ---
797                          * the parser should have removed 'em, but the Sort executor
798                          * will get terribly confused if any get through!
799                          */
800                         if (resdom->reskey == 0)
801                         {
802                                 /* OK, insert the ordering info needed by the executor. */
803                                 resdom->reskey = ++keyno;
804                                 resdom->reskeyop = get_opcode(grpcl->sortop);
805                         }
806                 }
807
808                 subplan = (Plan *) make_sort(sort_tlist,
809                                                                          _NONAME_RELATION_ID_,
810                                                                          subplan,
811                                                                          keyno);
812         }
813
814         return (Plan *) make_group(group_tlist, tuplePerGroup, numCols,
815                                                            grpColIdx, subplan);
816 }
817
818 /*
819  * make_sortplan
820  *        Add a Sort node to implement an explicit ORDER BY clause.
821  */
822 static Plan *
823 make_sortplan(List *tlist, List *sortcls, Plan *plannode)
824 {
825         List       *temp_tlist;
826         List       *i;
827         int                     keyno = 0;
828
829         /*
830          * First make a copy of the tlist so that we don't corrupt the
831          * original.
832          */
833
834         temp_tlist = new_unsorted_tlist(tlist);
835
836         foreach(i, sortcls)
837         {
838                 SortClause *sortcl = (SortClause *) lfirst(i);
839                 TargetEntry *tle = get_sortgroupclause_tle(sortcl, temp_tlist);
840                 Resdom     *resdom = tle->resdom;
841
842                 /*
843                  * Check for the possibility of duplicate order-by clauses --- the
844                  * parser should have removed 'em, but the executor will get
845                  * terribly confused if any get through!
846                  */
847                 if (resdom->reskey == 0)
848                 {
849                         /* OK, insert the ordering info needed by the executor. */
850                         resdom->reskey = ++keyno;
851                         resdom->reskeyop = get_opcode(sortcl->sortop);
852                 }
853         }
854
855         return (Plan *) make_sort(temp_tlist,
856                                                           _NONAME_RELATION_ID_,
857                                                           plannode,
858                                                           keyno);
859 }
860
861 /*
862  * pg_checkretval() -- check return value of a list of sql parse
863  *                                              trees.
864  *
865  * The return value of a sql function is the value returned by
866  * the final query in the function.  We do some ad-hoc define-time
867  * type checking here to be sure that the user is returning the
868  * type he claims.
869  *
870  * XXX Why is this function in this module?
871  */
872 void
873 pg_checkretval(Oid rettype, List *queryTreeList)
874 {
875         Query      *parse;
876         List       *tlist;
877         List       *rt;
878         int                     cmd;
879         Type            typ;
880         Resdom     *resnode;
881         Relation        reln;
882         Oid                     relid;
883         int                     relnatts;
884         int                     i;
885
886         /* find the final query */
887         parse = (Query *) nth(length(queryTreeList) - 1, queryTreeList);
888
889         /*
890          * test 1:      if the last query is a utility invocation, then there had
891          * better not be a return value declared.
892          */
893         if (parse->commandType == CMD_UTILITY)
894         {
895                 if (rettype == InvalidOid)
896                         return;
897                 else
898                         elog(ERROR, "return type mismatch in function decl: final query is a catalog utility");
899         }
900
901         /* okay, it's an ordinary query */
902         tlist = parse->targetList;
903         rt = parse->rtable;
904         cmd = parse->commandType;
905
906         /*
907          * test 2:      if the function is declared to return no value, then the
908          * final query had better not be a retrieve.
909          */
910         if (rettype == InvalidOid)
911         {
912                 if (cmd == CMD_SELECT)
913                         elog(ERROR,
914                                  "function declared with no return type, but final query is a retrieve");
915                 else
916                         return;
917         }
918
919         /* by here, the function is declared to return some type */
920         if ((typ = typeidType(rettype)) == NULL)
921                 elog(ERROR, "can't find return type %u for function\n", rettype);
922
923         /*
924          * test 3:      if the function is declared to return a value, then the
925          * final query had better be a retrieve.
926          */
927         if (cmd != CMD_SELECT)
928                 elog(ERROR, "function declared to return type %s, but final query is not a retrieve", typeTypeName(typ));
929
930         /*
931          * test 4:      for base type returns, the target list should have exactly
932          * one entry, and its type should agree with what the user declared.
933          */
934
935         if (typeTypeRelid(typ) == InvalidOid)
936         {
937                 if (ExecTargetListLength(tlist) > 1)
938                         elog(ERROR, "function declared to return %s returns multiple values in final retrieve", typeTypeName(typ));
939
940                 resnode = (Resdom *) ((TargetEntry *) lfirst(tlist))->resdom;
941                 if (resnode->restype != rettype)
942                         elog(ERROR, "return type mismatch in function: declared to return %s, returns %s", typeTypeName(typ), typeidTypeName(resnode->restype));
943
944                 /* by here, base return types match */
945                 return;
946         }
947
948         /*
949          * If the target list is of length 1, and the type of the varnode in
950          * the target list is the same as the declared return type, this is
951          * okay.  This can happen, for example, where the body of the function
952          * is 'retrieve (x = func2())', where func2 has the same return type
953          * as the function that's calling it.
954          */
955         if (ExecTargetListLength(tlist) == 1)
956         {
957                 resnode = (Resdom *) ((TargetEntry *) lfirst(tlist))->resdom;
958                 if (resnode->restype == rettype)
959                         return;
960         }
961
962         /*
963          * By here, the procedure returns a (set of) tuples.  This part of the
964          * typechecking is a hack.      We look up the relation that is the
965          * declared return type, and be sure that attributes 1 .. n in the
966          * target list match the declared types.
967          */
968         reln = heap_open(typeTypeRelid(typ), AccessShareLock);
969         relid = reln->rd_id;
970         relnatts = reln->rd_rel->relnatts;
971
972         if (ExecTargetListLength(tlist) != relnatts)
973                 elog(ERROR, "function declared to return type %s does not retrieve (%s.*)", typeTypeName(typ), typeTypeName(typ));
974
975         /* expect attributes 1 .. n in order */
976         for (i = 1; i <= relnatts; i++)
977         {
978                 TargetEntry *tle = lfirst(tlist);
979                 Node       *thenode = tle->expr;
980                 Oid                     tletype = exprType(thenode);
981
982                 if (tletype != reln->rd_att->attrs[i - 1]->atttypid)
983                         elog(ERROR, "function declared to return type %s does not retrieve (%s.all)", typeTypeName(typ), typeTypeName(typ));
984                 tlist = lnext(tlist);
985         }
986
987         heap_close(reln, AccessShareLock);
988 }