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