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