]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/planner.c
7c73a878242b9dff5ae5d6e8671d09a26e4d7549
[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.97 2000/12/06 23:55:17 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.  (Although we are comparing non-canonicalized
935                          * pathkeys here, it should be OK since they will both contain
936                          * only single-element sublists at this point.  See
937                          * pathkeys.c.)
938                          */
939                         if (parse->groupClause && parse->sortClause &&
940                                 !pathkeys_contained_in(sort_pathkeys, group_pathkeys))
941                                 tuple_fraction = 0.0;
942                 }
943                 else if (parse->hasAggs)
944                 {
945
946                         /*
947                          * Ungrouped aggregate will certainly want all the input
948                          * tuples.
949                          */
950                         tuple_fraction = 0.0;
951                 }
952                 else if (parse->distinctClause)
953                 {
954
955                         /*
956                          * SELECT DISTINCT, like GROUP, will absorb an unpredictable
957                          * number of input tuples per output tuple.  Handle the same
958                          * way.
959                          */
960                         if (tuple_fraction >= 1.0)
961                                 tuple_fraction = 0.25;
962                 }
963
964                 /* Generate the basic plan for this Query */
965                 result_plan = query_planner(parse,
966                                                                         sub_tlist,
967                                                                         tuple_fraction);
968
969                 /*
970                  * query_planner returns actual sort order (which is not
971                  * necessarily what we requested) in query_pathkeys.
972                  */
973                 current_pathkeys = parse->query_pathkeys;
974         }
975
976         /*
977          * We couldn't canonicalize group_pathkeys and sort_pathkeys before
978          * running query_planner(), so do it now.
979          */
980         group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
981         sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
982
983         /*
984          * If we have a GROUP BY clause, insert a group node (plus the
985          * appropriate sort node, if necessary).
986          */
987         if (parse->groupClause)
988         {
989                 bool            tuplePerGroup;
990                 List       *group_tlist;
991                 bool            is_sorted;
992
993                 /*
994                  * Decide whether how many tuples per group the Group node needs
995                  * to return. (Needs only one tuple per group if no aggregate is
996                  * present. Otherwise, need every tuple from the group to do the
997                  * aggregation.)  Note tuplePerGroup is named backwards :-(
998                  */
999                 tuplePerGroup = parse->hasAggs;
1000
1001                 /*
1002                  * If there are aggregates then the Group node should just return
1003                  * the same set of vars as the subplan did (but we can exclude any
1004                  * GROUP BY expressions).  If there are no aggregates then the
1005                  * Group node had better compute the final tlist.
1006                  */
1007                 if (parse->hasAggs)
1008                         group_tlist = flatten_tlist(result_plan->targetlist);
1009                 else
1010                         group_tlist = tlist;
1011
1012                 /*
1013                  * Figure out whether the path result is already ordered the way
1014                  * we need it --- if so, no need for an explicit sort step.
1015                  */
1016                 if (pathkeys_contained_in(group_pathkeys, current_pathkeys))
1017                 {
1018                         is_sorted = true;       /* no sort needed now */
1019                         /* current_pathkeys remains unchanged */
1020                 }
1021                 else
1022                 {
1023
1024                         /*
1025                          * We will need to do an explicit sort by the GROUP BY clause.
1026                          * make_groupplan will do the work, but set current_pathkeys
1027                          * to indicate the resulting order.
1028                          */
1029                         is_sorted = false;
1030                         current_pathkeys = group_pathkeys;
1031                 }
1032
1033                 result_plan = make_groupplan(group_tlist,
1034                                                                          tuplePerGroup,
1035                                                                          parse->groupClause,
1036                                                                          groupColIdx,
1037                                                                          is_sorted,
1038                                                                          result_plan);
1039         }
1040
1041         /*
1042          * If aggregate is present, insert the Agg node
1043          *
1044          * HAVING clause, if any, becomes qual of the Agg node
1045          */
1046         if (parse->hasAggs)
1047         {
1048                 result_plan = (Plan *) make_agg(tlist,
1049                                                                                 (List *) parse->havingQual,
1050                                                                                 result_plan);
1051                 /* Note: Agg does not affect any existing sort order of the tuples */
1052         }
1053
1054         /*
1055          * If we were not able to make the plan come out in the right order,
1056          * add an explicit sort step.
1057          */
1058         if (parse->sortClause)
1059         {
1060                 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1061                         result_plan = make_sortplan(tlist, result_plan,
1062                                                                                 parse->sortClause);
1063         }
1064
1065         /*
1066          * If there is a DISTINCT clause, add the UNIQUE node.
1067          */
1068         if (parse->distinctClause)
1069         {
1070                 result_plan = (Plan *) make_unique(tlist, result_plan,
1071                                                                                    parse->distinctClause);
1072         }
1073
1074         /*
1075          * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1076          */
1077         if (parse->limitOffset || parse->limitCount)
1078         {
1079                 result_plan = (Plan *) make_limit(tlist, result_plan,
1080                                                                                   parse->limitOffset,
1081                                                                                   parse->limitCount);
1082         }
1083
1084         return result_plan;
1085 }
1086
1087 /*---------------
1088  * make_subplanTargetList
1089  *        Generate appropriate target list when grouping is required.
1090  *
1091  * When grouping_planner inserts Aggregate and/or Group plan nodes above
1092  * the result of query_planner, we typically want to pass a different
1093  * target list to query_planner than the outer plan nodes should have.
1094  * This routine generates the correct target list for the subplan.
1095  *
1096  * The initial target list passed from the parser already contains entries
1097  * for all ORDER BY and GROUP BY expressions, but it will not have entries
1098  * for variables used only in HAVING clauses; so we need to add those
1099  * variables to the subplan target list.  Also, if we are doing either
1100  * grouping or aggregation, we flatten all expressions except GROUP BY items
1101  * into their component variables; the other expressions will be computed by
1102  * the inserted nodes rather than by the subplan.  For example,
1103  * given a query like
1104  *              SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1105  * we want to pass this targetlist to the subplan:
1106  *              a,b,c,d,a+b
1107  * where the a+b target will be used by the Sort/Group steps, and the
1108  * other targets will be used for computing the final results.  (In the
1109  * above example we could theoretically suppress the a and b targets and
1110  * use only a+b, but it's not really worth the trouble.)
1111  *
1112  * 'parse' is the query being processed.
1113  * 'tlist' is the query's target list.
1114  * 'groupColIdx' receives an array of column numbers for the GROUP BY
1115  * expressions (if there are any) in the subplan's target list.
1116  *
1117  * The result is the targetlist to be passed to the subplan.
1118  *---------------
1119  */
1120 static List *
1121 make_subplanTargetList(Query *parse,
1122                                            List *tlist,
1123                                            AttrNumber **groupColIdx)
1124 {
1125         List       *sub_tlist;
1126         List       *extravars;
1127         int                     numCols;
1128
1129         *groupColIdx = NULL;
1130
1131         /*
1132          * If we're not grouping or aggregating, nothing to do here;
1133          * query_planner should receive the unmodified target list.
1134          */
1135         if (!parse->hasAggs && !parse->groupClause && !parse->havingQual)
1136                 return tlist;
1137
1138         /*
1139          * Otherwise, start with a "flattened" tlist (having just the vars
1140          * mentioned in the targetlist and HAVING qual --- but not upper-
1141          * level Vars; they will be replaced by Params later on).
1142          */
1143         sub_tlist = flatten_tlist(tlist);
1144         extravars = pull_var_clause(parse->havingQual, false);
1145         sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1146         freeList(extravars);
1147
1148         /*
1149          * If grouping, create sub_tlist entries for all GROUP BY expressions
1150          * (GROUP BY items that are simple Vars should be in the list
1151          * already), and make an array showing where the group columns are in
1152          * the sub_tlist.
1153          */
1154         numCols = length(parse->groupClause);
1155         if (numCols > 0)
1156         {
1157                 int                     keyno = 0;
1158                 AttrNumber *grpColIdx;
1159                 List       *gl;
1160
1161                 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1162                 *groupColIdx = grpColIdx;
1163
1164                 foreach(gl, parse->groupClause)
1165                 {
1166                         GroupClause *grpcl = (GroupClause *) lfirst(gl);
1167                         Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1168                         TargetEntry *te = NULL;
1169                         List       *sl;
1170
1171                         /* Find or make a matching sub_tlist entry */
1172                         foreach(sl, sub_tlist)
1173                         {
1174                                 te = (TargetEntry *) lfirst(sl);
1175                                 if (equal(groupexpr, te->expr))
1176                                         break;
1177                         }
1178                         if (!sl)
1179                         {
1180                                 te = makeTargetEntry(makeResdom(length(sub_tlist) + 1,
1181                                                                                                 exprType(groupexpr),
1182                                                                                                 exprTypmod(groupexpr),
1183                                                                                                 NULL,
1184                                                                                                 false),
1185                                                                          groupexpr);
1186                                 sub_tlist = lappend(sub_tlist, te);
1187                         }
1188
1189                         /* and save its resno */
1190                         grpColIdx[keyno++] = te->resdom->resno;
1191                 }
1192         }
1193
1194         return sub_tlist;
1195 }
1196
1197 /*
1198  * make_groupplan
1199  *              Add a Group node for GROUP BY processing.
1200  *              If we couldn't make the subplan produce presorted output for grouping,
1201  *              first add an explicit Sort node.
1202  */
1203 static Plan *
1204 make_groupplan(List *group_tlist,
1205                            bool tuplePerGroup,
1206                            List *groupClause,
1207                            AttrNumber *grpColIdx,
1208                            bool is_presorted,
1209                            Plan *subplan)
1210 {
1211         int                     numCols = length(groupClause);
1212
1213         if (!is_presorted)
1214         {
1215
1216                 /*
1217                  * The Sort node always just takes a copy of the subplan's tlist
1218                  * plus ordering information.  (This might seem inefficient if the
1219                  * subplan contains complex GROUP BY expressions, but in fact Sort
1220                  * does not evaluate its targetlist --- it only outputs the same
1221                  * tuples in a new order.  So the expressions we might be copying
1222                  * are just dummies with no extra execution cost.)
1223                  */
1224                 List       *sort_tlist = new_unsorted_tlist(subplan->targetlist);
1225                 int                     keyno = 0;
1226                 List       *gl;
1227
1228                 foreach(gl, groupClause)
1229                 {
1230                         GroupClause *grpcl = (GroupClause *) lfirst(gl);
1231                         TargetEntry *te = nth(grpColIdx[keyno] - 1, sort_tlist);
1232                         Resdom     *resdom = te->resdom;
1233
1234                         /*
1235                          * Check for the possibility of duplicate group-by clauses ---
1236                          * the parser should have removed 'em, but the Sort executor
1237                          * will get terribly confused if any get through!
1238                          */
1239                         if (resdom->reskey == 0)
1240                         {
1241                                 /* OK, insert the ordering info needed by the executor. */
1242                                 resdom->reskey = ++keyno;
1243                                 resdom->reskeyop = get_opcode(grpcl->sortop);
1244                         }
1245                 }
1246
1247                 Assert(keyno > 0);
1248
1249                 subplan = (Plan *) make_sort(sort_tlist, subplan, keyno);
1250         }
1251
1252         return (Plan *) make_group(group_tlist, tuplePerGroup, numCols,
1253                                                            grpColIdx, subplan);
1254 }
1255
1256 /*
1257  * make_sortplan
1258  *        Add a Sort node to implement an explicit ORDER BY clause.
1259  */
1260 Plan *
1261 make_sortplan(List *tlist, Plan *plannode, List *sortcls)
1262 {
1263         List       *sort_tlist;
1264         List       *i;
1265         int                     keyno = 0;
1266
1267         /*
1268          * First make a copy of the tlist so that we don't corrupt the
1269          * original.
1270          */
1271         sort_tlist = new_unsorted_tlist(tlist);
1272
1273         foreach(i, sortcls)
1274         {
1275                 SortClause *sortcl = (SortClause *) lfirst(i);
1276                 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sort_tlist);
1277                 Resdom     *resdom = tle->resdom;
1278
1279                 /*
1280                  * Check for the possibility of duplicate order-by clauses --- the
1281                  * parser should have removed 'em, but the executor will get
1282                  * terribly confused if any get through!
1283                  */
1284                 if (resdom->reskey == 0)
1285                 {
1286                         /* OK, insert the ordering info needed by the executor. */
1287                         resdom->reskey = ++keyno;
1288                         resdom->reskeyop = get_opcode(sortcl->sortop);
1289                 }
1290         }
1291
1292         Assert(keyno > 0);
1293
1294         return (Plan *) make_sort(sort_tlist, plannode, keyno);
1295 }
1296
1297 /*
1298  * postprocess_setop_tlist
1299  *        Fix up targetlist returned by plan_set_operations().
1300  *
1301  * We need to transpose sort key info from the orig_tlist into new_tlist.
1302  * NOTE: this would not be good enough if we supported resjunk sort keys
1303  * for results of set operations --- then, we'd need to project a whole
1304  * new tlist to evaluate the resjunk columns.  For now, just elog if we
1305  * find any resjunk columns in orig_tlist.
1306  */
1307 static List *
1308 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1309 {
1310         List       *l;
1311
1312         foreach(l, new_tlist)
1313         {
1314                 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1315                 TargetEntry *orig_tle;
1316
1317                 /* ignore resjunk columns in setop result */
1318                 if (new_tle->resdom->resjunk)
1319                         continue;
1320
1321                 Assert(orig_tlist != NIL);
1322                 orig_tle = (TargetEntry *) lfirst(orig_tlist);
1323                 orig_tlist = lnext(orig_tlist);
1324                 if (orig_tle->resdom->resjunk)
1325                         elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");
1326                 Assert(new_tle->resdom->resno == orig_tle->resdom->resno);
1327                 Assert(new_tle->resdom->restype == orig_tle->resdom->restype);
1328                 new_tle->resdom->ressortgroupref = orig_tle->resdom->ressortgroupref;
1329         }
1330         if (orig_tlist != NIL)
1331                 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");
1332         return new_tlist;
1333 }