]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/planner.c
Repair two constraint-exclusion corner cases triggered by proving that an
[postgresql] / src / backend / optimizer / plan / planner.c
1 /*-------------------------------------------------------------------------
2  *
3  * planner.c
4  *        The query optimizer external interface.
5  *
6  * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/optimizer/plan/planner.c,v 1.221 2007/05/26 18:23:01 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
18 #include <limits.h>
19
20 #include "catalog/pg_operator.h"
21 #include "executor/executor.h"
22 #include "executor/nodeAgg.h"
23 #include "miscadmin.h"
24 #include "nodes/makefuncs.h"
25 #include "optimizer/clauses.h"
26 #include "optimizer/cost.h"
27 #include "optimizer/pathnode.h"
28 #include "optimizer/paths.h"
29 #include "optimizer/planmain.h"
30 #include "optimizer/planner.h"
31 #include "optimizer/prep.h"
32 #include "optimizer/subselect.h"
33 #include "optimizer/tlist.h"
34 #include "optimizer/var.h"
35 #ifdef OPTIMIZER_DEBUG
36 #include "nodes/print.h"
37 #endif
38 #include "parser/parse_expr.h"
39 #include "parser/parse_oper.h"
40 #include "parser/parsetree.h"
41 #include "utils/lsyscache.h"
42 #include "utils/syscache.h"
43
44
45 /* Hook for plugins to get control in planner() */
46 planner_hook_type planner_hook = NULL;
47
48
49 /* Expression kind codes for preprocess_expression */
50 #define EXPRKIND_QUAL           0
51 #define EXPRKIND_TARGET         1
52 #define EXPRKIND_RTFUNC         2
53 #define EXPRKIND_VALUES         3
54 #define EXPRKIND_LIMIT          4
55 #define EXPRKIND_ININFO         5
56 #define EXPRKIND_APPINFO        6
57
58
59 static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
60 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
61 static Plan *inheritance_planner(PlannerInfo *root);
62 static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
63 static bool is_dummy_plan(Plan *plan);
64 static double preprocess_limit(PlannerInfo *root,
65                                  double tuple_fraction,
66                                  int64 *offset_est, int64 *count_est);
67 static Oid *extract_grouping_ops(List *groupClause);
68 static bool choose_hashed_grouping(PlannerInfo *root,
69                                            double tuple_fraction, double limit_tuples,
70                                            Path *cheapest_path, Path *sorted_path,
71                                            Oid *groupOperators, double dNumGroups,
72                                            AggClauseCounts *agg_counts);
73 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
74                                            AttrNumber **groupColIdx, bool *need_tlist_eval);
75 static void locate_grouping_columns(PlannerInfo *root,
76                                                 List *tlist,
77                                                 List *sub_tlist,
78                                                 AttrNumber *groupColIdx);
79 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
80
81
82 /*****************************************************************************
83  *
84  *         Query optimizer entry point
85  *
86  * To support loadable plugins that monitor or modify planner behavior,
87  * we provide a hook variable that lets a plugin get control before and
88  * after the standard planning process.  The plugin would normally call
89  * standard_planner().
90  *
91  * Note to plugin authors: standard_planner() scribbles on its Query input,
92  * so you'd better copy that data structure if you want to plan more than once.
93  *
94  *****************************************************************************/
95 PlannedStmt *
96 planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
97 {
98         PlannedStmt *result;
99
100         if (planner_hook)
101                 result = (*planner_hook) (parse, cursorOptions, boundParams);
102         else
103                 result = standard_planner(parse, cursorOptions, boundParams);
104         return result;
105 }
106
107 PlannedStmt *
108 standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
109 {
110         PlannedStmt *result;
111         PlannerGlobal *glob;
112         double          tuple_fraction;
113         PlannerInfo *root;
114         Plan       *top_plan;
115         ListCell   *lp,
116                            *lr;
117
118         /* Cursor options may come from caller or from DECLARE CURSOR stmt */
119         if (parse->utilityStmt &&
120                 IsA(parse->utilityStmt, DeclareCursorStmt))
121                 cursorOptions |= ((DeclareCursorStmt *) parse->utilityStmt)->options;
122
123         /*
124          * Set up global state for this planner invocation.  This data is needed
125          * across all levels of sub-Query that might exist in the given command,
126          * so we keep it in a separate struct that's linked to by each per-Query
127          * PlannerInfo.
128          */
129         glob = makeNode(PlannerGlobal);
130
131         glob->boundParams = boundParams;
132         glob->paramlist = NIL;
133         glob->subplans = NIL;
134         glob->subrtables = NIL;
135         glob->rewindPlanIDs = NULL;
136         glob->finalrtable = NIL;
137
138         /* Determine what fraction of the plan is likely to be scanned */
139         if (cursorOptions & CURSOR_OPT_FAST_PLAN)
140         {
141                 /*
142                  * We have no real idea how many tuples the user will ultimately FETCH
143                  * from a cursor, but it seems a good bet that he doesn't want 'em
144                  * all.  Optimize for 10% retrieval (you gotta better number?  Should
145                  * this be a SETtable parameter?)
146                  */
147                 tuple_fraction = 0.10;
148         }
149         else
150         {
151                 /* Default assumption is we need all the tuples */
152                 tuple_fraction = 0.0;
153         }
154
155         /* primary planning entry point (may recurse for subqueries) */
156         top_plan = subquery_planner(glob, parse, 1, tuple_fraction, &root);
157
158         /*
159          * If creating a plan for a scrollable cursor, make sure it can run
160          * backwards on demand.  Add a Material node at the top at need.
161          */
162         if (cursorOptions & CURSOR_OPT_SCROLL)
163         {
164                 if (!ExecSupportsBackwardScan(top_plan))
165                         top_plan = materialize_finished_plan(top_plan);
166         }
167
168         /* final cleanup of the plan */
169         Assert(glob->finalrtable == NIL);
170         top_plan = set_plan_references(glob, top_plan, root->parse->rtable);
171         /* ... and the subplans (both regular subplans and initplans) */
172         Assert(list_length(glob->subplans) == list_length(glob->subrtables));
173         forboth(lp, glob->subplans, lr, glob->subrtables)
174         {
175                 Plan   *subplan = (Plan *) lfirst(lp);
176                 List   *subrtable = (List *) lfirst(lr);
177
178                 lfirst(lp) = set_plan_references(glob, subplan, subrtable);
179         }
180
181         /* build the PlannedStmt result */
182         result = makeNode(PlannedStmt);
183
184         result->commandType = parse->commandType;
185         result->canSetTag = parse->canSetTag;
186         result->planTree = top_plan;
187         result->rtable = glob->finalrtable;
188         result->resultRelations = root->resultRelations;
189         result->utilityStmt = parse->utilityStmt;
190         result->intoClause = parse->intoClause;
191         result->subplans = glob->subplans;
192         result->rewindPlanIDs = glob->rewindPlanIDs;
193         result->returningLists = root->returningLists;
194         result->rowMarks = parse->rowMarks;
195         result->nParamExec = list_length(glob->paramlist);
196
197         return result;
198 }
199
200
201 /*--------------------
202  * subquery_planner
203  *        Invokes the planner on a subquery.  We recurse to here for each
204  *        sub-SELECT found in the query tree.
205  *
206  * glob is the global state for the current planner run.
207  * parse is the querytree produced by the parser & rewriter.
208  * level is the current recursion depth (1 at the top-level Query).
209  * tuple_fraction is the fraction of tuples we expect will be retrieved.
210  * tuple_fraction is interpreted as explained for grouping_planner, below.
211  *
212  * If subroot isn't NULL, we pass back the query's final PlannerInfo struct;
213  * among other things this tells the output sort ordering of the plan.
214  *
215  * Basically, this routine does the stuff that should only be done once
216  * per Query object.  It then calls grouping_planner.  At one time,
217  * grouping_planner could be invoked recursively on the same Query object;
218  * that's not currently true, but we keep the separation between the two
219  * routines anyway, in case we need it again someday.
220  *
221  * subquery_planner will be called recursively to handle sub-Query nodes
222  * found within the query's expressions and rangetable.
223  *
224  * Returns a query plan.
225  *--------------------
226  */
227 Plan *
228 subquery_planner(PlannerGlobal *glob, Query *parse,
229                                  Index level, double tuple_fraction,
230                                  PlannerInfo **subroot)
231 {
232         int                     num_old_subplans = list_length(glob->subplans);
233         PlannerInfo *root;
234         Plan       *plan;
235         List       *newHaving;
236         ListCell   *l;
237
238         /* Create a PlannerInfo data structure for this subquery */
239         root = makeNode(PlannerInfo);
240         root->parse = parse;
241         root->glob = glob;
242         root->query_level = level;
243         root->planner_cxt = CurrentMemoryContext;
244         root->init_plans = NIL;
245         root->eq_classes = NIL;
246         root->in_info_list = NIL;
247         root->append_rel_list = NIL;
248
249         /*
250          * Look for IN clauses at the top level of WHERE, and transform them into
251          * joins.  Note that this step only handles IN clauses originally at top
252          * level of WHERE; if we pull up any subqueries in the next step, their
253          * INs are processed just before pulling them up.
254          */
255         if (parse->hasSubLinks)
256                 parse->jointree->quals = pull_up_IN_clauses(root,
257                                                                                                         parse->jointree->quals);
258
259         /*
260          * Check to see if any subqueries in the rangetable can be merged into
261          * this query.
262          */
263         parse->jointree = (FromExpr *)
264                 pull_up_subqueries(root, (Node *) parse->jointree, false, false);
265
266         /*
267          * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
268          * avoid the expense of doing flatten_join_alias_vars().  Also check for
269          * outer joins --- if none, we can skip reduce_outer_joins() and some
270          * other processing.  This must be done after we have done
271          * pull_up_subqueries, of course.
272          *
273          * Note: if reduce_outer_joins manages to eliminate all outer joins,
274          * root->hasOuterJoins is not reset currently.  This is OK since its
275          * purpose is merely to suppress unnecessary processing in simple cases.
276          */
277         root->hasJoinRTEs = false;
278         root->hasOuterJoins = false;
279         foreach(l, parse->rtable)
280         {
281                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
282
283                 if (rte->rtekind == RTE_JOIN)
284                 {
285                         root->hasJoinRTEs = true;
286                         if (IS_OUTER_JOIN(rte->jointype))
287                         {
288                                 root->hasOuterJoins = true;
289                                 /* Can quit scanning once we find an outer join */
290                                 break;
291                         }
292                 }
293         }
294
295         /*
296          * Expand any rangetable entries that are inheritance sets into "append
297          * relations".  This can add entries to the rangetable, but they must be
298          * plain base relations not joins, so it's OK (and marginally more
299          * efficient) to do it after checking for join RTEs.  We must do it after
300          * pulling up subqueries, else we'd fail to handle inherited tables in
301          * subqueries.
302          */
303         expand_inherited_tables(root);
304
305         /*
306          * Set hasHavingQual to remember if HAVING clause is present.  Needed
307          * because preprocess_expression will reduce a constant-true condition to
308          * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
309          */
310         root->hasHavingQual = (parse->havingQual != NULL);
311
312         /* Clear this flag; might get set in distribute_qual_to_rels */
313         root->hasPseudoConstantQuals = false;
314
315         /*
316          * Do expression preprocessing on targetlist and quals.
317          */
318         parse->targetList = (List *)
319                 preprocess_expression(root, (Node *) parse->targetList,
320                                                           EXPRKIND_TARGET);
321
322         parse->returningList = (List *)
323                 preprocess_expression(root, (Node *) parse->returningList,
324                                                           EXPRKIND_TARGET);
325
326         preprocess_qual_conditions(root, (Node *) parse->jointree);
327
328         parse->havingQual = preprocess_expression(root, parse->havingQual,
329                                                                                           EXPRKIND_QUAL);
330
331         parse->limitOffset = preprocess_expression(root, parse->limitOffset,
332                                                                                            EXPRKIND_LIMIT);
333         parse->limitCount = preprocess_expression(root, parse->limitCount,
334                                                                                           EXPRKIND_LIMIT);
335
336         root->in_info_list = (List *)
337                 preprocess_expression(root, (Node *) root->in_info_list,
338                                                           EXPRKIND_ININFO);
339         root->append_rel_list = (List *)
340                 preprocess_expression(root, (Node *) root->append_rel_list,
341                                                           EXPRKIND_APPINFO);
342
343         /* Also need to preprocess expressions for function and values RTEs */
344         foreach(l, parse->rtable)
345         {
346                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
347
348                 if (rte->rtekind == RTE_FUNCTION)
349                         rte->funcexpr = preprocess_expression(root, rte->funcexpr,
350                                                                                                   EXPRKIND_RTFUNC);
351                 else if (rte->rtekind == RTE_VALUES)
352                         rte->values_lists = (List *)
353                                 preprocess_expression(root, (Node *) rte->values_lists,
354                                                                           EXPRKIND_VALUES);
355         }
356
357         /*
358          * In some cases we may want to transfer a HAVING clause into WHERE. We
359          * cannot do so if the HAVING clause contains aggregates (obviously) or
360          * volatile functions (since a HAVING clause is supposed to be executed
361          * only once per group).  Also, it may be that the clause is so expensive
362          * to execute that we're better off doing it only once per group, despite
363          * the loss of selectivity.  This is hard to estimate short of doing the
364          * entire planning process twice, so we use a heuristic: clauses
365          * containing subplans are left in HAVING.      Otherwise, we move or copy the
366          * HAVING clause into WHERE, in hopes of eliminating tuples before
367          * aggregation instead of after.
368          *
369          * If the query has explicit grouping then we can simply move such a
370          * clause into WHERE; any group that fails the clause will not be in the
371          * output because none of its tuples will reach the grouping or
372          * aggregation stage.  Otherwise we must have a degenerate (variable-free)
373          * HAVING clause, which we put in WHERE so that query_planner() can use it
374          * in a gating Result node, but also keep in HAVING to ensure that we
375          * don't emit a bogus aggregated row. (This could be done better, but it
376          * seems not worth optimizing.)
377          *
378          * Note that both havingQual and parse->jointree->quals are in
379          * implicitly-ANDed-list form at this point, even though they are declared
380          * as Node *.
381          */
382         newHaving = NIL;
383         foreach(l, (List *) parse->havingQual)
384         {
385                 Node       *havingclause = (Node *) lfirst(l);
386
387                 if (contain_agg_clause(havingclause) ||
388                         contain_volatile_functions(havingclause) ||
389                         contain_subplans(havingclause))
390                 {
391                         /* keep it in HAVING */
392                         newHaving = lappend(newHaving, havingclause);
393                 }
394                 else if (parse->groupClause)
395                 {
396                         /* move it to WHERE */
397                         parse->jointree->quals = (Node *)
398                                 lappend((List *) parse->jointree->quals, havingclause);
399                 }
400                 else
401                 {
402                         /* put a copy in WHERE, keep it in HAVING */
403                         parse->jointree->quals = (Node *)
404                                 lappend((List *) parse->jointree->quals,
405                                                 copyObject(havingclause));
406                         newHaving = lappend(newHaving, havingclause);
407                 }
408         }
409         parse->havingQual = (Node *) newHaving;
410
411         /*
412          * If we have any outer joins, try to reduce them to plain inner joins.
413          * This step is most easily done after we've done expression
414          * preprocessing.
415          */
416         if (root->hasOuterJoins)
417                 reduce_outer_joins(root);
418
419         /*
420          * Do the main planning.  If we have an inherited target relation, that
421          * needs special processing, else go straight to grouping_planner.
422          */
423         if (parse->resultRelation &&
424                 rt_fetch(parse->resultRelation, parse->rtable)->inh)
425                 plan = inheritance_planner(root);
426         else
427                 plan = grouping_planner(root, tuple_fraction);
428
429         /*
430          * If any subplans were generated, or if we're inside a subplan, build
431          * initPlan list and extParam/allParam sets for plan nodes, and attach the
432          * initPlans to the top plan node.
433          */
434         if (list_length(glob->subplans) != num_old_subplans ||
435                 root->query_level > 1)
436                 SS_finalize_plan(root, plan);
437
438         /* Return internal info if caller wants it */
439         if (subroot)
440                 *subroot = root;
441
442         return plan;
443 }
444
445 /*
446  * preprocess_expression
447  *              Do subquery_planner's preprocessing work for an expression,
448  *              which can be a targetlist, a WHERE clause (including JOIN/ON
449  *              conditions), or a HAVING clause.
450  */
451 static Node *
452 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
453 {
454         /*
455          * Fall out quickly if expression is empty.  This occurs often enough to
456          * be worth checking.  Note that null->null is the correct conversion for
457          * implicit-AND result format, too.
458          */
459         if (expr == NULL)
460                 return NULL;
461
462         /*
463          * If the query has any join RTEs, replace join alias variables with
464          * base-relation variables. We must do this before sublink processing,
465          * else sublinks expanded out from join aliases wouldn't get processed. We
466          * can skip it in VALUES lists, however, since they can't contain any Vars
467          * at all.
468          */
469         if (root->hasJoinRTEs && kind != EXPRKIND_VALUES)
470                 expr = flatten_join_alias_vars(root, expr);
471
472         /*
473          * Simplify constant expressions.
474          *
475          * Note: this also flattens nested AND and OR expressions into N-argument
476          * form.  All processing of a qual expression after this point must be
477          * careful to maintain AND/OR flatness --- that is, do not generate a tree
478          * with AND directly under AND, nor OR directly under OR.
479          *
480          * Because this is a relatively expensive process, we skip it when the
481          * query is trivial, such as "SELECT 2+2;" or "INSERT ... VALUES()". The
482          * expression will only be evaluated once anyway, so no point in
483          * pre-simplifying; we can't execute it any faster than the executor can,
484          * and we will waste cycles copying the tree.  Notice however that we
485          * still must do it for quals (to get AND/OR flatness); and if we are in a
486          * subquery we should not assume it will be done only once.
487          *
488          * For VALUES lists we never do this at all, again on the grounds that we
489          * should optimize for one-time evaluation.
490          */
491         if (kind != EXPRKIND_VALUES &&
492                 (root->parse->jointree->fromlist != NIL ||
493                  kind == EXPRKIND_QUAL ||
494                  root->query_level > 1))
495                 expr = eval_const_expressions(expr);
496
497         /*
498          * If it's a qual or havingQual, canonicalize it.
499          */
500         if (kind == EXPRKIND_QUAL)
501         {
502                 expr = (Node *) canonicalize_qual((Expr *) expr);
503
504 #ifdef OPTIMIZER_DEBUG
505                 printf("After canonicalize_qual()\n");
506                 pprint(expr);
507 #endif
508         }
509
510         /* Expand SubLinks to SubPlans */
511         if (root->parse->hasSubLinks)
512                 expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
513
514         /*
515          * XXX do not insert anything here unless you have grokked the comments in
516          * SS_replace_correlation_vars ...
517          */
518
519         /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
520         if (root->query_level > 1)
521                 expr = SS_replace_correlation_vars(root, expr);
522
523         /*
524          * If it's a qual or havingQual, convert it to implicit-AND format. (We
525          * don't want to do this before eval_const_expressions, since the latter
526          * would be unable to simplify a top-level AND correctly. Also,
527          * SS_process_sublinks expects explicit-AND format.)
528          */
529         if (kind == EXPRKIND_QUAL)
530                 expr = (Node *) make_ands_implicit((Expr *) expr);
531
532         return expr;
533 }
534
535 /*
536  * preprocess_qual_conditions
537  *              Recursively scan the query's jointree and do subquery_planner's
538  *              preprocessing work on each qual condition found therein.
539  */
540 static void
541 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
542 {
543         if (jtnode == NULL)
544                 return;
545         if (IsA(jtnode, RangeTblRef))
546         {
547                 /* nothing to do here */
548         }
549         else if (IsA(jtnode, FromExpr))
550         {
551                 FromExpr   *f = (FromExpr *) jtnode;
552                 ListCell   *l;
553
554                 foreach(l, f->fromlist)
555                         preprocess_qual_conditions(root, lfirst(l));
556
557                 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
558         }
559         else if (IsA(jtnode, JoinExpr))
560         {
561                 JoinExpr   *j = (JoinExpr *) jtnode;
562
563                 preprocess_qual_conditions(root, j->larg);
564                 preprocess_qual_conditions(root, j->rarg);
565
566                 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
567         }
568         else
569                 elog(ERROR, "unrecognized node type: %d",
570                          (int) nodeTag(jtnode));
571 }
572
573 /*
574  * inheritance_planner
575  *        Generate a plan in the case where the result relation is an
576  *        inheritance set.
577  *
578  * We have to handle this case differently from cases where a source relation
579  * is an inheritance set. Source inheritance is expanded at the bottom of the
580  * plan tree (see allpaths.c), but target inheritance has to be expanded at
581  * the top.  The reason is that for UPDATE, each target relation needs a
582  * different targetlist matching its own column set.  Also, for both UPDATE
583  * and DELETE, the executor needs the Append plan node at the top, else it
584  * can't keep track of which table is the current target table.  Fortunately,
585  * the UPDATE/DELETE target can never be the nullable side of an outer join,
586  * so it's OK to generate the plan this way.
587  *
588  * Returns a query plan.
589  */
590 static Plan *
591 inheritance_planner(PlannerInfo *root)
592 {
593         Query      *parse = root->parse;
594         int                     parentRTindex = parse->resultRelation;
595         List       *subplans = NIL;
596         List       *resultRelations = NIL;
597         List       *returningLists = NIL;
598         List       *rtable = NIL;
599         List       *tlist = NIL;
600         PlannerInfo subroot;
601         ListCell   *l;
602
603         foreach(l, root->append_rel_list)
604         {
605                 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
606                 Plan       *subplan;
607
608                 /* append_rel_list contains all append rels; ignore others */
609                 if (appinfo->parent_relid != parentRTindex)
610                         continue;
611
612                 /*
613                  * Generate modified query with this rel as target.  We have to be
614                  * prepared to translate varnos in in_info_list as well as in the
615                  * Query proper.
616                  */
617                 memcpy(&subroot, root, sizeof(PlannerInfo));
618                 subroot.parse = (Query *)
619                         adjust_appendrel_attrs((Node *) parse,
620                                                                    appinfo);
621                 subroot.in_info_list = (List *)
622                         adjust_appendrel_attrs((Node *) root->in_info_list,
623                                                                    appinfo);
624                 subroot.init_plans = NIL;
625                 /* There shouldn't be any OJ info to translate, as yet */
626                 Assert(subroot.oj_info_list == NIL);
627
628                 /* Generate plan */
629                 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
630
631                 /*
632                  * If this child rel was excluded by constraint exclusion, exclude it
633                  * from the plan.
634                  */
635                 if (is_dummy_plan(subplan))
636                         continue;
637
638                 /* Save rtable and tlist from first rel for use below */
639                 if (subplans == NIL)
640                 {
641                         rtable = subroot.parse->rtable;
642                         tlist = subplan->targetlist;
643                 }
644
645                 subplans = lappend(subplans, subplan);
646
647                 /* Make sure any initplans from this rel get into the outer list */
648                 root->init_plans = list_concat(root->init_plans, subroot.init_plans);
649
650                 /* Build target-relations list for the executor */
651                 resultRelations = lappend_int(resultRelations, appinfo->child_relid);
652
653                 /* Build list of per-relation RETURNING targetlists */
654                 if (parse->returningList)
655                 {
656                         Assert(list_length(subroot.returningLists) == 1);
657                         returningLists = list_concat(returningLists,
658                                                                                  subroot.returningLists);
659                 }
660         }
661
662         root->resultRelations = resultRelations;
663         root->returningLists = returningLists;
664
665         /* Mark result as unordered (probably unnecessary) */
666         root->query_pathkeys = NIL;
667
668         /*
669          * If we managed to exclude every child rel, return a dummy plan
670          */
671         if (subplans == NIL)
672         {
673                 root->resultRelations = list_make1_int(parentRTindex);
674                 /* although dummy, it must have a valid tlist for executor */
675                 tlist = preprocess_targetlist(root, parse->targetList);
676                 return (Plan *) make_result(root,
677                                                                         tlist,
678                                                                         (Node *) list_make1(makeBoolConst(false,
679                                                                                                                                           false)),
680                                                                         NULL);
681         }
682
683         /*
684          * Planning might have modified the rangetable, due to changes of the
685          * Query structures inside subquery RTEs.  We have to ensure that this
686          * gets propagated back to the master copy.  But can't do this until we
687          * are done planning, because all the calls to grouping_planner need
688          * virgin sub-Queries to work from.  (We are effectively assuming that
689          * sub-Queries will get planned identically each time, or at least that
690          * the impacts on their rangetables will be the same each time.)
691          *
692          * XXX should clean this up someday
693          */
694         parse->rtable = rtable;
695
696         /* Suppress Append if there's only one surviving child rel */
697         if (list_length(subplans) == 1)
698                 return (Plan *) linitial(subplans);
699
700         return (Plan *) make_append(subplans, true, tlist);
701 }
702
703 /*--------------------
704  * grouping_planner
705  *        Perform planning steps related to grouping, aggregation, etc.
706  *        This primarily means adding top-level processing to the basic
707  *        query plan produced by query_planner.
708  *
709  * tuple_fraction is the fraction of tuples we expect will be retrieved
710  *
711  * tuple_fraction is interpreted as follows:
712  *        0: expect all tuples to be retrieved (normal case)
713  *        0 < tuple_fraction < 1: expect the given fraction of tuples available
714  *              from the plan to be retrieved
715  *        tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
716  *              expected to be retrieved (ie, a LIMIT specification)
717  *
718  * Returns a query plan.  Also, root->query_pathkeys is returned as the
719  * actual output ordering of the plan (in pathkey format).
720  *--------------------
721  */
722 static Plan *
723 grouping_planner(PlannerInfo *root, double tuple_fraction)
724 {
725         Query      *parse = root->parse;
726         List       *tlist = parse->targetList;
727         int64           offset_est = 0;
728         int64           count_est = 0;
729         double          limit_tuples = -1.0;
730         Plan       *result_plan;
731         List       *current_pathkeys;
732         List       *sort_pathkeys;
733         double          dNumGroups = 0;
734
735         /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
736         if (parse->limitCount || parse->limitOffset)
737         {
738                 tuple_fraction = preprocess_limit(root, tuple_fraction,
739                                                                                   &offset_est, &count_est);
740                 /*
741                  * If we have a known LIMIT, and don't have an unknown OFFSET,
742                  * we can estimate the effects of using a bounded sort.
743                  */
744                 if (count_est > 0 && offset_est >= 0)
745                         limit_tuples = (double) count_est + (double) offset_est;
746         }
747
748         if (parse->setOperations)
749         {
750                 List       *set_sortclauses;
751
752                 /*
753                  * If there's a top-level ORDER BY, assume we have to fetch all the
754                  * tuples.      This might seem too simplistic given all the hackery below
755                  * to possibly avoid the sort ... but a nonzero tuple_fraction is only
756                  * of use to plan_set_operations() when the setop is UNION ALL, and
757                  * the result of UNION ALL is always unsorted.
758                  */
759                 if (parse->sortClause)
760                         tuple_fraction = 0.0;
761
762                 /*
763                  * Construct the plan for set operations.  The result will not need
764                  * any work except perhaps a top-level sort and/or LIMIT.
765                  */
766                 result_plan = plan_set_operations(root, tuple_fraction,
767                                                                                   &set_sortclauses);
768
769                 /*
770                  * Calculate pathkeys representing the sort order (if any) of the set
771                  * operation's result.  We have to do this before overwriting the sort
772                  * key information...
773                  */
774                 current_pathkeys = make_pathkeys_for_sortclauses(root,
775                                                                                                                  set_sortclauses,
776                                                                                                         result_plan->targetlist,
777                                                                                                                  true);
778
779                 /*
780                  * We should not need to call preprocess_targetlist, since we must be
781                  * in a SELECT query node.      Instead, use the targetlist returned by
782                  * plan_set_operations (since this tells whether it returned any
783                  * resjunk columns!), and transfer any sort key information from the
784                  * original tlist.
785                  */
786                 Assert(parse->commandType == CMD_SELECT);
787
788                 tlist = postprocess_setop_tlist(result_plan->targetlist, tlist);
789
790                 /*
791                  * Can't handle FOR UPDATE/SHARE here (parser should have checked
792                  * already, but let's make sure).
793                  */
794                 if (parse->rowMarks)
795                         ereport(ERROR,
796                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
797                                          errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
798
799                 /*
800                  * Calculate pathkeys that represent result ordering requirements
801                  */
802                 sort_pathkeys = make_pathkeys_for_sortclauses(root,
803                                                                                                           parse->sortClause,
804                                                                                                           tlist,
805                                                                                                           true);
806         }
807         else
808         {
809                 /* No set operations, do regular planning */
810                 List       *sub_tlist;
811                 List       *group_pathkeys;
812                 AttrNumber *groupColIdx = NULL;
813                 Oid                *groupOperators = NULL;
814                 bool            need_tlist_eval = true;
815                 QualCost        tlist_cost;
816                 Path       *cheapest_path;
817                 Path       *sorted_path;
818                 Path       *best_path;
819                 long            numGroups = 0;
820                 AggClauseCounts agg_counts;
821                 int                     numGroupCols = list_length(parse->groupClause);
822                 bool            use_hashed_grouping = false;
823
824                 MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
825
826                 /* Preprocess targetlist */
827                 tlist = preprocess_targetlist(root, tlist);
828
829                 /*
830                  * Generate appropriate target list for subplan; may be different from
831                  * tlist if grouping or aggregation is needed.
832                  */
833                 sub_tlist = make_subplanTargetList(root, tlist,
834                                                                                    &groupColIdx, &need_tlist_eval);
835
836                 /*
837                  * Calculate pathkeys that represent grouping/ordering requirements.
838                  * Stash them in PlannerInfo so that query_planner can canonicalize
839                  * them after EquivalenceClasses have been formed.
840                  */
841                 root->group_pathkeys =
842                         make_pathkeys_for_sortclauses(root,
843                                                                                   parse->groupClause,
844                                                                                   tlist,
845                                                                                   false);
846                 root->sort_pathkeys =
847                         make_pathkeys_for_sortclauses(root,
848                                                                                   parse->sortClause,
849                                                                                   tlist,
850                                                                                   false);
851
852                 /*
853                  * Will need actual number of aggregates for estimating costs.
854                  *
855                  * Note: we do not attempt to detect duplicate aggregates here; a
856                  * somewhat-overestimated count is okay for our present purposes.
857                  *
858                  * Note: think not that we can turn off hasAggs if we find no aggs. It
859                  * is possible for constant-expression simplification to remove all
860                  * explicit references to aggs, but we still have to follow the
861                  * aggregate semantics (eg, producing only one output row).
862                  */
863                 if (parse->hasAggs)
864                 {
865                         count_agg_clauses((Node *) tlist, &agg_counts);
866                         count_agg_clauses(parse->havingQual, &agg_counts);
867                 }
868
869                 /*
870                  * Figure out whether we need a sorted result from query_planner.
871                  *
872                  * If we have a GROUP BY clause, then we want a result sorted properly
873                  * for grouping.  Otherwise, if there is an ORDER BY clause, we want
874                  * to sort by the ORDER BY clause.      (Note: if we have both, and ORDER
875                  * BY is a superset of GROUP BY, it would be tempting to request sort
876                  * by ORDER BY --- but that might just leave us failing to exploit an
877                  * available sort order at all. Needs more thought...)
878                  */
879                 if (parse->groupClause)
880                         root->query_pathkeys = root->group_pathkeys;
881                 else if (parse->sortClause)
882                         root->query_pathkeys = root->sort_pathkeys;
883                 else
884                         root->query_pathkeys = NIL;
885
886                 /*
887                  * Generate the best unsorted and presorted paths for this Query (but
888                  * note there may not be any presorted path).  query_planner will also
889                  * estimate the number of groups in the query, and canonicalize all
890                  * the pathkeys.
891                  */
892                 query_planner(root, sub_tlist, tuple_fraction, limit_tuples,
893                                           &cheapest_path, &sorted_path, &dNumGroups);
894
895                 group_pathkeys = root->group_pathkeys;
896                 sort_pathkeys = root->sort_pathkeys;
897
898                 /*
899                  * If grouping, extract the grouping operators and decide whether we
900                  * want to use hashed grouping.
901                  */
902                 if (parse->groupClause)
903                 {
904                         groupOperators = extract_grouping_ops(parse->groupClause);
905                         use_hashed_grouping =
906                                 choose_hashed_grouping(root, tuple_fraction, limit_tuples,
907                                                                            cheapest_path, sorted_path,
908                                                                            groupOperators, dNumGroups,
909                                                                            &agg_counts);
910
911                         /* Also convert # groups to long int --- but 'ware overflow! */
912                         numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
913                 }
914
915                 /*
916                  * Select the best path.  If we are doing hashed grouping, we will
917                  * always read all the input tuples, so use the cheapest-total path.
918                  * Otherwise, trust query_planner's decision about which to use.
919                  */
920                 if (use_hashed_grouping || !sorted_path)
921                         best_path = cheapest_path;
922                 else
923                         best_path = sorted_path;
924
925                 /*
926                  * Check to see if it's possible to optimize MIN/MAX aggregates. If
927                  * so, we will forget all the work we did so far to choose a "regular"
928                  * path ... but we had to do it anyway to be able to tell which way is
929                  * cheaper.
930                  */
931                 result_plan = optimize_minmax_aggregates(root,
932                                                                                                  tlist,
933                                                                                                  best_path);
934                 if (result_plan != NULL)
935                 {
936                         /*
937                          * optimize_minmax_aggregates generated the full plan, with the
938                          * right tlist, and it has no sort order.
939                          */
940                         current_pathkeys = NIL;
941                 }
942                 else
943                 {
944                         /*
945                          * Normal case --- create a plan according to query_planner's
946                          * results.
947                          */
948                         result_plan = create_plan(root, best_path);
949                         current_pathkeys = best_path->pathkeys;
950
951                         /*
952                          * create_plan() returns a plan with just a "flat" tlist of
953                          * required Vars.  Usually we need to insert the sub_tlist as the
954                          * tlist of the top plan node.  However, we can skip that if we
955                          * determined that whatever query_planner chose to return will be
956                          * good enough.
957                          */
958                         if (need_tlist_eval)
959                         {
960                                 /*
961                                  * If the top-level plan node is one that cannot do expression
962                                  * evaluation, we must insert a Result node to project the
963                                  * desired tlist.
964                                  */
965                                 if (!is_projection_capable_plan(result_plan))
966                                 {
967                                         result_plan = (Plan *) make_result(root,
968                                                                                                            sub_tlist,
969                                                                                                            NULL,
970                                                                                                            result_plan);
971                                 }
972                                 else
973                                 {
974                                         /*
975                                          * Otherwise, just replace the subplan's flat tlist with
976                                          * the desired tlist.
977                                          */
978                                         result_plan->targetlist = sub_tlist;
979                                 }
980
981                                 /*
982                                  * Also, account for the cost of evaluation of the sub_tlist.
983                                  *
984                                  * Up to now, we have only been dealing with "flat" tlists,
985                                  * containing just Vars.  So their evaluation cost is zero
986                                  * according to the model used by cost_qual_eval() (or if you
987                                  * prefer, the cost is factored into cpu_tuple_cost).  Thus we
988                                  * can avoid accounting for tlist cost throughout
989                                  * query_planner() and subroutines.  But now we've inserted a
990                                  * tlist that might contain actual operators, sub-selects, etc
991                                  * --- so we'd better account for its cost.
992                                  *
993                                  * Below this point, any tlist eval cost for added-on nodes
994                                  * should be accounted for as we create those nodes.
995                                  * Presently, of the node types we can add on, only Agg and
996                                  * Group project new tlists (the rest just copy their input
997                                  * tuples) --- so make_agg() and make_group() are responsible
998                                  * for computing the added cost.
999                                  */
1000                                 cost_qual_eval(&tlist_cost, sub_tlist, root);
1001                                 result_plan->startup_cost += tlist_cost.startup;
1002                                 result_plan->total_cost += tlist_cost.startup +
1003                                         tlist_cost.per_tuple * result_plan->plan_rows;
1004                         }
1005                         else
1006                         {
1007                                 /*
1008                                  * Since we're using query_planner's tlist and not the one
1009                                  * make_subplanTargetList calculated, we have to refigure any
1010                                  * grouping-column indexes make_subplanTargetList computed.
1011                                  */
1012                                 locate_grouping_columns(root, tlist, result_plan->targetlist,
1013                                                                                 groupColIdx);
1014                         }
1015
1016                         /*
1017                          * Insert AGG or GROUP node if needed, plus an explicit sort step
1018                          * if necessary.
1019                          *
1020                          * HAVING clause, if any, becomes qual of the Agg or Group node.
1021                          */
1022                         if (use_hashed_grouping)
1023                         {
1024                                 /* Hashed aggregate plan --- no sort needed */
1025                                 result_plan = (Plan *) make_agg(root,
1026                                                                                                 tlist,
1027                                                                                                 (List *) parse->havingQual,
1028                                                                                                 AGG_HASHED,
1029                                                                                                 numGroupCols,
1030                                                                                                 groupColIdx,
1031                                                                                                 groupOperators,
1032                                                                                                 numGroups,
1033                                                                                                 agg_counts.numAggs,
1034                                                                                                 result_plan);
1035                                 /* Hashed aggregation produces randomly-ordered results */
1036                                 current_pathkeys = NIL;
1037                         }
1038                         else if (parse->hasAggs)
1039                         {
1040                                 /* Plain aggregate plan --- sort if needed */
1041                                 AggStrategy aggstrategy;
1042
1043                                 if (parse->groupClause)
1044                                 {
1045                                         if (!pathkeys_contained_in(group_pathkeys,
1046                                                                                            current_pathkeys))
1047                                         {
1048                                                 result_plan = (Plan *)
1049                                                         make_sort_from_groupcols(root,
1050                                                                                                          parse->groupClause,
1051                                                                                                          groupColIdx,
1052                                                                                                          result_plan);
1053                                                 current_pathkeys = group_pathkeys;
1054                                         }
1055                                         aggstrategy = AGG_SORTED;
1056
1057                                         /*
1058                                          * The AGG node will not change the sort ordering of its
1059                                          * groups, so current_pathkeys describes the result too.
1060                                          */
1061                                 }
1062                                 else
1063                                 {
1064                                         aggstrategy = AGG_PLAIN;
1065                                         /* Result will be only one row anyway; no sort order */
1066                                         current_pathkeys = NIL;
1067                                 }
1068
1069                                 result_plan = (Plan *) make_agg(root,
1070                                                                                                 tlist,
1071                                                                                                 (List *) parse->havingQual,
1072                                                                                                 aggstrategy,
1073                                                                                                 numGroupCols,
1074                                                                                                 groupColIdx,
1075                                                                                                 groupOperators,
1076                                                                                                 numGroups,
1077                                                                                                 agg_counts.numAggs,
1078                                                                                                 result_plan);
1079                         }
1080                         else if (parse->groupClause)
1081                         {
1082                                 /*
1083                                  * GROUP BY without aggregation, so insert a group node (plus
1084                                  * the appropriate sort node, if necessary).
1085                                  *
1086                                  * Add an explicit sort if we couldn't make the path come out
1087                                  * the way the GROUP node needs it.
1088                                  */
1089                                 if (!pathkeys_contained_in(group_pathkeys, current_pathkeys))
1090                                 {
1091                                         result_plan = (Plan *)
1092                                                 make_sort_from_groupcols(root,
1093                                                                                                  parse->groupClause,
1094                                                                                                  groupColIdx,
1095                                                                                                  result_plan);
1096                                         current_pathkeys = group_pathkeys;
1097                                 }
1098
1099                                 result_plan = (Plan *) make_group(root,
1100                                                                                                   tlist,
1101                                                                                                   (List *) parse->havingQual,
1102                                                                                                   numGroupCols,
1103                                                                                                   groupColIdx,
1104                                                                                                   groupOperators,
1105                                                                                                   dNumGroups,
1106                                                                                                   result_plan);
1107                                 /* The Group node won't change sort ordering */
1108                         }
1109                         else if (root->hasHavingQual)
1110                         {
1111                                 /*
1112                                  * No aggregates, and no GROUP BY, but we have a HAVING qual.
1113                                  * This is a degenerate case in which we are supposed to emit
1114                                  * either 0 or 1 row depending on whether HAVING succeeds.
1115                                  * Furthermore, there cannot be any variables in either HAVING
1116                                  * or the targetlist, so we actually do not need the FROM
1117                                  * table at all!  We can just throw away the plan-so-far and
1118                                  * generate a Result node.      This is a sufficiently unusual
1119                                  * corner case that it's not worth contorting the structure of
1120                                  * this routine to avoid having to generate the plan in the
1121                                  * first place.
1122                                  */
1123                                 result_plan = (Plan *) make_result(root,
1124                                                                                                    tlist,
1125                                                                                                    parse->havingQual,
1126                                                                                                    NULL);
1127                         }
1128                 }                                               /* end of non-minmax-aggregate case */
1129         }                                                       /* end of if (setOperations) */
1130
1131         /*
1132          * If we were not able to make the plan come out in the right order, add
1133          * an explicit sort step.
1134          */
1135         if (parse->sortClause)
1136         {
1137                 if (!pathkeys_contained_in(sort_pathkeys, current_pathkeys))
1138                 {
1139                         result_plan = (Plan *) make_sort_from_pathkeys(root,
1140                                                                                                                    result_plan,
1141                                                                                                                    sort_pathkeys,
1142                                                                                                                    limit_tuples);
1143                         current_pathkeys = sort_pathkeys;
1144                 }
1145         }
1146
1147         /*
1148          * If there is a DISTINCT clause, add the UNIQUE node.
1149          */
1150         if (parse->distinctClause)
1151         {
1152                 result_plan = (Plan *) make_unique(result_plan, parse->distinctClause);
1153
1154                 /*
1155                  * If there was grouping or aggregation, leave plan_rows as-is (ie,
1156                  * assume the result was already mostly unique).  If not, use the
1157                  * number of distinct-groups calculated by query_planner.
1158                  */
1159                 if (!parse->groupClause && !root->hasHavingQual && !parse->hasAggs)
1160                         result_plan->plan_rows = dNumGroups;
1161         }
1162
1163         /*
1164          * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1165          */
1166         if (parse->limitCount || parse->limitOffset)
1167         {
1168                 result_plan = (Plan *) make_limit(result_plan,
1169                                                                                   parse->limitOffset,
1170                                                                                   parse->limitCount,
1171                                                                                   offset_est,
1172                                                                                   count_est);
1173         }
1174
1175         /*
1176          * Deal with the RETURNING clause if any.  It's convenient to pass the
1177          * returningList through setrefs.c now rather than at top level (if we
1178          * waited, handling inherited UPDATE/DELETE would be much harder).
1179          */
1180         if (parse->returningList)
1181         {
1182                 List       *rlist;
1183
1184                 Assert(parse->resultRelation);
1185                 rlist = set_returning_clause_references(parse->returningList,
1186                                                                                                 result_plan,
1187                                                                                                 parse->resultRelation);
1188                 root->returningLists = list_make1(rlist);
1189         }
1190         else
1191                 root->returningLists = NIL;
1192
1193         /* Compute result-relations list if needed */
1194         if (parse->resultRelation)
1195                 root->resultRelations = list_make1_int(parse->resultRelation);
1196         else
1197                 root->resultRelations = NIL;
1198
1199         /*
1200          * Return the actual output ordering in query_pathkeys for possible use by
1201          * an outer query level.
1202          */
1203         root->query_pathkeys = current_pathkeys;
1204
1205         return result_plan;
1206 }
1207
1208 /*
1209  * Detect whether a plan node is a "dummy" plan created when a relation
1210  * is deemed not to need scanning due to constraint exclusion.
1211  *
1212  * Currently, such dummy plans are Result nodes with constant FALSE
1213  * filter quals.
1214  */
1215 static bool
1216 is_dummy_plan(Plan *plan)
1217 {
1218         if (IsA(plan, Result))
1219         {
1220                 List       *rcqual = (List *) ((Result *) plan)->resconstantqual;
1221
1222                 if (list_length(rcqual) == 1)
1223                 {
1224                         Const      *constqual = (Const *) linitial(rcqual);
1225
1226                         if (constqual && IsA(constqual, Const))
1227                         {
1228                                 if (!constqual->constisnull &&
1229                                         !DatumGetBool(constqual->constvalue))
1230                                         return true;
1231                         }
1232                 }
1233         }
1234         return false;
1235 }
1236
1237 /*
1238  * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1239  *
1240  * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1241  * results back in *count_est and *offset_est.  These variables are set to
1242  * 0 if the corresponding clause is not present, and -1 if it's present
1243  * but we couldn't estimate the value for it.  (The "0" convention is OK
1244  * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1245  * LIMIT 0 as though it were LIMIT 1.  But this is in line with the planner's
1246  * usual practice of never estimating less than one row.)  These values will
1247  * be passed to make_limit, which see if you change this code.
1248  *
1249  * The return value is the suitably adjusted tuple_fraction to use for
1250  * planning the query.  This adjustment is not overridable, since it reflects
1251  * plan actions that grouping_planner() will certainly take, not assumptions
1252  * about context.
1253  */
1254 static double
1255 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1256                                  int64 *offset_est, int64 *count_est)
1257 {
1258         Query      *parse = root->parse;
1259         Node       *est;
1260         double          limit_fraction;
1261
1262         /* Should not be called unless LIMIT or OFFSET */
1263         Assert(parse->limitCount || parse->limitOffset);
1264
1265         /*
1266          * Try to obtain the clause values.  We use estimate_expression_value
1267          * primarily because it can sometimes do something useful with Params.
1268          */
1269         if (parse->limitCount)
1270         {
1271                 est = estimate_expression_value(root, parse->limitCount);
1272                 if (est && IsA(est, Const))
1273                 {
1274                         if (((Const *) est)->constisnull)
1275                         {
1276                                 /* NULL indicates LIMIT ALL, ie, no limit */
1277                                 *count_est = 0; /* treat as not present */
1278                         }
1279                         else
1280                         {
1281                                 *count_est = DatumGetInt64(((Const *) est)->constvalue);
1282                                 if (*count_est <= 0)
1283                                         *count_est = 1;         /* force to at least 1 */
1284                         }
1285                 }
1286                 else
1287                         *count_est = -1;        /* can't estimate */
1288         }
1289         else
1290                 *count_est = 0;                 /* not present */
1291
1292         if (parse->limitOffset)
1293         {
1294                 est = estimate_expression_value(root, parse->limitOffset);
1295                 if (est && IsA(est, Const))
1296                 {
1297                         if (((Const *) est)->constisnull)
1298                         {
1299                                 /* Treat NULL as no offset; the executor will too */
1300                                 *offset_est = 0;        /* treat as not present */
1301                         }
1302                         else
1303                         {
1304                                 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
1305                                 if (*offset_est < 0)
1306                                         *offset_est = 0;        /* less than 0 is same as 0 */
1307                         }
1308                 }
1309                 else
1310                         *offset_est = -1;       /* can't estimate */
1311         }
1312         else
1313                 *offset_est = 0;                /* not present */
1314
1315         if (*count_est != 0)
1316         {
1317                 /*
1318                  * A LIMIT clause limits the absolute number of tuples returned.
1319                  * However, if it's not a constant LIMIT then we have to guess; for
1320                  * lack of a better idea, assume 10% of the plan's result is wanted.
1321                  */
1322                 if (*count_est < 0 || *offset_est < 0)
1323                 {
1324                         /* LIMIT or OFFSET is an expression ... punt ... */
1325                         limit_fraction = 0.10;
1326                 }
1327                 else
1328                 {
1329                         /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
1330                         limit_fraction = (double) *count_est + (double) *offset_est;
1331                 }
1332
1333                 /*
1334                  * If we have absolute limits from both caller and LIMIT, use the
1335                  * smaller value; likewise if they are both fractional.  If one is
1336                  * fractional and the other absolute, we can't easily determine which
1337                  * is smaller, but we use the heuristic that the absolute will usually
1338                  * be smaller.
1339                  */
1340                 if (tuple_fraction >= 1.0)
1341                 {
1342                         if (limit_fraction >= 1.0)
1343                         {
1344                                 /* both absolute */
1345                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
1346                         }
1347                         else
1348                         {
1349                                 /* caller absolute, limit fractional; use caller's value */
1350                         }
1351                 }
1352                 else if (tuple_fraction > 0.0)
1353                 {
1354                         if (limit_fraction >= 1.0)
1355                         {
1356                                 /* caller fractional, limit absolute; use limit */
1357                                 tuple_fraction = limit_fraction;
1358                         }
1359                         else
1360                         {
1361                                 /* both fractional */
1362                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
1363                         }
1364                 }
1365                 else
1366                 {
1367                         /* no info from caller, just use limit */
1368                         tuple_fraction = limit_fraction;
1369                 }
1370         }
1371         else if (*offset_est != 0 && tuple_fraction > 0.0)
1372         {
1373                 /*
1374                  * We have an OFFSET but no LIMIT.      This acts entirely differently
1375                  * from the LIMIT case: here, we need to increase rather than decrease
1376                  * the caller's tuple_fraction, because the OFFSET acts to cause more
1377                  * tuples to be fetched instead of fewer.  This only matters if we got
1378                  * a tuple_fraction > 0, however.
1379                  *
1380                  * As above, use 10% if OFFSET is present but unestimatable.
1381                  */
1382                 if (*offset_est < 0)
1383                         limit_fraction = 0.10;
1384                 else
1385                         limit_fraction = (double) *offset_est;
1386
1387                 /*
1388                  * If we have absolute counts from both caller and OFFSET, add them
1389                  * together; likewise if they are both fractional.      If one is
1390                  * fractional and the other absolute, we want to take the larger, and
1391                  * we heuristically assume that's the fractional one.
1392                  */
1393                 if (tuple_fraction >= 1.0)
1394                 {
1395                         if (limit_fraction >= 1.0)
1396                         {
1397                                 /* both absolute, so add them together */
1398                                 tuple_fraction += limit_fraction;
1399                         }
1400                         else
1401                         {
1402                                 /* caller absolute, limit fractional; use limit */
1403                                 tuple_fraction = limit_fraction;
1404                         }
1405                 }
1406                 else
1407                 {
1408                         if (limit_fraction >= 1.0)
1409                         {
1410                                 /* caller fractional, limit absolute; use caller's value */
1411                         }
1412                         else
1413                         {
1414                                 /* both fractional, so add them together */
1415                                 tuple_fraction += limit_fraction;
1416                                 if (tuple_fraction >= 1.0)
1417                                         tuple_fraction = 0.0;           /* assume fetch all */
1418                         }
1419                 }
1420         }
1421
1422         return tuple_fraction;
1423 }
1424
1425 /*
1426  * extract_grouping_ops - make an array of the equality operator OIDs
1427  *              for the GROUP BY clause
1428  */
1429 static Oid *
1430 extract_grouping_ops(List *groupClause)
1431 {
1432         int                     numCols = list_length(groupClause);
1433         int                     colno = 0;
1434         Oid                *groupOperators;
1435         ListCell   *glitem;
1436
1437         groupOperators = (Oid *) palloc(sizeof(Oid) * numCols);
1438
1439         foreach(glitem, groupClause)
1440         {
1441                 GroupClause *groupcl = (GroupClause *) lfirst(glitem);
1442
1443                 groupOperators[colno] = get_equality_op_for_ordering_op(groupcl->sortop);
1444                 if (!OidIsValid(groupOperators[colno]))         /* shouldn't happen */
1445                         elog(ERROR, "could not find equality operator for ordering operator %u",
1446                                  groupcl->sortop);
1447                 colno++;
1448         }
1449
1450         return groupOperators;
1451 }
1452
1453 /*
1454  * choose_hashed_grouping - should we use hashed grouping?
1455  */
1456 static bool
1457 choose_hashed_grouping(PlannerInfo *root,
1458                                            double tuple_fraction, double limit_tuples,
1459                                            Path *cheapest_path, Path *sorted_path,
1460                                            Oid *groupOperators, double dNumGroups,
1461                                            AggClauseCounts *agg_counts)
1462 {
1463         int                     numGroupCols = list_length(root->parse->groupClause);
1464         double          cheapest_path_rows;
1465         int                     cheapest_path_width;
1466         Size            hashentrysize;
1467         List       *current_pathkeys;
1468         Path            hashed_p;
1469         Path            sorted_p;
1470         int                     i;
1471
1472         /*
1473          * Check can't-do-it conditions, including whether the grouping operators
1474          * are hashjoinable.  (We assume hashing is OK if they are marked
1475          * oprcanhash.  If there isn't actually a supporting hash function,
1476          * the executor will complain at runtime.)
1477          *
1478          * Executor doesn't support hashed aggregation with DISTINCT aggregates.
1479          * (Doing so would imply storing *all* the input values in the hash table,
1480          * which seems like a certain loser.)
1481          */
1482         if (!enable_hashagg)
1483                 return false;
1484         if (agg_counts->numDistinctAggs != 0)
1485                 return false;
1486         for (i = 0; i < numGroupCols; i++)
1487         {
1488                 if (!op_hashjoinable(groupOperators[i]))
1489                         return false;
1490         }
1491
1492         /*
1493          * Don't do it if it doesn't look like the hashtable will fit into
1494          * work_mem.
1495          *
1496          * Beware here of the possibility that cheapest_path->parent is NULL. This
1497          * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
1498          */
1499         if (cheapest_path->parent)
1500         {
1501                 cheapest_path_rows = cheapest_path->parent->rows;
1502                 cheapest_path_width = cheapest_path->parent->width;
1503         }
1504         else
1505         {
1506                 cheapest_path_rows = 1; /* assume non-set result */
1507                 cheapest_path_width = 100;              /* arbitrary */
1508         }
1509
1510         /* Estimate per-hash-entry space at tuple width... */
1511         hashentrysize = MAXALIGN(cheapest_path_width) + MAXALIGN(sizeof(MinimalTupleData));
1512         /* plus space for pass-by-ref transition values... */
1513         hashentrysize += agg_counts->transitionSpace;
1514         /* plus the per-hash-entry overhead */
1515         hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
1516
1517         if (hashentrysize * dNumGroups > work_mem * 1024L)
1518                 return false;
1519
1520         /*
1521          * See if the estimated cost is no more than doing it the other way. While
1522          * avoiding the need for sorted input is usually a win, the fact that the
1523          * output won't be sorted may be a loss; so we need to do an actual cost
1524          * comparison.
1525          *
1526          * We need to consider cheapest_path + hashagg [+ final sort] versus
1527          * either cheapest_path [+ sort] + group or agg [+ final sort] or
1528          * presorted_path + group or agg [+ final sort] where brackets indicate a
1529          * step that may not be needed. We assume query_planner() will have
1530          * returned a presorted path only if it's a winner compared to
1531          * cheapest_path for this purpose.
1532          *
1533          * These path variables are dummies that just hold cost fields; we don't
1534          * make actual Paths for these steps.
1535          */
1536         cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
1537                          numGroupCols, dNumGroups,
1538                          cheapest_path->startup_cost, cheapest_path->total_cost,
1539                          cheapest_path_rows);
1540         /* Result of hashed agg is always unsorted */
1541         if (root->sort_pathkeys)
1542                 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
1543                                   dNumGroups, cheapest_path_width, limit_tuples);
1544
1545         if (sorted_path)
1546         {
1547                 sorted_p.startup_cost = sorted_path->startup_cost;
1548                 sorted_p.total_cost = sorted_path->total_cost;
1549                 current_pathkeys = sorted_path->pathkeys;
1550         }
1551         else
1552         {
1553                 sorted_p.startup_cost = cheapest_path->startup_cost;
1554                 sorted_p.total_cost = cheapest_path->total_cost;
1555                 current_pathkeys = cheapest_path->pathkeys;
1556         }
1557         if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1558         {
1559                 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
1560                                   cheapest_path_rows, cheapest_path_width, -1.0);
1561                 current_pathkeys = root->group_pathkeys;
1562         }
1563
1564         if (root->parse->hasAggs)
1565                 cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
1566                                  numGroupCols, dNumGroups,
1567                                  sorted_p.startup_cost, sorted_p.total_cost,
1568                                  cheapest_path_rows);
1569         else
1570                 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
1571                                    sorted_p.startup_cost, sorted_p.total_cost,
1572                                    cheapest_path_rows);
1573         /* The Agg or Group node will preserve ordering */
1574         if (root->sort_pathkeys &&
1575                 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1576                 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
1577                                   dNumGroups, cheapest_path_width, limit_tuples);
1578
1579         /*
1580          * Now make the decision using the top-level tuple fraction.  First we
1581          * have to convert an absolute count (LIMIT) into fractional form.
1582          */
1583         if (tuple_fraction >= 1.0)
1584                 tuple_fraction /= dNumGroups;
1585
1586         if (compare_fractional_path_costs(&hashed_p, &sorted_p,
1587                                                                           tuple_fraction) < 0)
1588         {
1589                 /* Hashed is cheaper, so use it */
1590                 return true;
1591         }
1592         return false;
1593 }
1594
1595 /*---------------
1596  * make_subplanTargetList
1597  *        Generate appropriate target list when grouping is required.
1598  *
1599  * When grouping_planner inserts Aggregate, Group, or Result plan nodes
1600  * above the result of query_planner, we typically want to pass a different
1601  * target list to query_planner than the outer plan nodes should have.
1602  * This routine generates the correct target list for the subplan.
1603  *
1604  * The initial target list passed from the parser already contains entries
1605  * for all ORDER BY and GROUP BY expressions, but it will not have entries
1606  * for variables used only in HAVING clauses; so we need to add those
1607  * variables to the subplan target list.  Also, we flatten all expressions
1608  * except GROUP BY items into their component variables; the other expressions
1609  * will be computed by the inserted nodes rather than by the subplan.
1610  * For example, given a query like
1611  *              SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
1612  * we want to pass this targetlist to the subplan:
1613  *              a,b,c,d,a+b
1614  * where the a+b target will be used by the Sort/Group steps, and the
1615  * other targets will be used for computing the final results.  (In the
1616  * above example we could theoretically suppress the a and b targets and
1617  * pass down only c,d,a+b, but it's not really worth the trouble to
1618  * eliminate simple var references from the subplan.  We will avoid doing
1619  * the extra computation to recompute a+b at the outer level; see
1620  * fix_upper_expr() in setrefs.c.)
1621  *
1622  * If we are grouping or aggregating, *and* there are no non-Var grouping
1623  * expressions, then the returned tlist is effectively dummy; we do not
1624  * need to force it to be evaluated, because all the Vars it contains
1625  * should be present in the output of query_planner anyway.
1626  *
1627  * 'tlist' is the query's target list.
1628  * 'groupColIdx' receives an array of column numbers for the GROUP BY
1629  *                      expressions (if there are any) in the subplan's target list.
1630  * 'need_tlist_eval' is set true if we really need to evaluate the
1631  *                      result tlist.
1632  *
1633  * The result is the targetlist to be passed to the subplan.
1634  *---------------
1635  */
1636 static List *
1637 make_subplanTargetList(PlannerInfo *root,
1638                                            List *tlist,
1639                                            AttrNumber **groupColIdx,
1640                                            bool *need_tlist_eval)
1641 {
1642         Query      *parse = root->parse;
1643         List       *sub_tlist;
1644         List       *extravars;
1645         int                     numCols;
1646
1647         *groupColIdx = NULL;
1648
1649         /*
1650          * If we're not grouping or aggregating, there's nothing to do here;
1651          * query_planner should receive the unmodified target list.
1652          */
1653         if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual)
1654         {
1655                 *need_tlist_eval = true;
1656                 return tlist;
1657         }
1658
1659         /*
1660          * Otherwise, start with a "flattened" tlist (having just the vars
1661          * mentioned in the targetlist and HAVING qual --- but not upper- level
1662          * Vars; they will be replaced by Params later on).
1663          */
1664         sub_tlist = flatten_tlist(tlist);
1665         extravars = pull_var_clause(parse->havingQual, false);
1666         sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
1667         list_free(extravars);
1668         *need_tlist_eval = false;       /* only eval if not flat tlist */
1669
1670         /*
1671          * If grouping, create sub_tlist entries for all GROUP BY expressions
1672          * (GROUP BY items that are simple Vars should be in the list already),
1673          * and make an array showing where the group columns are in the sub_tlist.
1674          */
1675         numCols = list_length(parse->groupClause);
1676         if (numCols > 0)
1677         {
1678                 int                     keyno = 0;
1679                 AttrNumber *grpColIdx;
1680                 ListCell   *gl;
1681
1682                 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
1683                 *groupColIdx = grpColIdx;
1684
1685                 foreach(gl, parse->groupClause)
1686                 {
1687                         GroupClause *grpcl = (GroupClause *) lfirst(gl);
1688                         Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1689                         TargetEntry *te = NULL;
1690                         ListCell   *sl;
1691
1692                         /* Find or make a matching sub_tlist entry */
1693                         foreach(sl, sub_tlist)
1694                         {
1695                                 te = (TargetEntry *) lfirst(sl);
1696                                 if (equal(groupexpr, te->expr))
1697                                         break;
1698                         }
1699                         if (!sl)
1700                         {
1701                                 te = makeTargetEntry((Expr *) groupexpr,
1702                                                                          list_length(sub_tlist) + 1,
1703                                                                          NULL,
1704                                                                          false);
1705                                 sub_tlist = lappend(sub_tlist, te);
1706                                 *need_tlist_eval = true;                /* it's not flat anymore */
1707                         }
1708
1709                         /* and save its resno */
1710                         grpColIdx[keyno++] = te->resno;
1711                 }
1712         }
1713
1714         return sub_tlist;
1715 }
1716
1717 /*
1718  * locate_grouping_columns
1719  *              Locate grouping columns in the tlist chosen by query_planner.
1720  *
1721  * This is only needed if we don't use the sub_tlist chosen by
1722  * make_subplanTargetList.      We have to forget the column indexes found
1723  * by that routine and re-locate the grouping vars in the real sub_tlist.
1724  */
1725 static void
1726 locate_grouping_columns(PlannerInfo *root,
1727                                                 List *tlist,
1728                                                 List *sub_tlist,
1729                                                 AttrNumber *groupColIdx)
1730 {
1731         int                     keyno = 0;
1732         ListCell   *gl;
1733
1734         /*
1735          * No work unless grouping.
1736          */
1737         if (!root->parse->groupClause)
1738         {
1739                 Assert(groupColIdx == NULL);
1740                 return;
1741         }
1742         Assert(groupColIdx != NULL);
1743
1744         foreach(gl, root->parse->groupClause)
1745         {
1746                 GroupClause *grpcl = (GroupClause *) lfirst(gl);
1747                 Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
1748                 TargetEntry *te = NULL;
1749                 ListCell   *sl;
1750
1751                 foreach(sl, sub_tlist)
1752                 {
1753                         te = (TargetEntry *) lfirst(sl);
1754                         if (equal(groupexpr, te->expr))
1755                                 break;
1756                 }
1757                 if (!sl)
1758                         elog(ERROR, "failed to locate grouping columns");
1759
1760                 groupColIdx[keyno++] = te->resno;
1761         }
1762 }
1763
1764 /*
1765  * postprocess_setop_tlist
1766  *        Fix up targetlist returned by plan_set_operations().
1767  *
1768  * We need to transpose sort key info from the orig_tlist into new_tlist.
1769  * NOTE: this would not be good enough if we supported resjunk sort keys
1770  * for results of set operations --- then, we'd need to project a whole
1771  * new tlist to evaluate the resjunk columns.  For now, just ereport if we
1772  * find any resjunk columns in orig_tlist.
1773  */
1774 static List *
1775 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
1776 {
1777         ListCell   *l;
1778         ListCell   *orig_tlist_item = list_head(orig_tlist);
1779
1780         foreach(l, new_tlist)
1781         {
1782                 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
1783                 TargetEntry *orig_tle;
1784
1785                 /* ignore resjunk columns in setop result */
1786                 if (new_tle->resjunk)
1787                         continue;
1788
1789                 Assert(orig_tlist_item != NULL);
1790                 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
1791                 orig_tlist_item = lnext(orig_tlist_item);
1792                 if (orig_tle->resjunk)  /* should not happen */
1793                         elog(ERROR, "resjunk output columns are not implemented");
1794                 Assert(new_tle->resno == orig_tle->resno);
1795                 new_tle->ressortgroupref = orig_tle->ressortgroupref;
1796         }
1797         if (orig_tlist_item != NULL)
1798                 elog(ERROR, "resjunk output columns are not implemented");
1799         return new_tlist;
1800 }