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