]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/planner.c
Reconsider mechanism for marking sub-selects that are at top level of
[postgresql] / src / backend / optimizer / plan / planner.c
1 /*-------------------------------------------------------------------------
2  *
3  * planner.c
4  *        The query optimizer external interface.
5  *
6  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
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.138 2003/01/13 18:10:53 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include <limits.h>
19
20 #include "catalog/pg_operator.h"
21 #include "catalog/pg_type.h"
22 #include "miscadmin.h"
23 #include "nodes/makefuncs.h"
24 #ifdef OPTIMIZER_DEBUG
25 #include "nodes/print.h"
26 #endif
27 #include "optimizer/clauses.h"
28 #include "optimizer/cost.h"
29 #include "optimizer/pathnode.h"
30 #include "optimizer/paths.h"
31 #include "optimizer/planmain.h"
32 #include "optimizer/planner.h"
33 #include "optimizer/prep.h"
34 #include "optimizer/subselect.h"
35 #include "optimizer/tlist.h"
36 #include "optimizer/var.h"
37 #include "parser/analyze.h"
38 #include "parser/parsetree.h"
39 #include "parser/parse_expr.h"
40 #include "parser/parse_oper.h"
41 #include "rewrite/rewriteManip.h"
42 #include "utils/lsyscache.h"
43 #include "utils/selfuncs.h"
44 #include "utils/syscache.h"
45
46
47 /* Expression kind codes for preprocess_expression */
48 #define EXPRKIND_TARGET 0
49 #define EXPRKIND_WHERE  1
50 #define EXPRKIND_HAVING 2
51
52
53 static Node *pull_up_subqueries(Query *parse, Node *jtnode,
54                                    bool below_outer_join);
55 static bool is_simple_subquery(Query *subquery);
56 static bool has_nullable_targetlist(Query *subquery);
57 static void resolvenew_in_jointree(Node *jtnode, int varno, List *subtlist);
58 static Node *preprocess_jointree(Query *parse, Node *jtnode);
59 static Node *preprocess_expression(Query *parse, Node *expr, int kind);
60 static void preprocess_qual_conditions(Query *parse, Node *jtnode);
61 static Plan *inheritance_planner(Query *parse, List *inheritlist);
62 static Plan *grouping_planner(Query *parse, double tuple_fraction);
63 static bool hash_safe_grouping(Query *parse);
64 static List *make_subplanTargetList(Query *parse, List *tlist,
65                                            AttrNumber **groupColIdx);
66 static Plan *make_groupsortplan(Query *parse,
67                                                                 List *groupClause,
68                                                                 AttrNumber *grpColIdx,
69                                                                 Plan *subplan);
70 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
71
72
73 /*****************************************************************************
74  *
75  *         Query optimizer entry point
76  *
77  *****************************************************************************/
78 Plan *
79 planner(Query *parse)
80 {
81         Plan       *result_plan;
82         Index           save_PlannerQueryLevel;
83         List       *save_PlannerParamVar;
84
85         /*
86          * The planner can be called recursively (an example is when
87          * eval_const_expressions tries to pre-evaluate an SQL function). So,
88          * these global state variables must be saved and restored.
89          *
90          * These vars cannot be moved into the Query structure since their whole
91          * purpose is communication across multiple sub-Queries.
92          *
93          * Note we do NOT save and restore PlannerPlanId: it exists to assign
94          * unique IDs to SubPlan nodes, and we want those IDs to be unique for
95          * the life of a backend.  Also, PlannerInitPlan is saved/restored in
96          * subquery_planner, not here.
97          */
98         save_PlannerQueryLevel = PlannerQueryLevel;
99         save_PlannerParamVar = PlannerParamVar;
100
101         /* Initialize state for handling outer-level references and params */
102         PlannerQueryLevel = 0;          /* will be 1 in top-level subquery_planner */
103         PlannerParamVar = NIL;
104
105         /* primary planning entry point (may recurse for subqueries) */
106         result_plan = subquery_planner(parse, -1.0 /* default case */ );
107
108         Assert(PlannerQueryLevel == 0);
109
110         /* executor wants to know total number of Params used overall */
111         result_plan->nParamExec = length(PlannerParamVar);
112
113         /* final cleanup of the plan */
114         set_plan_references(result_plan, parse->rtable);
115
116         /* restore state for outer planner, if any */
117         PlannerQueryLevel = save_PlannerQueryLevel;
118         PlannerParamVar = save_PlannerParamVar;
119
120         return result_plan;
121 }
122
123
124 /*--------------------
125  * subquery_planner
126  *        Invokes the planner on a subquery.  We recurse to here for each
127  *        sub-SELECT found in the query tree.
128  *
129  * parse is the querytree produced by the parser & rewriter.
130  * tuple_fraction is the fraction of tuples we expect will be retrieved.
131  * tuple_fraction is interpreted as explained for grouping_planner, below.
132  *
133  * Basically, this routine does the stuff that should only be done once
134  * per Query object.  It then calls grouping_planner.  At one time,
135  * grouping_planner could be invoked recursively on the same Query object;
136  * that's not currently true, but we keep the separation between the two
137  * routines anyway, in case we need it again someday.
138  *
139  * subquery_planner will be called recursively to handle sub-Query nodes
140  * found within the query's expressions and rangetable.
141  *
142  * Returns a query plan.
143  *--------------------
144  */
145 Plan *
146 subquery_planner(Query *parse, double tuple_fraction)
147 {
148         List       *saved_initplan = PlannerInitPlan;
149         int                     saved_planid = PlannerPlanId;
150         Plan       *plan;
151         List       *newHaving;
152         List       *lst;
153
154         /* Set up for a new level of subquery */
155         PlannerQueryLevel++;
156         PlannerInitPlan = NIL;
157
158         /*
159          * Check to see if any subqueries in the rangetable can be merged into
160          * this query.
161          */
162         parse->jointree = (FromExpr *)
163                 pull_up_subqueries(parse, (Node *) parse->jointree, false);
164
165         /*
166          * If so, we may have created opportunities to simplify the jointree.
167          */
168         parse->jointree = (FromExpr *)
169                 preprocess_jointree(parse, (Node *) parse->jointree);
170
171         /*
172          * Detect whether any rangetable entries are RTE_JOIN kind; if not,
173          * we can avoid the expense of doing flatten_join_alias_vars().
174          * This must be done after we have done pull_up_subqueries, of course.
175          */
176         parse->hasJoinRTEs = false;
177         foreach(lst, parse->rtable)
178         {
179                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lst);
180
181                 if (rte->rtekind == RTE_JOIN)
182                 {
183                         parse->hasJoinRTEs = true;
184                         break;
185                 }
186         }
187
188         /*
189          * Do expression preprocessing on targetlist and quals.
190          */
191         parse->targetList = (List *)
192                 preprocess_expression(parse, (Node *) parse->targetList,
193                                                           EXPRKIND_TARGET);
194
195         preprocess_qual_conditions(parse, (Node *) parse->jointree);
196
197         parse->havingQual = preprocess_expression(parse, parse->havingQual,
198                                                                                           EXPRKIND_HAVING);
199
200         /* Also need to preprocess expressions for function RTEs */
201         foreach(lst, parse->rtable)
202         {
203                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lst);
204
205                 if (rte->rtekind == RTE_FUNCTION)
206                         rte->funcexpr = preprocess_expression(parse, rte->funcexpr,
207                                                                                                   EXPRKIND_TARGET);
208                 /* These are not targetlist items, but close enough... */
209         }
210
211         /*
212          * Check for ungrouped variables passed to subplans in targetlist and
213          * HAVING clause (but not in WHERE or JOIN/ON clauses, since those are
214          * evaluated before grouping).  We can't do this any earlier because
215          * we must use the preprocessed targetlist for comparisons of grouped
216          * expressions.
217          */
218         if (parse->hasSubLinks &&
219                 (parse->groupClause != NIL || parse->hasAggs))
220                 check_subplans_for_ungrouped_vars(parse);
221
222         /*
223          * A HAVING clause without aggregates is equivalent to a WHERE clause
224          * (except it can only refer to grouped fields).  Transfer any
225          * agg-free clauses of the HAVING qual into WHERE.      This may seem like
226          * wasting cycles to cater to stupidly-written queries, but there are
227          * other reasons for doing it.  Firstly, if the query contains no aggs
228          * at all, then we aren't going to generate an Agg plan node, and so
229          * there'll be no place to execute HAVING conditions; without this
230          * transfer, we'd lose the HAVING condition entirely, which is wrong.
231          * Secondly, when we push down a qual condition into a sub-query, it's
232          * easiest to push the qual into HAVING always, in case it contains
233          * aggs, and then let this code sort it out.
234          *
235          * Note that both havingQual and parse->jointree->quals are in
236          * implicitly-ANDed-list form at this point, even though they are
237          * declared as Node *.  Also note that contain_agg_clause does not
238          * recurse into sub-selects, which is exactly what we need here.
239          */
240         newHaving = NIL;
241         foreach(lst, (List *) parse->havingQual)
242         {
243                 Node       *havingclause = (Node *) lfirst(lst);
244
245                 if (contain_agg_clause(havingclause))
246                         newHaving = lappend(newHaving, havingclause);
247                 else
248                         parse->jointree->quals = (Node *)
249                                 lappend((List *) parse->jointree->quals, havingclause);
250         }
251         parse->havingQual = (Node *) newHaving;
252
253         /*
254          * Do the main planning.  If we have an inherited target relation,
255          * that needs special processing, else go straight to
256          * grouping_planner.
257          */
258         if (parse->resultRelation &&
259          (lst = expand_inherted_rtentry(parse, parse->resultRelation, false))
260                 != NIL)
261                 plan = inheritance_planner(parse, lst);
262         else
263                 plan = grouping_planner(parse, tuple_fraction);
264
265         /*
266          * If any subplans were generated, or if we're inside a subplan, build
267          * initPlan, extParam and locParam lists for plan nodes.
268          */
269         if (PlannerPlanId != saved_planid || PlannerQueryLevel > 1)
270         {
271                 Cost    initplan_cost = 0;
272
273                 /* Prepare extParam/locParam data for all nodes in tree */
274                 (void) SS_finalize_plan(plan, parse->rtable);
275
276                 /*
277                  * SS_finalize_plan doesn't handle initPlans, so we have to manually
278                  * attach them to the topmost plan node, and add their extParams to
279                  * the topmost node's, too.
280                  *
281                  * We also add the total_cost of each initPlan to the startup cost
282                  * of the top node.  This is a conservative overestimate, since in
283                  * fact each initPlan might be executed later than plan startup, or
284                  * even not at all.
285                  */
286                 plan->initPlan = PlannerInitPlan;
287
288                 foreach(lst, plan->initPlan)
289                 {
290                         SubPlan    *initplan = (SubPlan *) lfirst(lst);
291
292                         plan->extParam = set_unioni(plan->extParam,
293                                                                                 initplan->plan->extParam);
294                         initplan_cost += initplan->plan->total_cost;
295                 }
296
297                 plan->startup_cost += initplan_cost;
298                 plan->total_cost += initplan_cost;
299         }
300
301         /* Return to outer subquery context */
302         PlannerQueryLevel--;
303         PlannerInitPlan = saved_initplan;
304         /* we do NOT restore PlannerPlanId; that's not an oversight! */
305
306         return plan;
307 }
308
309 /*
310  * pull_up_subqueries
311  *              Look for subqueries in the rangetable that can be pulled up into
312  *              the parent query.  If the subquery has no special features like
313  *              grouping/aggregation then we can merge it into the parent's jointree.
314  *
315  * below_outer_join is true if this jointree node is within the nullable
316  * side of an outer join.  This restricts what we can do.
317  *
318  * A tricky aspect of this code is that if we pull up a subquery we have
319  * to replace Vars that reference the subquery's outputs throughout the
320  * parent query, including quals attached to jointree nodes above the one
321  * we are currently processing!  We handle this by being careful not to
322  * change the jointree structure while recursing: no nodes other than
323  * subquery RangeTblRef entries will be replaced.  Also, we can't turn
324  * ResolveNew loose on the whole jointree, because it'll return a mutated
325  * copy of the tree; we have to invoke it just on the quals, instead.
326  */
327 static Node *
328 pull_up_subqueries(Query *parse, Node *jtnode, bool below_outer_join)
329 {
330         if (jtnode == NULL)
331                 return NULL;
332         if (IsA(jtnode, RangeTblRef))
333         {
334                 int                     varno = ((RangeTblRef *) jtnode)->rtindex;
335                 RangeTblEntry *rte = rt_fetch(varno, parse->rtable);
336                 Query      *subquery = rte->subquery;
337
338                 /*
339                  * Is this a subquery RTE, and if so, is the subquery simple
340                  * enough to pull up?  (If not, do nothing at this node.)
341                  *
342                  * If we are inside an outer join, only pull up subqueries whose
343                  * targetlists are nullable --- otherwise substituting their tlist
344                  * entries for upper Var references would do the wrong thing (the
345                  * results wouldn't become NULL when they're supposed to). XXX
346                  * This could be improved by generating pseudo-variables for such
347                  * expressions; we'd have to figure out how to get the pseudo-
348                  * variables evaluated at the right place in the modified plan
349                  * tree. Fix it someday.
350                  *
351                  * Note: even if the subquery itself is simple enough, we can't pull
352                  * it up if there is a reference to its whole tuple result.
353                  * Perhaps a pseudo-variable is the answer here too.
354                  */
355                 if (rte->rtekind == RTE_SUBQUERY && is_simple_subquery(subquery) &&
356                         (!below_outer_join || has_nullable_targetlist(subquery)) &&
357                         !contain_whole_tuple_var((Node *) parse, varno, 0))
358                 {
359                         int                     rtoffset;
360                         List       *subtlist;
361                         List       *rt;
362
363                         /*
364                          * First, recursively pull up the subquery's subqueries, so
365                          * that this routine's processing is complete for its jointree
366                          * and rangetable.      NB: if the same subquery is referenced
367                          * from multiple jointree items (which can't happen normally,
368                          * but might after rule rewriting), then we will invoke this
369                          * processing multiple times on that subquery.  OK because
370                          * nothing will happen after the first time.  We do have to be
371                          * careful to copy everything we pull up, however, or risk
372                          * having chunks of structure multiply linked.
373                          *
374                          * Note: 'false' is correct here even if we are within an outer
375                          * join in the upper query; the lower query starts with a clean
376                          * slate for outer-join semantics.
377                          */
378                         subquery->jointree = (FromExpr *)
379                                 pull_up_subqueries(subquery, (Node *) subquery->jointree,
380                                                                    false);
381
382                         /*
383                          * Now make a modifiable copy of the subquery that we can run
384                          * OffsetVarNodes and IncrementVarSublevelsUp on.
385                          */
386                         subquery = copyObject(subquery);
387
388                         /*
389                          * Adjust level-0 varnos in subquery so that we can append its
390                          * rangetable to upper query's.
391                          */
392                         rtoffset = length(parse->rtable);
393                         OffsetVarNodes((Node *) subquery, rtoffset, 0);
394
395                         /*
396                          * Upper-level vars in subquery are now one level closer to their
397                          * parent than before.
398                          */
399                         IncrementVarSublevelsUp((Node *) subquery, -1, 1);
400
401                         /*
402                          * Replace all of the top query's references to the subquery's
403                          * outputs with copies of the adjusted subtlist items, being
404                          * careful not to replace any of the jointree structure.
405                          * (This'd be a lot cleaner if we could use
406                          * query_tree_mutator.)
407                          */
408                         subtlist = subquery->targetList;
409                         parse->targetList = (List *)
410                                 ResolveNew((Node *) parse->targetList,
411                                                    varno, 0, subtlist, CMD_SELECT, 0);
412                         resolvenew_in_jointree((Node *) parse->jointree, varno, subtlist);
413                         Assert(parse->setOperations == NULL);
414                         parse->havingQual =
415                                 ResolveNew(parse->havingQual,
416                                                    varno, 0, subtlist, CMD_SELECT, 0);
417
418                         foreach(rt, parse->rtable)
419                         {
420                                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
421
422                                 if (rte->rtekind == RTE_JOIN)
423                                         rte->joinaliasvars = (List *)
424                                                 ResolveNew((Node *) rte->joinaliasvars,
425                                                                    varno, 0, subtlist, CMD_SELECT, 0);
426                         }
427
428                         /*
429                          * Now append the adjusted rtable entries to upper query. (We
430                          * hold off until after fixing the upper rtable entries; no
431                          * point in running that code on the subquery ones too.)
432                          */
433                         parse->rtable = nconc(parse->rtable, subquery->rtable);
434
435                         /*
436                          * Pull up any FOR UPDATE markers, too.  (OffsetVarNodes
437                          * already adjusted the marker values, so just nconc the
438                          * list.)
439                          */
440                         parse->rowMarks = nconc(parse->rowMarks, subquery->rowMarks);
441
442                         /*
443                          * Miscellaneous housekeeping.
444                          */
445                         parse->hasSubLinks |= subquery->hasSubLinks;
446                         /* subquery won't be pulled up if it hasAggs, so no work there */
447
448                         /*
449                          * Return the adjusted subquery jointree to replace the
450                          * RangeTblRef entry in my jointree.
451                          */
452                         return (Node *) subquery->jointree;
453                 }
454         }
455         else if (IsA(jtnode, FromExpr))
456         {
457                 FromExpr   *f = (FromExpr *) jtnode;
458                 List       *l;
459
460                 foreach(l, f->fromlist)
461                         lfirst(l) = pull_up_subqueries(parse, lfirst(l),
462                                                                                    below_outer_join);
463         }
464         else if (IsA(jtnode, JoinExpr))
465         {
466                 JoinExpr   *j = (JoinExpr *) jtnode;
467
468                 /* Recurse, being careful to tell myself when inside outer join */
469                 switch (j->jointype)
470                 {
471                         case JOIN_INNER:
472                                 j->larg = pull_up_subqueries(parse, j->larg,
473                                                                                          below_outer_join);
474                                 j->rarg = pull_up_subqueries(parse, j->rarg,
475                                                                                          below_outer_join);
476                                 break;
477                         case JOIN_LEFT:
478                                 j->larg = pull_up_subqueries(parse, j->larg,
479                                                                                          below_outer_join);
480                                 j->rarg = pull_up_subqueries(parse, j->rarg,
481                                                                                          true);
482                                 break;
483                         case JOIN_FULL:
484                                 j->larg = pull_up_subqueries(parse, j->larg,
485                                                                                          true);
486                                 j->rarg = pull_up_subqueries(parse, j->rarg,
487                                                                                          true);
488                                 break;
489                         case JOIN_RIGHT:
490                                 j->larg = pull_up_subqueries(parse, j->larg,
491                                                                                          true);
492                                 j->rarg = pull_up_subqueries(parse, j->rarg,
493                                                                                          below_outer_join);
494                                 break;
495                         case JOIN_UNION:
496
497                                 /*
498                                  * This is where we fail if upper levels of planner
499                                  * haven't rewritten UNION JOIN as an Append ...
500                                  */
501                                 elog(ERROR, "UNION JOIN is not implemented yet");
502                                 break;
503                         default:
504                                 elog(ERROR, "pull_up_subqueries: unexpected join type %d",
505                                          j->jointype);
506                                 break;
507                 }
508         }
509         else
510                 elog(ERROR, "pull_up_subqueries: unexpected node type %d",
511                          nodeTag(jtnode));
512         return jtnode;
513 }
514
515 /*
516  * is_simple_subquery
517  *        Check a subquery in the range table to see if it's simple enough
518  *        to pull up into the parent query.
519  */
520 static bool
521 is_simple_subquery(Query *subquery)
522 {
523         /*
524          * Let's just make sure it's a valid subselect ...
525          */
526         if (!IsA(subquery, Query) ||
527                 subquery->commandType != CMD_SELECT ||
528                 subquery->resultRelation != 0 ||
529                 subquery->into != NULL ||
530                 subquery->isPortal)
531                 elog(ERROR, "is_simple_subquery: subquery is bogus");
532
533         /*
534          * Can't currently pull up a query with setops. Maybe after querytree
535          * redesign...
536          */
537         if (subquery->setOperations)
538                 return false;
539
540         /*
541          * Can't pull up a subquery involving grouping, aggregation, sorting,
542          * or limiting.
543          */
544         if (subquery->hasAggs ||
545                 subquery->groupClause ||
546                 subquery->havingQual ||
547                 subquery->sortClause ||
548                 subquery->distinctClause ||
549                 subquery->limitOffset ||
550                 subquery->limitCount)
551                 return false;
552
553         /*
554          * Don't pull up a subquery that has any set-returning functions in
555          * its targetlist.      Otherwise we might well wind up inserting
556          * set-returning functions into places where they mustn't go, such as
557          * quals of higher queries.
558          */
559         if (expression_returns_set((Node *) subquery->targetList))
560                 return false;
561
562         /*
563          * Don't pull up a subquery that has any sublinks in its targetlist,
564          * either.  As of PG 7.3 this creates problems because the pulled-up
565          * expressions may go into join alias lists, and the sublinks would
566          * not get fixed because we do flatten_join_alias_vars() too late.
567          * Eventually we should do a complete flatten_join_alias_vars as the
568          * first step of preprocess_expression, and then we could probably
569          * support this.  (BUT: it might be a bad idea anyway, due to possibly
570          * causing multiple evaluations of an expensive sublink.)
571          */
572         if (subquery->hasSubLinks &&
573                 contain_subplans((Node *) subquery->targetList))
574                 return false;
575
576         /*
577          * Hack: don't try to pull up a subquery with an empty jointree.
578          * query_planner() will correctly generate a Result plan for a
579          * jointree that's totally empty, but I don't think the right things
580          * happen if an empty FromExpr appears lower down in a jointree. Not
581          * worth working hard on this, just to collapse SubqueryScan/Result
582          * into Result...
583          */
584         if (subquery->jointree->fromlist == NIL)
585                 return false;
586
587         return true;
588 }
589
590 /*
591  * has_nullable_targetlist
592  *        Check a subquery in the range table to see if all the non-junk
593  *        targetlist items are simple variables (and, hence, will correctly
594  *        go to NULL when examined above the point of an outer join).
595  *
596  * A possible future extension is to accept strict functions of simple
597  * variables, eg, "x + 1".
598  */
599 static bool
600 has_nullable_targetlist(Query *subquery)
601 {
602         List       *l;
603
604         foreach(l, subquery->targetList)
605         {
606                 TargetEntry *tle = (TargetEntry *) lfirst(l);
607
608                 /* ignore resjunk columns */
609                 if (tle->resdom->resjunk)
610                         continue;
611
612                 /* Okay if tlist item is a simple Var */
613                 if (tle->expr && IsA(tle->expr, Var))
614                         continue;
615
616                 return false;
617         }
618         return true;
619 }
620
621 /*
622  * Helper routine for pull_up_subqueries: do ResolveNew on every expression
623  * in the jointree, without changing the jointree structure itself.  Ugly,
624  * but there's no other way...
625  */
626 static void
627 resolvenew_in_jointree(Node *jtnode, int varno, List *subtlist)
628 {
629         if (jtnode == NULL)
630                 return;
631         if (IsA(jtnode, RangeTblRef))
632         {
633                 /* nothing to do here */
634         }
635         else if (IsA(jtnode, FromExpr))
636         {
637                 FromExpr   *f = (FromExpr *) jtnode;
638                 List       *l;
639
640                 foreach(l, f->fromlist)
641                         resolvenew_in_jointree(lfirst(l), varno, subtlist);
642                 f->quals = ResolveNew(f->quals,
643                                                           varno, 0, subtlist, CMD_SELECT, 0);
644         }
645         else if (IsA(jtnode, JoinExpr))
646         {
647                 JoinExpr   *j = (JoinExpr *) jtnode;
648
649                 resolvenew_in_jointree(j->larg, varno, subtlist);
650                 resolvenew_in_jointree(j->rarg, varno, subtlist);
651                 j->quals = ResolveNew(j->quals,
652                                                           varno, 0, subtlist, CMD_SELECT, 0);
653
654                 /*
655                  * We don't bother to update the colvars list, since it won't be
656                  * used again ...
657                  */
658         }
659         else
660                 elog(ERROR, "resolvenew_in_jointree: unexpected node type %d",
661                          nodeTag(jtnode));
662 }
663
664 /*
665  * preprocess_jointree
666  *              Attempt to simplify a query's jointree.
667  *
668  * If we succeed in pulling up a subquery then we might form a jointree
669  * in which a FromExpr is a direct child of another FromExpr.  In that
670  * case we can consider collapsing the two FromExprs into one.  This is
671  * an optional conversion, since the planner will work correctly either
672  * way.  But we may find a better plan (at the cost of more planning time)
673  * if we merge the two nodes.
674  *
675  * NOTE: don't try to do this in the same jointree scan that does subquery
676  * pullup!      Since we're changing the jointree structure here, that wouldn't
677  * work reliably --- see comments for pull_up_subqueries().
678  */
679 static Node *
680 preprocess_jointree(Query *parse, Node *jtnode)
681 {
682         if (jtnode == NULL)
683                 return NULL;
684         if (IsA(jtnode, RangeTblRef))
685         {
686                 /* nothing to do here... */
687         }
688         else if (IsA(jtnode, FromExpr))
689         {
690                 FromExpr   *f = (FromExpr *) jtnode;
691                 List       *newlist = NIL;
692                 List       *l;
693
694                 foreach(l, f->fromlist)
695                 {
696                         Node       *child = (Node *) lfirst(l);
697
698                         /* Recursively simplify the child... */
699                         child = preprocess_jointree(parse, child);
700                         /* Now, is it a FromExpr? */
701                         if (child && IsA(child, FromExpr))
702                         {
703                                 /*
704                                  * Yes, so do we want to merge it into parent?  Always do
705                                  * so if child has just one element (since that doesn't
706                                  * make the parent's list any longer).  Otherwise we have
707                                  * to be careful about the increase in planning time
708                                  * caused by combining the two join search spaces into
709                                  * one.  Our heuristic is to merge if the merge will
710                                  * produce a join list no longer than GEQO_RELS/2.
711                                  * (Perhaps need an additional user parameter?)
712                                  */
713                                 FromExpr   *subf = (FromExpr *) child;
714                                 int                     childlen = length(subf->fromlist);
715                                 int                     myothers = length(newlist) + length(lnext(l));
716
717                                 if (childlen <= 1 || (childlen + myothers) <= geqo_rels / 2)
718                                 {
719                                         newlist = nconc(newlist, subf->fromlist);
720                                         f->quals = make_and_qual(subf->quals, f->quals);
721                                 }
722                                 else
723                                         newlist = lappend(newlist, child);
724                         }
725                         else
726                                 newlist = lappend(newlist, child);
727                 }
728                 f->fromlist = newlist;
729         }
730         else if (IsA(jtnode, JoinExpr))
731         {
732                 JoinExpr   *j = (JoinExpr *) jtnode;
733
734                 /* Can't usefully change the JoinExpr, but recurse on children */
735                 j->larg = preprocess_jointree(parse, j->larg);
736                 j->rarg = preprocess_jointree(parse, j->rarg);
737         }
738         else
739                 elog(ERROR, "preprocess_jointree: unexpected node type %d",
740                          nodeTag(jtnode));
741         return jtnode;
742 }
743
744 /*
745  * preprocess_expression
746  *              Do subquery_planner's preprocessing work for an expression,
747  *              which can be a targetlist, a WHERE clause (including JOIN/ON
748  *              conditions), or a HAVING clause.
749  */
750 static Node *
751 preprocess_expression(Query *parse, Node *expr, int kind)
752 {
753         /*
754          * Simplify constant expressions.
755          *
756          * Note that at this point quals have not yet been converted to
757          * implicit-AND form, so we can apply eval_const_expressions directly.
758          */
759         expr = eval_const_expressions(expr);
760
761         /*
762          * If it's a qual or havingQual, canonicalize it, and convert it to
763          * implicit-AND format.
764          *
765          * XXX Is there any value in re-applying eval_const_expressions after
766          * canonicalize_qual?
767          */
768         if (kind != EXPRKIND_TARGET)
769         {
770                 expr = (Node *) canonicalize_qual((Expr *) expr, true);
771
772 #ifdef OPTIMIZER_DEBUG
773                 printf("After canonicalize_qual()\n");
774                 pprint(expr);
775 #endif
776         }
777
778         /* Expand SubLinks to SubPlans */
779         if (parse->hasSubLinks)
780                 expr = SS_process_sublinks(expr, (kind != EXPRKIND_TARGET));
781
782         /* Replace uplevel vars with Param nodes */
783         if (PlannerQueryLevel > 1)
784                 expr = SS_replace_correlation_vars(expr);
785
786         /*
787          * If the query has any join RTEs, try to replace join alias variables
788          * with base-relation variables, to allow quals to be pushed down. We
789          * must do this after sublink processing, since it does not recurse
790          * into sublinks.
791          */
792         if (parse->hasJoinRTEs)
793                 expr = flatten_join_alias_vars(expr, parse->rtable, false);
794
795         return expr;
796 }
797
798 /*
799  * preprocess_qual_conditions
800  *              Recursively scan the query's jointree and do subquery_planner's
801  *              preprocessing work on each qual condition found therein.
802  */
803 static void
804 preprocess_qual_conditions(Query *parse, Node *jtnode)
805 {
806         if (jtnode == NULL)
807                 return;
808         if (IsA(jtnode, RangeTblRef))
809         {
810                 /* nothing to do here */
811         }
812         else if (IsA(jtnode, FromExpr))
813         {
814                 FromExpr   *f = (FromExpr *) jtnode;
815                 List       *l;
816
817                 foreach(l, f->fromlist)
818                         preprocess_qual_conditions(parse, lfirst(l));
819
820                 f->quals = preprocess_expression(parse, f->quals, EXPRKIND_WHERE);
821         }
822         else if (IsA(jtnode, JoinExpr))
823         {
824                 JoinExpr   *j = (JoinExpr *) jtnode;
825
826                 preprocess_qual_conditions(parse, j->larg);
827                 preprocess_qual_conditions(parse, j->rarg);
828
829                 j->quals = preprocess_expression(parse, j->quals, EXPRKIND_WHERE);
830         }
831         else
832                 elog(ERROR, "preprocess_qual_conditions: unexpected node type %d",
833                          nodeTag(jtnode));
834 }
835
836 /*--------------------
837  * inheritance_planner
838  *        Generate a plan in the case where the result relation is an
839  *        inheritance set.
840  *
841  * We have to handle this case differently from cases where a source
842  * relation is an inheritance set.      Source inheritance is expanded at
843  * the bottom of the plan tree (see allpaths.c), but target inheritance
844  * has to be expanded at the top.  The reason is that for UPDATE, each
845  * target relation needs a different targetlist matching its own column
846  * set.  (This is not so critical for DELETE, but for simplicity we treat
847  * inherited DELETE the same way.)      Fortunately, the UPDATE/DELETE target
848  * can never be the nullable side of an outer join, so it's OK to generate
849  * the plan this way.
850  *
851  * parse is the querytree produced by the parser & rewriter.
852  * inheritlist is an integer list of RT indexes for the result relation set.
853  *
854  * Returns a query plan.
855  *--------------------
856  */
857 static Plan *
858 inheritance_planner(Query *parse, List *inheritlist)
859 {
860         int                     parentRTindex = parse->resultRelation;
861         Oid                     parentOID = getrelid(parentRTindex, parse->rtable);
862         List       *subplans = NIL;
863         List       *tlist = NIL;
864         List       *l;
865
866         foreach(l, inheritlist)
867         {
868                 int                     childRTindex = lfirsti(l);
869                 Oid                     childOID = getrelid(childRTindex, parse->rtable);
870                 Query      *subquery;
871                 Plan       *subplan;
872
873                 /* Generate modified query with this rel as target */
874                 subquery = (Query *) adjust_inherited_attrs((Node *) parse,
875                                                                                                 parentRTindex, parentOID,
876                                                                                                  childRTindex, childOID);
877                 /* Generate plan */
878                 subplan = grouping_planner(subquery, 0.0 /* retrieve all tuples */ );
879                 subplans = lappend(subplans, subplan);
880                 /* Save preprocessed tlist from first rel for use in Append */
881                 if (tlist == NIL)
882                         tlist = subplan->targetlist;
883         }
884
885         /* Save the target-relations list for the executor, too */
886         parse->resultRelations = inheritlist;
887
888         return (Plan *) make_append(subplans, true, tlist);
889 }
890
891 /*--------------------
892  * grouping_planner
893  *        Perform planning steps related to grouping, aggregation, etc.
894  *        This primarily means adding top-level processing to the basic
895  *        query plan produced by query_planner.
896  *
897  * parse is the querytree produced by the parser & rewriter.
898  * tuple_fraction is the fraction of tuples we expect will be retrieved
899  *
900  * tuple_fraction is interpreted as follows:
901  *        < 0: determine fraction by inspection of query (normal case)
902  *        0: expect all tuples to be retrieved
903  *        0 < tuple_fraction < 1: expect the given fraction of tuples available
904  *              from the plan to be retrieved
905  *        tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
906  *              expected to be retrieved (ie, a LIMIT specification)
907  * The normal case is to pass -1, but some callers pass values >= 0 to
908  * override this routine's determination of the appropriate fraction.
909  *
910  * Returns a query plan.
911  *--------------------
912  */
913 static Plan *
914 grouping_planner(Query *parse, double tuple_fraction)
915 {
916         List       *tlist = parse->targetList;
917         Plan       *result_plan;
918         List       *current_pathkeys;
919         List       *sort_pathkeys;
920
921         if (parse->setOperations)
922         {
923                 /*
924                  * Construct the plan for set operations.  The result will not
925                  * need any work except perhaps a top-level sort and/or LIMIT.
926                  */
927                 result_plan = plan_set_operations(parse);
928
929                 /*
930                  * We should not need to call preprocess_targetlist, since we must
931                  * be in a SELECT query node.  Instead, use the targetlist
932                  * returned by plan_set_operations (since this tells whether it
933                  * returned any resjunk columns!), and transfer any sort key
934                  * information from the original tlist.
935                  */
936                 Assert(parse->commandType == CMD_SELECT);
937
938                 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
939
940                 /*
941                  * Can't handle FOR UPDATE here (parser should have checked
942                  * already, but let's make sure).
943                  */
944                 if (parse->rowMarks)
945                         elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
946
947                 /*
948                  * We set current_pathkeys NIL indicating we do not know sort
949                  * order.  This is correct when the top set operation is UNION
950                  * ALL, since the appended-together results are unsorted even if
951                  * the subplans were sorted.  For other set operations we could be
952                  * smarter --- room for future improvement!
953                  */
954                 current_pathkeys = NIL;
955
956                 /*
957                  * Calculate pathkeys that represent ordering requirements
958                  */
959                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
960                                                                                                           tlist);
961                 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
962         }
963         else
964         {
965                 /* No set operations, do regular planning */
966                 List       *sub_tlist;
967                 List       *group_pathkeys;
968                 AttrNumber *groupColIdx = NULL;
969                 QualCost        tlist_cost;
970                 double          sub_tuple_fraction;
971                 Path       *cheapest_path;
972                 Path       *sorted_path;
973                 double          dNumGroups = 0;
974                 long            numGroups = 0;
975                 int                     numAggs = 0;
976                 int                     numGroupCols = length(parse->groupClause);
977                 bool            use_hashed_grouping = false;
978
979                 /* Preprocess targetlist in case we are inside an INSERT/UPDATE. */
980                 tlist = preprocess_targetlist(tlist,
981                                                                           parse->commandType,
982                                                                           parse->resultRelation,
983                                                                           parse->rtable);
984
985                 /*
986                  * Add TID targets for rels selected FOR UPDATE (should this be
987                  * done in preprocess_targetlist?).  The executor uses the TID to
988                  * know which rows to lock, much as for UPDATE or DELETE.
989                  */
990                 if (parse->rowMarks)
991                 {
992                         List       *l;
993
994                         /*
995                          * We've got trouble if the FOR UPDATE appears inside
996                          * grouping, since grouping renders a reference to individual
997                          * tuple CTIDs invalid.  This is also checked at parse time,
998                          * but that's insufficient because of rule substitution, query
999                          * pullup, etc.
1000                          */
1001                         CheckSelectForUpdate(parse);
1002
1003                         /*
1004                          * Currently the executor only supports FOR UPDATE at top
1005                          * level
1006                          */
1007                         if (PlannerQueryLevel > 1)
1008                                 elog(ERROR, "SELECT FOR UPDATE is not allowed in subselects");
1009
1010                         foreach(l, parse->rowMarks)
1011                         {
1012                                 Index           rti = lfirsti(l);
1013                                 char       *resname;
1014                                 Resdom     *resdom;
1015                                 Var                *var;
1016                                 TargetEntry *ctid;
1017
1018                                 resname = (char *) palloc(32);
1019                                 snprintf(resname, 32, "ctid%u", rti);
1020                                 resdom = makeResdom(length(tlist) + 1,
1021                                                                         TIDOID,
1022                                                                         -1,
1023                                                                         resname,
1024                                                                         true);
1025
1026                                 var = makeVar(rti,
1027                                                           SelfItemPointerAttributeNumber,
1028                                                           TIDOID,
1029                                                           -1,
1030                                                           0);
1031
1032                                 ctid = makeTargetEntry(resdom, (Expr *) var);
1033                                 tlist = lappend(tlist, ctid);
1034                         }
1035                 }
1036
1037                 /*
1038                  * Generate appropriate target list for subplan; may be different
1039                  * from tlist if grouping or aggregation is needed.
1040                  */
1041                 sub_tlist = make_subplanTargetList(parse, tlist, &groupColIdx);
1042
1043                 /*
1044                  * Calculate pathkeys that represent grouping/ordering
1045                  * requirements
1046                  */
1047                 group_pathkeys = make_pathkeys_for_sortclauses(parse->groupClause,
1048                                                                                                            tlist);
1049                 sort_pathkeys = make_pathkeys_for_sortclauses(parse->sortClause,
1050                                                                                                           tlist);
1051
1052                 /*
1053                  * Will need actual number of aggregates for estimating costs.
1054                  * Also, it's possible that optimization has eliminated all
1055                  * aggregates, and we may as well check for that here.
1056                  */
1057                 if (parse->hasAggs)
1058                 {
1059                         numAggs = length(pull_agg_clause((Node *) tlist)) +
1060                                 length(pull_agg_clause(parse->havingQual));
1061                         if (numAggs == 0)
1062                                 parse->hasAggs = false;
1063                 }
1064
1065                 /*
1066                  * Figure out whether we need a sorted result from query_planner.
1067                  *
1068                  * If we have a GROUP BY clause, then we want a result sorted
1069                  * properly for grouping.  Otherwise, if there is an ORDER BY
1070                  * clause, we want to sort by the ORDER BY clause.      (Note: if we
1071                  * have both, and ORDER BY is a superset of GROUP BY, it would be
1072                  * tempting to request sort by ORDER BY --- but that might just
1073                  * leave us failing to exploit an available sort order at all.
1074                  * Needs more thought...)
1075                  */
1076                 if (parse->groupClause)
1077                         parse->query_pathkeys = group_pathkeys;
1078                 else if (parse->sortClause)
1079                         parse->query_pathkeys = sort_pathkeys;
1080                 else
1081                         parse->query_pathkeys = NIL;
1082
1083                 /*
1084                  * Figure out whether we expect to retrieve all the tuples that
1085                  * the plan can generate, or to stop early due to outside factors
1086                  * such as a cursor.  If the caller passed a value >= 0, believe
1087                  * that value, else do our own examination of the query context.
1088                  */
1089                 if (tuple_fraction < 0.0)
1090                 {
1091                         /* Initial assumption is we need all the tuples */
1092                         tuple_fraction = 0.0;
1093
1094                         /*
1095                          * Check for retrieve-into-portal, ie DECLARE CURSOR.
1096                          *
1097                          * We have no real idea how many tuples the user will ultimately
1098                          * FETCH from a cursor, but it seems a good bet that he
1099                          * doesn't want 'em all.  Optimize for 10% retrieval (you
1100                          * gotta better number?  Should this be a SETtable parameter?)
1101                          */
1102                         if (parse->isPortal)
1103                                 tuple_fraction = 0.10;
1104                 }
1105
1106                 /*
1107                  * Adjust tuple_fraction if we see that we are going to apply
1108                  * limiting/grouping/aggregation/etc.  This is not overridable by
1109                  * the caller, since it reflects plan actions that this routine
1110                  * will certainly take, not assumptions about context.
1111                  */
1112                 if (parse->limitCount != NULL)
1113                 {
1114                         /*
1115                          * A LIMIT clause limits the absolute number of tuples
1116                          * returned. However, if it's not a constant LIMIT then we
1117                          * have to punt; for lack of a better idea, assume 10% of the
1118                          * plan's result is wanted.
1119                          */
1120                         double          limit_fraction = 0.0;
1121
1122                         if (IsA(parse->limitCount, Const))
1123                         {
1124                                 Const      *limitc = (Const *) parse->limitCount;
1125                                 int32           count = DatumGetInt32(limitc->constvalue);
1126
1127                                 /*
1128                                  * A NULL-constant LIMIT represents "LIMIT ALL", which we
1129                                  * treat the same as no limit (ie, expect to retrieve all
1130                                  * the tuples).
1131                                  */
1132                                 if (!limitc->constisnull && count > 0)
1133                                 {
1134                                         limit_fraction = (double) count;
1135                                         /* We must also consider the OFFSET, if present */
1136                                         if (parse->limitOffset != NULL)
1137                                         {
1138                                                 if (IsA(parse->limitOffset, Const))
1139                                                 {
1140                                                         int32           offset;
1141
1142                                                         limitc = (Const *) parse->limitOffset;
1143                                                         offset = DatumGetInt32(limitc->constvalue);
1144                                                         if (!limitc->constisnull && offset > 0)
1145                                                                 limit_fraction += (double) offset;
1146                                                 }
1147                                                 else
1148                                                 {
1149                                                         /* OFFSET is an expression ... punt ... */
1150                                                         limit_fraction = 0.10;
1151                                                 }
1152                                         }
1153                                 }
1154                         }
1155                         else
1156                         {
1157                                 /* LIMIT is an expression ... punt ... */
1158                                 limit_fraction = 0.10;
1159                         }
1160
1161                         if (limit_fraction > 0.0)
1162                         {
1163                                 /*
1164                                  * If we have absolute limits from both caller and LIMIT,
1165                                  * use the smaller value; if one is fractional and the
1166                                  * other absolute, treat the fraction as a fraction of the
1167                                  * absolute value; else we can multiply the two fractions
1168                                  * together.
1169                                  */
1170                                 if (tuple_fraction >= 1.0)
1171                                 {
1172                                         if (limit_fraction >= 1.0)
1173                                         {
1174                                                 /* both absolute */
1175                                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
1176                                         }
1177                                         else
1178                                         {
1179                                                 /* caller absolute, limit fractional */
1180                                                 tuple_fraction *= limit_fraction;
1181                                                 if (tuple_fraction < 1.0)
1182                                                         tuple_fraction = 1.0;
1183                                         }
1184                                 }
1185                                 else if (tuple_fraction > 0.0)
1186                                 {
1187                                         if (limit_fraction >= 1.0)
1188                                         {
1189                                                 /* caller fractional, limit absolute */
1190                                                 tuple_fraction *= limit_fraction;
1191                                                 if (tuple_fraction < 1.0)
1192                                                         tuple_fraction = 1.0;
1193                                         }
1194                                         else
1195                                         {
1196                                                 /* both fractional */
1197                                                 tuple_fraction *= limit_fraction;
1198                                         }
1199                                 }
1200                                 else
1201                                 {
1202                                         /* no info from caller, just use limit */
1203                                         tuple_fraction = limit_fraction;
1204                                 }
1205                         }
1206                 }
1207
1208                 /*
1209                  * With grouping or aggregation, the tuple fraction to pass to
1210                  * query_planner() may be different from what it is at top level.
1211                  */
1212                 sub_tuple_fraction = tuple_fraction;
1213
1214                 if (parse->groupClause)
1215                 {
1216                         /*
1217                          * In GROUP BY mode, we have the little problem that we don't
1218                          * really know how many input tuples will be needed to make a
1219                          * group, so we can't translate an output LIMIT count into an
1220                          * input count.  For lack of a better idea, assume 25% of the
1221                          * input data will be processed if there is any output limit.
1222                          * However, if the caller gave us a fraction rather than an
1223                          * absolute count, we can keep using that fraction (which
1224                          * amounts to assuming that all the groups are about the same
1225                          * size).
1226                          */
1227                         if (sub_tuple_fraction >= 1.0)
1228                                 sub_tuple_fraction = 0.25;
1229
1230                         /*
1231                          * If both GROUP BY and ORDER BY are specified, we will need
1232                          * two levels of sort --- and, therefore, certainly need to
1233                          * read all the input tuples --- unless ORDER BY is a subset
1234                          * of GROUP BY.  (We have not yet canonicalized the pathkeys,
1235                          * so must use the slower noncanonical comparison method.)
1236                          */
1237                         if (parse->groupClause && parse->sortClause &&
1238                                 !noncanonical_pathkeys_contained_in(sort_pathkeys,
1239                                                                                                         group_pathkeys))
1240                                 sub_tuple_fraction = 0.0;
1241                 }
1242                 else if (parse->hasAggs)
1243                 {
1244                         /*
1245                          * Ungrouped aggregate will certainly want all the input
1246                          * tuples.
1247                          */
1248                         sub_tuple_fraction = 0.0;
1249                 }
1250                 else if (parse->distinctClause)
1251                 {
1252                         /*
1253                          * SELECT DISTINCT, like GROUP, will absorb an unpredictable
1254                          * number of input tuples per output tuple.  Handle the same
1255                          * way.
1256                          */
1257                         if (sub_tuple_fraction >= 1.0)
1258                                 sub_tuple_fraction = 0.25;
1259                 }
1260
1261                 /*
1262                  * Generate the best unsorted and presorted paths for this Query
1263                  * (but note there may not be any presorted path).
1264                  */
1265                 query_planner(parse, sub_tlist, sub_tuple_fraction,
1266                                           &cheapest_path, &sorted_path);
1267
1268                 /*
1269                  * We couldn't canonicalize group_pathkeys and sort_pathkeys before
1270                  * running query_planner(), so do it now.
1271                  */
1272                 group_pathkeys = canonicalize_pathkeys(parse, group_pathkeys);
1273                 sort_pathkeys = canonicalize_pathkeys(parse, sort_pathkeys);
1274
1275                 /*
1276                  * Consider whether we might want to use hashed grouping.
1277                  */
1278                 if (parse->groupClause)
1279                 {
1280                         /*
1281                          * Always estimate the number of groups.  We can't do this until
1282                          * after running query_planner(), either.
1283                          */
1284                         dNumGroups = estimate_num_groups(parse,
1285                                                                                          parse->groupClause,
1286                                                                                          cheapest_path->parent->rows);
1287                         /* Also want it as a long int --- but 'ware overflow! */
1288                         numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
1289
1290                         /*
1291                          * Check can't-do-it conditions, including whether the grouping
1292                          * operators are hashjoinable.
1293                          *
1294                          * Executor doesn't support hashed aggregation with DISTINCT
1295                          * aggregates.  (Doing so would imply storing *all* the input
1296                          * values in the hash table, which seems like a certain loser.)
1297                          */
1298                         if (!enable_hashagg || !hash_safe_grouping(parse))
1299                                 use_hashed_grouping = false;
1300                         else if (parse->hasAggs &&
1301                                          (contain_distinct_agg_clause((Node *) tlist) ||
1302                                           contain_distinct_agg_clause(parse->havingQual)))
1303                                 use_hashed_grouping = false;
1304                         else
1305                         {
1306                                 /*
1307                                  * Use hashed grouping if (a) we think we can fit the
1308                                  * hashtable into SortMem, *and* (b) the estimated cost
1309                                  * is no more than doing it the other way.  While avoiding
1310                                  * the need for sorted input is usually a win, the fact
1311                                  * that the output won't be sorted may be a loss; so we
1312                                  * need to do an actual cost comparison.
1313                                  *
1314                                  * In most cases we have no good way to estimate the size of
1315                                  * the transition value needed by an aggregate; arbitrarily
1316                                  * assume it is 100 bytes.  Also set the overhead per hashtable
1317                                  * entry at 64 bytes.
1318                                  */
1319                                 int             hashentrysize = cheapest_path->parent->width + 64 +
1320                                         numAggs * 100;
1321
1322                                 if (hashentrysize * dNumGroups <= SortMem * 1024L)
1323                                 {
1324                                         /*
1325                                          * Okay, do the cost comparison.  We need to consider
1326                                          *      cheapest_path + hashagg [+ final sort]
1327                                          * versus either
1328                                          *      cheapest_path [+ sort] + group or agg [+ final sort]
1329                                          * or
1330                                          *      presorted_path + group or agg [+ final sort]
1331                                          * where brackets indicate a step that may not be needed.
1332                                          * We assume query_planner() will have returned a
1333                                          * presorted path only if it's a winner compared to
1334                                          * cheapest_path for this purpose.
1335                                          *
1336                                          * These path variables are dummies that just hold cost
1337                                          * fields; we don't make actual Paths for these steps.
1338                                          */
1339                                         Path            hashed_p;
1340                                         Path            sorted_p;
1341
1342                                         cost_agg(&hashed_p, parse,
1343                                                          AGG_HASHED, numAggs,
1344                                                          numGroupCols, dNumGroups,
1345                                                          cheapest_path->startup_cost,
1346                                                          cheapest_path->total_cost,
1347                                                          cheapest_path->parent->rows);
1348                                         /* Result of hashed agg is always unsorted */
1349                                         if (sort_pathkeys)
1350                                                 cost_sort(&hashed_p, parse, sort_pathkeys,
1351                                                                   hashed_p.total_cost,
1352                                                                   dNumGroups,
1353                                                                   cheapest_path->parent->width);
1354
1355                                         if (sorted_path)
1356                                         {
1357                                                 sorted_p.startup_cost = sorted_path->startup_cost;
1358                                                 sorted_p.total_cost = sorted_path->total_cost;
1359                                                 current_pathkeys = sorted_path->pathkeys;
1360                                         }
1361                                         else
1362                                         {
1363                                                 sorted_p.startup_cost = cheapest_path->startup_cost;
1364                                                 sorted_p.total_cost = cheapest_path->total_cost;
1365                                                 current_pathkeys = cheapest_path->pathkeys;
1366                                         }
1367                                         if (!pathkeys_contained_in(group_pathkeys,
1368                                                                                            current_pathkeys))
1369                                         {
1370                                                 cost_sort(&sorted_p, parse, group_pathkeys,
1371                                                                   sorted_p.total_cost,
1372                                                                   cheapest_path->parent->rows,
1373                                                                   cheapest_path->parent->width);
1374                                                 current_pathkeys = group_pathkeys;
1375                                         }
1376                                         if (parse->hasAggs)
1377                                                 cost_agg(&sorted_p, parse,
1378                                                                  AGG_SORTED, numAggs,
1379                                                                  numGroupCols, dNumGroups,
1380                                                                  sorted_p.startup_cost,
1381                                                                  sorted_p.total_cost,
1382                                                                  cheapest_path->parent->rows);
1383                                         else
1384                                                 cost_group(&sorted_p, parse,
1385                                                                    numGroupCols, dNumGroups,
1386                                                                    sorted_p.startup_cost,
1387                                                                    sorted_p.total_cost,
1388                                                                    cheapest_path->parent->rows);
1389                                         /* The Agg or Group node will preserve ordering */
1390                                         if (sort_pathkeys &&
1391                                                 !pathkeys_contained_in(sort_pathkeys,
1392                                                                                            current_pathkeys))
1393                                         {
1394                                                 cost_sort(&sorted_p, parse, sort_pathkeys,
1395                                                                   sorted_p.total_cost,
1396                                                                   dNumGroups,
1397                                                                   cheapest_path->parent->width);
1398                                         }
1399
1400                                         /*
1401                                          * Now make the decision using the top-level tuple
1402                                          * fraction.  First we have to convert an absolute
1403                                          * count (LIMIT) into fractional form.
1404                                          */
1405                                         if (tuple_fraction >= 1.0)
1406                                                 tuple_fraction /= dNumGroups;
1407
1408                                         if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1409                                                                                                           tuple_fraction) <= 0)
1410                                         {
1411                                                 /* Hashed is cheaper, so use it */
1412                                                 use_hashed_grouping = true;
1413                                         }
1414                                 }
1415                         }
1416                 }
1417
1418                 /*
1419                  * Select the best path and create a plan to execute it.
1420                  *
1421                  * If we are doing hashed grouping, we will always read all the
1422                  * input tuples, so use the cheapest-total path.  Otherwise,
1423                  * trust query_planner's decision about which to use.
1424                  */
1425                 if (sorted_path && !use_hashed_grouping)
1426                 {
1427                         result_plan = create_plan(parse, sorted_path);
1428                         current_pathkeys = sorted_path->pathkeys;
1429                 }
1430                 else
1431                 {
1432                         result_plan = create_plan(parse, cheapest_path);
1433                         current_pathkeys = cheapest_path->pathkeys;
1434                 }
1435
1436                 /*
1437                  * create_plan() returns a plan with just a "flat" tlist of required
1438                  * Vars.  We want to insert the sub_tlist as the tlist of the top
1439                  * plan node.  If the top-level plan node is one that cannot do
1440                  * expression evaluation, we must insert a Result node to project the
1441                  * desired tlist.
1442                  * Currently, the only plan node we might see here that falls into
1443                  * that category is Append.
1444                  */
1445                 if (IsA(result_plan, Append))
1446                 {
1447                         result_plan = (Plan *) make_result(sub_tlist, NULL, result_plan);
1448                 }
1449                 else
1450                 {
1451                         /*
1452                          * Otherwise, just replace the flat tlist with the desired tlist.
1453                          */
1454                         result_plan->targetlist = sub_tlist;
1455                 }
1456                 /*
1457                  * Also, account for the cost of evaluation of the sub_tlist.
1458                  *
1459                  * Up to now, we have only been dealing with "flat" tlists, containing
1460                  * just Vars.  So their evaluation cost is zero according to the
1461                  * model used by cost_qual_eval() (or if you prefer, the cost is
1462                  * factored into cpu_tuple_cost).  Thus we can avoid accounting for
1463                  * tlist cost throughout query_planner() and subroutines.
1464                  * But now we've inserted a tlist that might contain actual operators,
1465                  * sub-selects, etc --- so we'd better account for its cost.
1466                  *
1467                  * Below this point, any tlist eval cost for added-on nodes should
1468                  * be accounted for as we create those nodes.  Presently, of the
1469                  * node types we can add on, only Agg and Group project new tlists
1470                  * (the rest just copy their input tuples) --- so make_agg() and
1471                  * make_group() are responsible for computing the added cost.
1472                  */
1473                 cost_qual_eval(&tlist_cost, sub_tlist);
1474                 result_plan->startup_cost += tlist_cost.startup;
1475                 result_plan->total_cost += tlist_cost.startup +
1476                         tlist_cost.per_tuple * result_plan->plan_rows;
1477
1478                 /*
1479                  * Insert AGG or GROUP node if needed, plus an explicit sort step
1480                  * if necessary.
1481                  *
1482                  * HAVING clause, if any, becomes qual of the Agg node
1483                  */
1484                 if (use_hashed_grouping)
1485                 {
1486                         /* Hashed aggregate plan --- no sort needed */
1487                         result_plan = (Plan *) make_agg(parse,
1488                                                                                         tlist,
1489                                                                                         (List *) parse->havingQual,
1490                                                                                         AGG_HASHED,
1491                                                                                         numGroupCols,
1492                                                                                         groupColIdx,
1493                                                                                         numGroups,
1494                                                                                         numAggs,
1495                                                                                         result_plan);
1496                         /* Hashed aggregation produces randomly-ordered results */
1497                         current_pathkeys = NIL;
1498                 }
1499                 else if (parse->hasAggs)
1500                 {
1501                         /* Plain aggregate plan --- sort if needed */
1502                         AggStrategy aggstrategy;
1503
1504                         if (parse->groupClause)
1505                         {
1506                                 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1507                                 {
1508                                         result_plan = make_groupsortplan(parse,
1509                                                                                                          parse->groupClause,
1510                                                                                                          groupColIdx,
1511                                                                                                          result_plan);
1512                                         current_pathkeys = group_pathkeys;
1513                                 }
1514                                 aggstrategy = AGG_SORTED;
1515                                 /*
1516                                  * The AGG node will not change the sort ordering of its
1517                                  * groups, so current_pathkeys describes the result too.
1518                                  */
1519                         }
1520                         else
1521                         {
1522                                 aggstrategy = AGG_PLAIN;
1523                                 /* Result will be only one row anyway; no sort order */
1524                                 current_pathkeys = NIL;
1525                         }
1526
1527                         result_plan = (Plan *) make_agg(parse,
1528                                                                                         tlist,
1529                                                                                         (List *) parse->havingQual,
1530                                                                                         aggstrategy,
1531                                                                                         numGroupCols,
1532                                                                                         groupColIdx,
1533                                                                                         numGroups,
1534                                                                                         numAggs,
1535                                                                                         result_plan);
1536                 }
1537                 else
1538                 {
1539                         /*
1540                          * If there are no Aggs, we shouldn't have any HAVING qual anymore
1541                          */
1542                         Assert(parse->havingQual == NULL);
1543
1544                         /*
1545                          * If we have a GROUP BY clause, insert a group node (plus the
1546                          * appropriate sort node, if necessary).
1547                          */
1548                         if (parse->groupClause)
1549                         {
1550                                 /*
1551                                  * Add an explicit sort if we couldn't make the path come out
1552                                  * the way the GROUP node needs it.
1553                                  */
1554                                 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1555                                 {
1556                                         result_plan = make_groupsortplan(parse,
1557                                                                                                          parse->groupClause,
1558                                                                                                          groupColIdx,
1559                                                                                                          result_plan);
1560                                         current_pathkeys = group_pathkeys;
1561                                 }
1562
1563                                 result_plan = (Plan *) make_group(parse,
1564                                                                                                   tlist,
1565                                                                                                   numGroupCols,
1566                                                                                                   groupColIdx,
1567                                                                                                   dNumGroups,
1568                                                                                                   result_plan);
1569                                 /* The Group node won't change sort ordering */
1570                         }
1571                 }
1572         } /* end of if (setOperations) */
1573
1574         /*
1575          * If we were not able to make the plan come out in the right order,
1576          * add an explicit sort step.
1577          */
1578         if (parse->sortClause)
1579         {
1580                 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1581                         result_plan = make_sortplan(parse, tlist, result_plan,
1582                                                                                 parse->sortClause);
1583         }
1584
1585         /*
1586          * If there is a DISTINCT clause, add the UNIQUE node.
1587          */
1588         if (parse->distinctClause)
1589         {
1590                 result_plan = (Plan *) make_unique(tlist, result_plan,
1591                                                                                    parse->distinctClause);
1592                 /*
1593                  * If there was grouping or aggregation, leave plan_rows as-is
1594                  * (ie, assume the result was already mostly unique).  If not,
1595                  * it's reasonable to assume the UNIQUE filter has effects
1596                  * comparable to GROUP BY.
1597                  */
1598                 if (!parse->groupClause && !parse->hasAggs)
1599                         result_plan->plan_rows = estimate_num_groups(parse,
1600                                                                                                                  parse->distinctClause,
1601                                                                                                                  result_plan->plan_rows);
1602         }
1603
1604         /*
1605          * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1606          */
1607         if (parse->limitOffset || parse->limitCount)
1608         {
1609                 result_plan = (Plan *) make_limit(tlist, result_plan,
1610                                                                                   parse->limitOffset,
1611                                                                                   parse->limitCount);
1612         }
1613
1614         return result_plan;
1615 }
1616
1617 /*
1618  * hash_safe_grouping - are grouping operators hashable?
1619  *
1620  * We assume hashed aggregation will work if the datatype's equality operator
1621  * is marked hashjoinable.
1622  */
1623 static bool
1624 hash_safe_grouping(Query *parse)
1625 {
1626         List       *gl;
1627
1628         foreach(gl, parse->groupClause)
1629         {
1630                 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1631                 TargetEntry *tle = get_sortgroupclause_tle(grpcl, parse->targetList);
1632                 Operator        optup;
1633                 bool            oprcanhash;
1634
1635                 optup = equality_oper(tle->resdom->restype, false);
1636                 oprcanhash = ((Form_pg_operator) GETSTRUCT(optup))->oprcanhash;
1637                 ReleaseSysCache(optup);
1638                 if (!oprcanhash)
1639                         return false;
1640         }
1641         return true;
1642 }
1643
1644 /*---------------
1645  * make_subplanTargetList
1646  *        Generate appropriate target list when grouping is required.
1647  *
1648  * When grouping_planner inserts Aggregate or Group plan nodes above
1649  * the result of query_planner, we typically want to pass a different
1650  * target list to query_planner than the outer plan nodes should have.
1651  * This routine generates the correct target list for the subplan.
1652  *
1653  * The initial target list passed from the parser already contains entries
1654  * for all ORDER BY and GROUP BY expressions, but it will not have entries
1655  * for variables used only in HAVING clauses; so we need to add those
1656  * variables to the subplan target list.  Also, if we are doing either
1657  * grouping or aggregation, we flatten all expressions except GROUP BY items
1658  * into their component variables; the other expressions will be computed by
1659  * the inserted nodes rather than by the subplan.  For example,
1660  * given a query like
1661  *              SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1662  * we want to pass this targetlist to the subplan:
1663  *              a,b,c,d,a+b
1664  * where the a+b target will be used by the Sort/Group steps, and the
1665  * other targets will be used for computing the final results.  (In the
1666  * above example we could theoretically suppress the a and b targets and
1667  * pass down only c,d,a+b, but it's not really worth the trouble to
1668  * eliminate simple var references from the subplan.  We will avoid doing
1669  * the extra computation to recompute a+b at the outer level; see
1670  * replace_vars_with_subplan_refs() in setrefs.c.)
1671  *
1672  * 'parse' is the query being processed.
1673  * 'tlist' is the query's target list.
1674  * 'groupColIdx' receives an array of column numbers for the GROUP BY
1675  * expressions (if there are any) in the subplan's target list.
1676  *
1677  * The result is the targetlist to be passed to the subplan.
1678  *---------------
1679  */
1680 static List *
1681 make_subplanTargetList(Query *parse,
1682                                            List *tlist,
1683                                            AttrNumber **groupColIdx)
1684 {
1685         List       *sub_tlist;
1686         List       *extravars;
1687         int                     numCols;
1688
1689         *groupColIdx = NULL;
1690
1691         /*
1692          * If we're not grouping or aggregating, nothing to do here;
1693          * query_planner should receive the unmodified target list.
1694          */
1695         if (!parse->hasAggs && !parse->groupClause && !parse->havingQual)
1696                 return tlist;
1697
1698         /*
1699          * Otherwise, start with a "flattened" tlist (having just the vars
1700          * mentioned in the targetlist and HAVING qual --- but not upper-
1701          * level Vars; they will be replaced by Params later on).
1702          */
1703         sub_tlist = flatten_tlist(tlist);
1704         extravars = pull_var_clause(parse->havingQual, false);
1705         sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1706         freeList(extravars);
1707
1708         /*
1709          * If grouping, create sub_tlist entries for all GROUP BY expressions
1710          * (GROUP BY items that are simple Vars should be in the list
1711          * already), and make an array showing where the group columns are in
1712          * the sub_tlist.
1713          */
1714         numCols = length(parse->groupClause);
1715         if (numCols > 0)
1716         {
1717                 int                     keyno = 0;
1718                 AttrNumber *grpColIdx;
1719                 List       *gl;
1720
1721                 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1722                 *groupColIdx = grpColIdx;
1723
1724                 foreach(gl, parse->groupClause)
1725                 {
1726                         GroupClause *grpcl = (GroupClause *) lfirst(gl);
1727                         Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1728                         TargetEntry *te = NULL;
1729                         List       *sl;
1730
1731                         /* Find or make a matching sub_tlist entry */
1732                         foreach(sl, sub_tlist)
1733                         {
1734                                 te = (TargetEntry *) lfirst(sl);
1735                                 if (equal(groupexpr, te->expr))
1736                                         break;
1737                         }
1738                         if (!sl)
1739                         {
1740                                 te = makeTargetEntry(makeResdom(length(sub_tlist) + 1,
1741                                                                                                 exprType(groupexpr),
1742                                                                                                 exprTypmod(groupexpr),
1743                                                                                                 NULL,
1744                                                                                                 false),
1745                                                                          (Expr *) groupexpr);
1746                                 sub_tlist = lappend(sub_tlist, te);
1747                         }
1748
1749                         /* and save its resno */
1750                         grpColIdx[keyno++] = te->resdom->resno;
1751                 }
1752         }
1753
1754         return sub_tlist;
1755 }
1756
1757 /*
1758  * make_groupsortplan
1759  *              Add a Sort node to explicitly sort according to the GROUP BY clause.
1760  *
1761  * Note: the Sort node always just takes a copy of the subplan's tlist
1762  * plus ordering information.  (This might seem inefficient if the
1763  * subplan contains complex GROUP BY expressions, but in fact Sort
1764  * does not evaluate its targetlist --- it only outputs the same
1765  * tuples in a new order.  So the expressions we might be copying
1766  * are just dummies with no extra execution cost.)
1767  */
1768 static Plan *
1769 make_groupsortplan(Query *parse,
1770                                    List *groupClause,
1771                                    AttrNumber *grpColIdx,
1772                                    Plan *subplan)
1773 {
1774         List       *sort_tlist = new_unsorted_tlist(subplan->targetlist);
1775         int                     keyno = 0;
1776         List       *gl;
1777
1778         foreach(gl, groupClause)
1779         {
1780                 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1781                 TargetEntry *te = nth(grpColIdx[keyno] - 1, sort_tlist);
1782                 Resdom     *resdom = te->resdom;
1783
1784                 /*
1785                  * Check for the possibility of duplicate group-by clauses ---
1786                  * the parser should have removed 'em, but the Sort executor
1787                  * will get terribly confused if any get through!
1788                  */
1789                 if (resdom->reskey == 0)
1790                 {
1791                         /* OK, insert the ordering info needed by the executor. */
1792                         resdom->reskey = ++keyno;
1793                         resdom->reskeyop = grpcl->sortop;
1794                 }
1795         }
1796
1797         Assert(keyno > 0);
1798
1799         return (Plan *) make_sort(parse, sort_tlist, subplan, keyno);
1800 }
1801
1802 /*
1803  * make_sortplan
1804  *        Add a Sort node to implement an explicit ORDER BY clause.
1805  */
1806 Plan *
1807 make_sortplan(Query *parse, List *tlist, Plan *plannode, List *sortcls)
1808 {
1809         List       *sort_tlist;
1810         List       *i;
1811         int                     keyno = 0;
1812
1813         /*
1814          * First make a copy of the tlist so that we don't corrupt the
1815          * original.
1816          */
1817         sort_tlist = new_unsorted_tlist(tlist);
1818
1819         foreach(i, sortcls)
1820         {
1821                 SortClause *sortcl = (SortClause *) lfirst(i);
1822                 TargetEntry *tle = get_sortgroupclause_tle(sortcl, sort_tlist);
1823                 Resdom     *resdom = tle->resdom;
1824
1825                 /*
1826                  * Check for the possibility of duplicate order-by clauses --- the
1827                  * parser should have removed 'em, but the executor will get
1828                  * terribly confused if any get through!
1829                  */
1830                 if (resdom->reskey == 0)
1831                 {
1832                         /* OK, insert the ordering info needed by the executor. */
1833                         resdom->reskey = ++keyno;
1834                         resdom->reskeyop = sortcl->sortop;
1835                 }
1836         }
1837
1838         Assert(keyno > 0);
1839
1840         return (Plan *) make_sort(parse, sort_tlist, plannode, keyno);
1841 }
1842
1843 /*
1844  * postprocess_setop_tlist
1845  *        Fix up targetlist returned by plan_set_operations().
1846  *
1847  * We need to transpose sort key info from the orig_tlist into new_tlist.
1848  * NOTE: this would not be good enough if we supported resjunk sort keys
1849  * for results of set operations --- then, we'd need to project a whole
1850  * new tlist to evaluate the resjunk columns.  For now, just elog if we
1851  * find any resjunk columns in orig_tlist.
1852  */
1853 static List *
1854 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1855 {
1856         List       *l;
1857
1858         foreach(l, new_tlist)
1859         {
1860                 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1861                 TargetEntry *orig_tle;
1862
1863                 /* ignore resjunk columns in setop result */
1864                 if (new_tle->resdom->resjunk)
1865                         continue;
1866
1867                 Assert(orig_tlist != NIL);
1868                 orig_tle = (TargetEntry *) lfirst(orig_tlist);
1869                 orig_tlist = lnext(orig_tlist);
1870                 if (orig_tle->resdom->resjunk)
1871                         elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");
1872                 Assert(new_tle->resdom->resno == orig_tle->resdom->resno);
1873                 Assert(new_tle->resdom->restype == orig_tle->resdom->restype);
1874                 new_tle->resdom->ressortgroupref = orig_tle->resdom->ressortgroupref;
1875         }
1876         if (orig_tlist != NIL)
1877                 elog(ERROR, "postprocess_setop_tlist: resjunk output columns not implemented");
1878         return new_tlist;
1879 }