]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/planner.c
9aafc8adcc6bd5884925c6280c1b9d19904ea58e
[postgresql] / src / backend / optimizer / plan / planner.c
1 /*-------------------------------------------------------------------------
2  *
3  * planner.c
4  *        The query optimizer external interface.
5  *
6  * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/optimizer/plan/planner.c
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/plancat.h"
30 #include "optimizer/planmain.h"
31 #include "optimizer/planner.h"
32 #include "optimizer/prep.h"
33 #include "optimizer/subselect.h"
34 #include "optimizer/tlist.h"
35 #include "optimizer/var.h"
36 #ifdef OPTIMIZER_DEBUG
37 #include "nodes/print.h"
38 #endif
39 #include "parser/analyze.h"
40 #include "parser/parse_expr.h"
41 #include "parser/parse_oper.h"
42 #include "parser/parsetree.h"
43 #include "utils/lsyscache.h"
44 #include "utils/syscache.h"
45
46
47 /* GUC parameter */
48 double          cursor_tuple_fraction = DEFAULT_CURSOR_TUPLE_FRACTION;
49
50 /* Hook for plugins to get control in planner() */
51 planner_hook_type planner_hook = NULL;
52
53
54 /* Expression kind codes for preprocess_expression */
55 #define EXPRKIND_QUAL           0
56 #define EXPRKIND_TARGET         1
57 #define EXPRKIND_RTFUNC         2
58 #define EXPRKIND_VALUES         3
59 #define EXPRKIND_LIMIT          4
60 #define EXPRKIND_APPINFO        5
61
62
63 static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
64 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
65 static Plan *inheritance_planner(PlannerInfo *root);
66 static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
67 static bool is_dummy_plan(Plan *plan);
68 static void preprocess_rowmarks(PlannerInfo *root);
69 static double preprocess_limit(PlannerInfo *root,
70                                  double tuple_fraction,
71                                  int64 *offset_est, int64 *count_est);
72 static void preprocess_groupclause(PlannerInfo *root);
73 static bool choose_hashed_grouping(PlannerInfo *root,
74                                            double tuple_fraction, double limit_tuples,
75                                            double path_rows, int path_width,
76                                            Path *cheapest_path, Path *sorted_path,
77                                            double dNumGroups, AggClauseCosts *agg_costs);
78 static bool choose_hashed_distinct(PlannerInfo *root,
79                                            double tuple_fraction, double limit_tuples,
80                                            double path_rows, int path_width,
81                                            Cost cheapest_startup_cost, Cost cheapest_total_cost,
82                                            Cost sorted_startup_cost, Cost sorted_total_cost,
83                                            List *sorted_pathkeys,
84                                            double dNumDistinctRows);
85 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
86                                            AttrNumber **groupColIdx, bool *need_tlist_eval);
87 static void locate_grouping_columns(PlannerInfo *root,
88                                                 List *tlist,
89                                                 List *sub_tlist,
90                                                 AttrNumber *groupColIdx);
91 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
92 static List *select_active_windows(PlannerInfo *root, WindowFuncLists *wflists);
93 static List *add_volatile_sort_exprs(List *window_tlist, List *tlist,
94                                                 List *activeWindows);
95 static List *make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc,
96                                                  List *tlist, bool canonicalize);
97 static void get_column_info_for_window(PlannerInfo *root, WindowClause *wc,
98                                                    List *tlist,
99                                                    int numSortCols, AttrNumber *sortColIdx,
100                                                    int *partNumCols,
101                                                    AttrNumber **partColIdx,
102                                                    Oid **partOperators,
103                                                    int *ordNumCols,
104                                                    AttrNumber **ordColIdx,
105                                                    Oid **ordOperators);
106
107
108 /*****************************************************************************
109  *
110  *         Query optimizer entry point
111  *
112  * To support loadable plugins that monitor or modify planner behavior,
113  * we provide a hook variable that lets a plugin get control before and
114  * after the standard planning process.  The plugin would normally call
115  * standard_planner().
116  *
117  * Note to plugin authors: standard_planner() scribbles on its Query input,
118  * so you'd better copy that data structure if you want to plan more than once.
119  *
120  *****************************************************************************/
121 PlannedStmt *
122 planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
123 {
124         PlannedStmt *result;
125
126         if (planner_hook)
127                 result = (*planner_hook) (parse, cursorOptions, boundParams);
128         else
129                 result = standard_planner(parse, cursorOptions, boundParams);
130         return result;
131 }
132
133 PlannedStmt *
134 standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
135 {
136         PlannedStmt *result;
137         PlannerGlobal *glob;
138         double          tuple_fraction;
139         PlannerInfo *root;
140         Plan       *top_plan;
141         ListCell   *lp,
142                            *lrt,
143                            *lrm;
144
145         /* Cursor options may come from caller or from DECLARE CURSOR stmt */
146         if (parse->utilityStmt &&
147                 IsA(parse->utilityStmt, DeclareCursorStmt))
148                 cursorOptions |= ((DeclareCursorStmt *) parse->utilityStmt)->options;
149
150         /*
151          * Set up global state for this planner invocation.  This data is needed
152          * across all levels of sub-Query that might exist in the given command,
153          * so we keep it in a separate struct that's linked to by each per-Query
154          * PlannerInfo.
155          */
156         glob = makeNode(PlannerGlobal);
157
158         glob->boundParams = boundParams;
159         glob->paramlist = NIL;
160         glob->subplans = NIL;
161         glob->subrtables = NIL;
162         glob->subrowmarks = NIL;
163         glob->rewindPlanIDs = NULL;
164         glob->finalrtable = NIL;
165         glob->finalrowmarks = NIL;
166         glob->resultRelations = NIL;
167         glob->relationOids = NIL;
168         glob->invalItems = NIL;
169         glob->lastPHId = 0;
170         glob->lastRowMarkId = 0;
171         glob->transientPlan = false;
172
173         /* Determine what fraction of the plan is likely to be scanned */
174         if (cursorOptions & CURSOR_OPT_FAST_PLAN)
175         {
176                 /*
177                  * We have no real idea how many tuples the user will ultimately FETCH
178                  * from a cursor, but it is often the case that he doesn't want 'em
179                  * all, or would prefer a fast-start plan anyway so that he can
180                  * process some of the tuples sooner.  Use a GUC parameter to decide
181                  * what fraction to optimize for.
182                  */
183                 tuple_fraction = cursor_tuple_fraction;
184
185                 /*
186                  * We document cursor_tuple_fraction as simply being a fraction, which
187                  * means the edge cases 0 and 1 have to be treated specially here.      We
188                  * convert 1 to 0 ("all the tuples") and 0 to a very small fraction.
189                  */
190                 if (tuple_fraction >= 1.0)
191                         tuple_fraction = 0.0;
192                 else if (tuple_fraction <= 0.0)
193                         tuple_fraction = 1e-10;
194         }
195         else
196         {
197                 /* Default assumption is we need all the tuples */
198                 tuple_fraction = 0.0;
199         }
200
201         /* primary planning entry point (may recurse for subqueries) */
202         top_plan = subquery_planner(glob, parse, NULL,
203                                                                 false, tuple_fraction, &root);
204
205         /*
206          * If creating a plan for a scrollable cursor, make sure it can run
207          * backwards on demand.  Add a Material node at the top at need.
208          */
209         if (cursorOptions & CURSOR_OPT_SCROLL)
210         {
211                 if (!ExecSupportsBackwardScan(top_plan))
212                         top_plan = materialize_finished_plan(top_plan);
213         }
214
215         /* final cleanup of the plan */
216         Assert(glob->finalrtable == NIL);
217         Assert(glob->finalrowmarks == NIL);
218         Assert(glob->resultRelations == NIL);
219         top_plan = set_plan_references(glob, top_plan,
220                                                                    root->parse->rtable,
221                                                                    root->rowMarks);
222         /* ... and the subplans (both regular subplans and initplans) */
223         Assert(list_length(glob->subplans) == list_length(glob->subrtables));
224         Assert(list_length(glob->subplans) == list_length(glob->subrowmarks));
225         lrt = list_head(glob->subrtables);
226         lrm = list_head(glob->subrowmarks);
227         foreach(lp, glob->subplans)
228         {
229                 Plan       *subplan = (Plan *) lfirst(lp);
230                 List       *subrtable = (List *) lfirst(lrt);
231                 List       *subrowmark = (List *) lfirst(lrm);
232
233                 lfirst(lp) = set_plan_references(glob, subplan,
234                                                                                  subrtable, subrowmark);
235                 lrt = lnext(lrt);
236                 lrm = lnext(lrm);
237         }
238
239         /* build the PlannedStmt result */
240         result = makeNode(PlannedStmt);
241
242         result->commandType = parse->commandType;
243         result->hasReturning = (parse->returningList != NIL);
244         result->hasModifyingCTE = parse->hasModifyingCTE;
245         result->canSetTag = parse->canSetTag;
246         result->transientPlan = glob->transientPlan;
247         result->planTree = top_plan;
248         result->rtable = glob->finalrtable;
249         result->resultRelations = glob->resultRelations;
250         result->utilityStmt = parse->utilityStmt;
251         result->intoClause = parse->intoClause;
252         result->subplans = glob->subplans;
253         result->rewindPlanIDs = glob->rewindPlanIDs;
254         result->rowMarks = glob->finalrowmarks;
255         result->relationOids = glob->relationOids;
256         result->invalItems = glob->invalItems;
257         result->nParamExec = list_length(glob->paramlist);
258
259         return result;
260 }
261
262
263 /*--------------------
264  * subquery_planner
265  *        Invokes the planner on a subquery.  We recurse to here for each
266  *        sub-SELECT found in the query tree.
267  *
268  * glob is the global state for the current planner run.
269  * parse is the querytree produced by the parser & rewriter.
270  * parent_root is the immediate parent Query's info (NULL at the top level).
271  * hasRecursion is true if this is a recursive WITH query.
272  * tuple_fraction is the fraction of tuples we expect will be retrieved.
273  * tuple_fraction is interpreted as explained for grouping_planner, below.
274  *
275  * If subroot isn't NULL, we pass back the query's final PlannerInfo struct;
276  * among other things this tells the output sort ordering of the plan.
277  *
278  * Basically, this routine does the stuff that should only be done once
279  * per Query object.  It then calls grouping_planner.  At one time,
280  * grouping_planner could be invoked recursively on the same Query object;
281  * that's not currently true, but we keep the separation between the two
282  * routines anyway, in case we need it again someday.
283  *
284  * subquery_planner will be called recursively to handle sub-Query nodes
285  * found within the query's expressions and rangetable.
286  *
287  * Returns a query plan.
288  *--------------------
289  */
290 Plan *
291 subquery_planner(PlannerGlobal *glob, Query *parse,
292                                  PlannerInfo *parent_root,
293                                  bool hasRecursion, double tuple_fraction,
294                                  PlannerInfo **subroot)
295 {
296         int                     num_old_subplans = list_length(glob->subplans);
297         PlannerInfo *root;
298         Plan       *plan;
299         List       *newHaving;
300         bool            hasOuterJoins;
301         ListCell   *l;
302
303         /* Create a PlannerInfo data structure for this subquery */
304         root = makeNode(PlannerInfo);
305         root->parse = parse;
306         root->glob = glob;
307         root->query_level = parent_root ? parent_root->query_level + 1 : 1;
308         root->parent_root = parent_root;
309         root->planner_cxt = CurrentMemoryContext;
310         root->init_plans = NIL;
311         root->cte_plan_ids = NIL;
312         root->eq_classes = NIL;
313         root->append_rel_list = NIL;
314         root->rowMarks = NIL;
315         root->hasInheritedTarget = false;
316
317         root->hasRecursion = hasRecursion;
318         if (hasRecursion)
319                 root->wt_param_id = SS_assign_special_param(root);
320         else
321                 root->wt_param_id = -1;
322         root->non_recursive_plan = NULL;
323
324         /*
325          * If there is a WITH list, process each WITH query and build an initplan
326          * SubPlan structure for it.
327          */
328         if (parse->cteList)
329                 SS_process_ctes(root);
330
331         /*
332          * Look for ANY and EXISTS SubLinks in WHERE and JOIN/ON clauses, and try
333          * to transform them into joins.  Note that this step does not descend
334          * into subqueries; if we pull up any subqueries below, their SubLinks are
335          * processed just before pulling them up.
336          */
337         if (parse->hasSubLinks)
338                 pull_up_sublinks(root);
339
340         /*
341          * Scan the rangetable for set-returning functions, and inline them if
342          * possible (producing subqueries that might get pulled up next).
343          * Recursion issues here are handled in the same way as for SubLinks.
344          */
345         inline_set_returning_functions(root);
346
347         /*
348          * Check to see if any subqueries in the jointree can be merged into this
349          * query.
350          */
351         parse->jointree = (FromExpr *)
352                 pull_up_subqueries(root, (Node *) parse->jointree, NULL, NULL);
353
354         /*
355          * If this is a simple UNION ALL query, flatten it into an appendrel. We
356          * do this now because it requires applying pull_up_subqueries to the leaf
357          * queries of the UNION ALL, which weren't touched above because they
358          * weren't referenced by the jointree (they will be after we do this).
359          */
360         if (parse->setOperations)
361                 flatten_simple_union_all(root);
362
363         /*
364          * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
365          * avoid the expense of doing flatten_join_alias_vars().  Also check for
366          * outer joins --- if none, we can skip reduce_outer_joins(). This must be
367          * done after we have done pull_up_subqueries, of course.
368          */
369         root->hasJoinRTEs = false;
370         hasOuterJoins = false;
371         foreach(l, parse->rtable)
372         {
373                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
374
375                 if (rte->rtekind == RTE_JOIN)
376                 {
377                         root->hasJoinRTEs = true;
378                         if (IS_OUTER_JOIN(rte->jointype))
379                         {
380                                 hasOuterJoins = true;
381                                 /* Can quit scanning once we find an outer join */
382                                 break;
383                         }
384                 }
385         }
386
387         /*
388          * Preprocess RowMark information.      We need to do this after subquery
389          * pullup (so that all non-inherited RTEs are present) and before
390          * inheritance expansion (so that the info is available for
391          * expand_inherited_tables to examine and modify).
392          */
393         preprocess_rowmarks(root);
394
395         /*
396          * Expand any rangetable entries that are inheritance sets into "append
397          * relations".  This can add entries to the rangetable, but they must be
398          * plain base relations not joins, so it's OK (and marginally more
399          * efficient) to do it after checking for join RTEs.  We must do it after
400          * pulling up subqueries, else we'd fail to handle inherited tables in
401          * subqueries.
402          */
403         expand_inherited_tables(root);
404
405         /*
406          * Set hasHavingQual to remember if HAVING clause is present.  Needed
407          * because preprocess_expression will reduce a constant-true condition to
408          * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
409          */
410         root->hasHavingQual = (parse->havingQual != NULL);
411
412         /* Clear this flag; might get set in distribute_qual_to_rels */
413         root->hasPseudoConstantQuals = false;
414
415         /*
416          * Do expression preprocessing on targetlist and quals, as well as other
417          * random expressions in the querytree.  Note that we do not need to
418          * handle sort/group expressions explicitly, because they are actually
419          * part of the targetlist.
420          */
421         parse->targetList = (List *)
422                 preprocess_expression(root, (Node *) parse->targetList,
423                                                           EXPRKIND_TARGET);
424
425         parse->returningList = (List *)
426                 preprocess_expression(root, (Node *) parse->returningList,
427                                                           EXPRKIND_TARGET);
428
429         preprocess_qual_conditions(root, (Node *) parse->jointree);
430
431         parse->havingQual = preprocess_expression(root, parse->havingQual,
432                                                                                           EXPRKIND_QUAL);
433
434         foreach(l, parse->windowClause)
435         {
436                 WindowClause *wc = (WindowClause *) lfirst(l);
437
438                 /* partitionClause/orderClause are sort/group expressions */
439                 wc->startOffset = preprocess_expression(root, wc->startOffset,
440                                                                                                 EXPRKIND_LIMIT);
441                 wc->endOffset = preprocess_expression(root, wc->endOffset,
442                                                                                           EXPRKIND_LIMIT);
443         }
444
445         parse->limitOffset = preprocess_expression(root, parse->limitOffset,
446                                                                                            EXPRKIND_LIMIT);
447         parse->limitCount = preprocess_expression(root, parse->limitCount,
448                                                                                           EXPRKIND_LIMIT);
449
450         root->append_rel_list = (List *)
451                 preprocess_expression(root, (Node *) root->append_rel_list,
452                                                           EXPRKIND_APPINFO);
453
454         /* Also need to preprocess expressions for function and values RTEs */
455         foreach(l, parse->rtable)
456         {
457                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
458
459                 if (rte->rtekind == RTE_FUNCTION)
460                         rte->funcexpr = preprocess_expression(root, rte->funcexpr,
461                                                                                                   EXPRKIND_RTFUNC);
462                 else if (rte->rtekind == RTE_VALUES)
463                         rte->values_lists = (List *)
464                                 preprocess_expression(root, (Node *) rte->values_lists,
465                                                                           EXPRKIND_VALUES);
466         }
467
468         /*
469          * In some cases we may want to transfer a HAVING clause into WHERE. We
470          * cannot do so if the HAVING clause contains aggregates (obviously) or
471          * volatile functions (since a HAVING clause is supposed to be executed
472          * only once per group).  Also, it may be that the clause is so expensive
473          * to execute that we're better off doing it only once per group, despite
474          * the loss of selectivity.  This is hard to estimate short of doing the
475          * entire planning process twice, so we use a heuristic: clauses
476          * containing subplans are left in HAVING.      Otherwise, we move or copy the
477          * HAVING clause into WHERE, in hopes of eliminating tuples before
478          * aggregation instead of after.
479          *
480          * If the query has explicit grouping then we can simply move such a
481          * clause into WHERE; any group that fails the clause will not be in the
482          * output because none of its tuples will reach the grouping or
483          * aggregation stage.  Otherwise we must have a degenerate (variable-free)
484          * HAVING clause, which we put in WHERE so that query_planner() can use it
485          * in a gating Result node, but also keep in HAVING to ensure that we
486          * don't emit a bogus aggregated row. (This could be done better, but it
487          * seems not worth optimizing.)
488          *
489          * Note that both havingQual and parse->jointree->quals are in
490          * implicitly-ANDed-list form at this point, even though they are declared
491          * as Node *.
492          */
493         newHaving = NIL;
494         foreach(l, (List *) parse->havingQual)
495         {
496                 Node       *havingclause = (Node *) lfirst(l);
497
498                 if (contain_agg_clause(havingclause) ||
499                         contain_volatile_functions(havingclause) ||
500                         contain_subplans(havingclause))
501                 {
502                         /* keep it in HAVING */
503                         newHaving = lappend(newHaving, havingclause);
504                 }
505                 else if (parse->groupClause)
506                 {
507                         /* move it to WHERE */
508                         parse->jointree->quals = (Node *)
509                                 lappend((List *) parse->jointree->quals, havingclause);
510                 }
511                 else
512                 {
513                         /* put a copy in WHERE, keep it in HAVING */
514                         parse->jointree->quals = (Node *)
515                                 lappend((List *) parse->jointree->quals,
516                                                 copyObject(havingclause));
517                         newHaving = lappend(newHaving, havingclause);
518                 }
519         }
520         parse->havingQual = (Node *) newHaving;
521
522         /*
523          * If we have any outer joins, try to reduce them to plain inner joins.
524          * This step is most easily done after we've done expression
525          * preprocessing.
526          */
527         if (hasOuterJoins)
528                 reduce_outer_joins(root);
529
530         /*
531          * Do the main planning.  If we have an inherited target relation, that
532          * needs special processing, else go straight to grouping_planner.
533          */
534         if (parse->resultRelation &&
535                 rt_fetch(parse->resultRelation, parse->rtable)->inh)
536                 plan = inheritance_planner(root);
537         else
538         {
539                 plan = grouping_planner(root, tuple_fraction);
540                 /* If it's not SELECT, we need a ModifyTable node */
541                 if (parse->commandType != CMD_SELECT)
542                 {
543                         List       *returningLists;
544                         List       *rowMarks;
545
546                         /*
547                          * Deal with the RETURNING clause if any.  It's convenient to pass
548                          * the returningList through setrefs.c now rather than at top
549                          * level (if we waited, handling inherited UPDATE/DELETE would be
550                          * much harder).
551                          */
552                         if (parse->returningList)
553                         {
554                                 List       *rlist;
555
556                                 Assert(parse->resultRelation);
557                                 rlist = set_returning_clause_references(root->glob,
558                                                                                                                 parse->returningList,
559                                                                                                                 plan,
560                                                                                                           parse->resultRelation);
561                                 returningLists = list_make1(rlist);
562                         }
563                         else
564                                 returningLists = NIL;
565
566                         /*
567                          * If there was a FOR UPDATE/SHARE clause, the LockRows node will
568                          * have dealt with fetching non-locked marked rows, else we need
569                          * to have ModifyTable do that.
570                          */
571                         if (parse->rowMarks)
572                                 rowMarks = NIL;
573                         else
574                                 rowMarks = root->rowMarks;
575
576                         plan = (Plan *) make_modifytable(parse->commandType,
577                                                                                          parse->canSetTag,
578                                                                            list_make1_int(parse->resultRelation),
579                                                                                          list_make1(plan),
580                                                                                          returningLists,
581                                                                                          rowMarks,
582                                                                                          SS_assign_special_param(root));
583                 }
584         }
585
586         /*
587          * If any subplans were generated, or if there are any parameters to worry
588          * about, build initPlan list and extParam/allParam sets for plan nodes,
589          * and attach the initPlans to the top plan node.
590          */
591         if (list_length(glob->subplans) != num_old_subplans ||
592                 root->glob->paramlist != NIL)
593                 SS_finalize_plan(root, plan, true);
594
595         /* Return internal info if caller wants it */
596         if (subroot)
597                 *subroot = root;
598
599         return plan;
600 }
601
602 /*
603  * preprocess_expression
604  *              Do subquery_planner's preprocessing work for an expression,
605  *              which can be a targetlist, a WHERE clause (including JOIN/ON
606  *              conditions), or a HAVING clause.
607  */
608 static Node *
609 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
610 {
611         /*
612          * Fall out quickly if expression is empty.  This occurs often enough to
613          * be worth checking.  Note that null->null is the correct conversion for
614          * implicit-AND result format, too.
615          */
616         if (expr == NULL)
617                 return NULL;
618
619         /*
620          * If the query has any join RTEs, replace join alias variables with
621          * base-relation variables. We must do this before sublink processing,
622          * else sublinks expanded out from join aliases wouldn't get processed. We
623          * can skip it in VALUES lists, however, since they can't contain any Vars
624          * at all.
625          */
626         if (root->hasJoinRTEs && kind != EXPRKIND_VALUES)
627                 expr = flatten_join_alias_vars(root, expr);
628
629         /*
630          * Simplify constant expressions.
631          *
632          * Note: an essential effect of this is to convert named-argument function
633          * calls to positional notation and insert the current actual values of
634          * any default arguments for functions.  To ensure that happens, we *must*
635          * process all expressions here.  Previous PG versions sometimes skipped
636          * const-simplification if it didn't seem worth the trouble, but we can't
637          * do that anymore.
638          *
639          * Note: this also flattens nested AND and OR expressions into N-argument
640          * form.  All processing of a qual expression after this point must be
641          * careful to maintain AND/OR flatness --- that is, do not generate a tree
642          * with AND directly under AND, nor OR directly under OR.
643          */
644         expr = eval_const_expressions(root, expr);
645
646         /*
647          * If it's a qual or havingQual, canonicalize it.
648          */
649         if (kind == EXPRKIND_QUAL)
650         {
651                 expr = (Node *) canonicalize_qual((Expr *) expr);
652
653 #ifdef OPTIMIZER_DEBUG
654                 printf("After canonicalize_qual()\n");
655                 pprint(expr);
656 #endif
657         }
658
659         /* Expand SubLinks to SubPlans */
660         if (root->parse->hasSubLinks)
661                 expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
662
663         /*
664          * XXX do not insert anything here unless you have grokked the comments in
665          * SS_replace_correlation_vars ...
666          */
667
668         /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
669         if (root->query_level > 1)
670                 expr = SS_replace_correlation_vars(root, expr);
671
672         /*
673          * If it's a qual or havingQual, convert it to implicit-AND format. (We
674          * don't want to do this before eval_const_expressions, since the latter
675          * would be unable to simplify a top-level AND correctly. Also,
676          * SS_process_sublinks expects explicit-AND format.)
677          */
678         if (kind == EXPRKIND_QUAL)
679                 expr = (Node *) make_ands_implicit((Expr *) expr);
680
681         return expr;
682 }
683
684 /*
685  * preprocess_qual_conditions
686  *              Recursively scan the query's jointree and do subquery_planner's
687  *              preprocessing work on each qual condition found therein.
688  */
689 static void
690 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
691 {
692         if (jtnode == NULL)
693                 return;
694         if (IsA(jtnode, RangeTblRef))
695         {
696                 /* nothing to do here */
697         }
698         else if (IsA(jtnode, FromExpr))
699         {
700                 FromExpr   *f = (FromExpr *) jtnode;
701                 ListCell   *l;
702
703                 foreach(l, f->fromlist)
704                         preprocess_qual_conditions(root, lfirst(l));
705
706                 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
707         }
708         else if (IsA(jtnode, JoinExpr))
709         {
710                 JoinExpr   *j = (JoinExpr *) jtnode;
711
712                 preprocess_qual_conditions(root, j->larg);
713                 preprocess_qual_conditions(root, j->rarg);
714
715                 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
716         }
717         else
718                 elog(ERROR, "unrecognized node type: %d",
719                          (int) nodeTag(jtnode));
720 }
721
722 /*
723  * inheritance_planner
724  *        Generate a plan in the case where the result relation is an
725  *        inheritance set.
726  *
727  * We have to handle this case differently from cases where a source relation
728  * is an inheritance set. Source inheritance is expanded at the bottom of the
729  * plan tree (see allpaths.c), but target inheritance has to be expanded at
730  * the top.  The reason is that for UPDATE, each target relation needs a
731  * different targetlist matching its own column set.  Fortunately,
732  * the UPDATE/DELETE target can never be the nullable side of an outer join,
733  * so it's OK to generate the plan this way.
734  *
735  * Returns a query plan.
736  */
737 static Plan *
738 inheritance_planner(PlannerInfo *root)
739 {
740         Query      *parse = root->parse;
741         int                     parentRTindex = parse->resultRelation;
742         List       *subplans = NIL;
743         List       *resultRelations = NIL;
744         List       *returningLists = NIL;
745         List       *rtable = NIL;
746         List       *rowMarks;
747         List       *tlist;
748         PlannerInfo subroot;
749         ListCell   *l;
750
751         foreach(l, root->append_rel_list)
752         {
753                 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
754                 Plan       *subplan;
755
756                 /* append_rel_list contains all append rels; ignore others */
757                 if (appinfo->parent_relid != parentRTindex)
758                         continue;
759
760                 /*
761                  * Generate modified query with this rel as target.
762                  */
763                 memcpy(&subroot, root, sizeof(PlannerInfo));
764                 subroot.parse = (Query *)
765                         adjust_appendrel_attrs((Node *) parse,
766                                                                    appinfo);
767                 subroot.init_plans = NIL;
768                 subroot.hasInheritedTarget = true;
769                 /* We needn't modify the child's append_rel_list */
770                 /* There shouldn't be any OJ info to translate, as yet */
771                 Assert(subroot.join_info_list == NIL);
772                 /* and we haven't created PlaceHolderInfos, either */
773                 Assert(subroot.placeholder_list == NIL);
774
775                 /* Generate plan */
776                 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
777
778                 /*
779                  * If this child rel was excluded by constraint exclusion, exclude it
780                  * from the plan.
781                  */
782                 if (is_dummy_plan(subplan))
783                         continue;
784
785                 /* Save rtable from first rel for use below */
786                 if (subplans == NIL)
787                         rtable = subroot.parse->rtable;
788
789                 subplans = lappend(subplans, subplan);
790
791                 /* Make sure any initplans from this rel get into the outer list */
792                 root->init_plans = list_concat(root->init_plans, subroot.init_plans);
793
794                 /* Build list of target-relation RT indexes */
795                 resultRelations = lappend_int(resultRelations, appinfo->child_relid);
796
797                 /* Build list of per-relation RETURNING targetlists */
798                 if (parse->returningList)
799                 {
800                         List       *rlist;
801
802                         rlist = set_returning_clause_references(root->glob,
803                                                                                                 subroot.parse->returningList,
804                                                                                                         subplan,
805                                                                                                         appinfo->child_relid);
806                         returningLists = lappend(returningLists, rlist);
807                 }
808         }
809
810         /* Mark result as unordered (probably unnecessary) */
811         root->query_pathkeys = NIL;
812
813         /*
814          * If we managed to exclude every child rel, return a dummy plan; it
815          * doesn't even need a ModifyTable node.
816          */
817         if (subplans == NIL)
818         {
819                 /* although dummy, it must have a valid tlist for executor */
820                 tlist = preprocess_targetlist(root, parse->targetList);
821                 return (Plan *) make_result(root,
822                                                                         tlist,
823                                                                         (Node *) list_make1(makeBoolConst(false,
824                                                                                                                                           false)),
825                                                                         NULL);
826         }
827
828         /*
829          * Planning might have modified the rangetable, due to changes of the
830          * Query structures inside subquery RTEs.  We have to ensure that this
831          * gets propagated back to the master copy.  But can't do this until we
832          * are done planning, because all the calls to grouping_planner need
833          * virgin sub-Queries to work from.  (We are effectively assuming that
834          * sub-Queries will get planned identically each time, or at least that
835          * the impacts on their rangetables will be the same each time.)
836          *
837          * XXX should clean this up someday
838          */
839         parse->rtable = rtable;
840
841         /*
842          * If there was a FOR UPDATE/SHARE clause, the LockRows node will have
843          * dealt with fetching non-locked marked rows, else we need to have
844          * ModifyTable do that.
845          */
846         if (parse->rowMarks)
847                 rowMarks = NIL;
848         else
849                 rowMarks = root->rowMarks;
850
851         /* And last, tack on a ModifyTable node to do the UPDATE/DELETE work */
852         return (Plan *) make_modifytable(parse->commandType,
853                                                                          parse->canSetTag,
854                                                                          resultRelations,
855                                                                          subplans,
856                                                                          returningLists,
857                                                                          rowMarks,
858                                                                          SS_assign_special_param(root));
859 }
860
861 /*--------------------
862  * grouping_planner
863  *        Perform planning steps related to grouping, aggregation, etc.
864  *        This primarily means adding top-level processing to the basic
865  *        query plan produced by query_planner.
866  *
867  * tuple_fraction is the fraction of tuples we expect will be retrieved
868  *
869  * tuple_fraction is interpreted as follows:
870  *        0: expect all tuples to be retrieved (normal case)
871  *        0 < tuple_fraction < 1: expect the given fraction of tuples available
872  *              from the plan to be retrieved
873  *        tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
874  *              expected to be retrieved (ie, a LIMIT specification)
875  *
876  * Returns a query plan.  Also, root->query_pathkeys is returned as the
877  * actual output ordering of the plan (in pathkey format).
878  *--------------------
879  */
880 static Plan *
881 grouping_planner(PlannerInfo *root, double tuple_fraction)
882 {
883         Query      *parse = root->parse;
884         List       *tlist = parse->targetList;
885         int64           offset_est = 0;
886         int64           count_est = 0;
887         double          limit_tuples = -1.0;
888         Plan       *result_plan;
889         List       *current_pathkeys;
890         double          dNumGroups = 0;
891         bool            use_hashed_distinct = false;
892         bool            tested_hashed_distinct = false;
893
894         /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
895         if (parse->limitCount || parse->limitOffset)
896         {
897                 tuple_fraction = preprocess_limit(root, tuple_fraction,
898                                                                                   &offset_est, &count_est);
899
900                 /*
901                  * If we have a known LIMIT, and don't have an unknown OFFSET, we can
902                  * estimate the effects of using a bounded sort.
903                  */
904                 if (count_est > 0 && offset_est >= 0)
905                         limit_tuples = (double) count_est + (double) offset_est;
906         }
907
908         if (parse->setOperations)
909         {
910                 List       *set_sortclauses;
911
912                 /*
913                  * If there's a top-level ORDER BY, assume we have to fetch all the
914                  * tuples.      This might be too simplistic given all the hackery below
915                  * to possibly avoid the sort; but the odds of accurate estimates here
916                  * are pretty low anyway.
917                  */
918                 if (parse->sortClause)
919                         tuple_fraction = 0.0;
920
921                 /*
922                  * Construct the plan for set operations.  The result will not need
923                  * any work except perhaps a top-level sort and/or LIMIT.  Note that
924                  * any special work for recursive unions is the responsibility of
925                  * plan_set_operations.
926                  */
927                 result_plan = plan_set_operations(root, tuple_fraction,
928                                                                                   &set_sortclauses);
929
930                 /*
931                  * Calculate pathkeys representing the sort order (if any) of the set
932                  * operation's result.  We have to do this before overwriting the sort
933                  * key information...
934                  */
935                 current_pathkeys = make_pathkeys_for_sortclauses(root,
936                                                                                                                  set_sortclauses,
937                                                                                                          result_plan->targetlist,
938                                                                                                                  true);
939
940                 /*
941                  * We should not need to call preprocess_targetlist, since we must be
942                  * in a SELECT query node.      Instead, use the targetlist returned by
943                  * plan_set_operations (since this tells whether it returned any
944                  * resjunk columns!), and transfer any sort key information from the
945                  * original tlist.
946                  */
947                 Assert(parse->commandType == CMD_SELECT);
948
949                 tlist = postprocess_setop_tlist(copyObject(result_plan->targetlist),
950                                                                                 tlist);
951
952                 /*
953                  * Can't handle FOR UPDATE/SHARE here (parser should have checked
954                  * already, but let's make sure).
955                  */
956                 if (parse->rowMarks)
957                         ereport(ERROR,
958                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
959                                          errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
960
961                 /*
962                  * Calculate pathkeys that represent result ordering requirements
963                  */
964                 Assert(parse->distinctClause == NIL);
965                 root->sort_pathkeys = make_pathkeys_for_sortclauses(root,
966                                                                                                                         parse->sortClause,
967                                                                                                                         tlist,
968                                                                                                                         true);
969         }
970         else
971         {
972                 /* No set operations, do regular planning */
973                 List       *sub_tlist;
974                 double          sub_limit_tuples;
975                 AttrNumber *groupColIdx = NULL;
976                 bool            need_tlist_eval = true;
977                 QualCost        tlist_cost;
978                 Path       *cheapest_path;
979                 Path       *sorted_path;
980                 Path       *best_path;
981                 long            numGroups = 0;
982                 AggClauseCosts agg_costs;
983                 int                     numGroupCols;
984                 double          path_rows;
985                 int                     path_width;
986                 bool            use_hashed_grouping = false;
987                 WindowFuncLists *wflists = NULL;
988                 List       *activeWindows = NIL;
989
990                 MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
991
992                 /* A recursive query should always have setOperations */
993                 Assert(!root->hasRecursion);
994
995                 /* Preprocess GROUP BY clause, if any */
996                 if (parse->groupClause)
997                         preprocess_groupclause(root);
998                 numGroupCols = list_length(parse->groupClause);
999
1000                 /* Preprocess targetlist */
1001                 tlist = preprocess_targetlist(root, tlist);
1002
1003                 /*
1004                  * Locate any window functions in the tlist.  (We don't need to look
1005                  * anywhere else, since expressions used in ORDER BY will be in there
1006                  * too.)  Note that they could all have been eliminated by constant
1007                  * folding, in which case we don't need to do any more work.
1008                  */
1009                 if (parse->hasWindowFuncs)
1010                 {
1011                         wflists = find_window_functions((Node *) tlist,
1012                                                                                         list_length(parse->windowClause));
1013                         if (wflists->numWindowFuncs > 0)
1014                                 activeWindows = select_active_windows(root, wflists);
1015                         else
1016                                 parse->hasWindowFuncs = false;
1017                 }
1018
1019                 /*
1020                  * Generate appropriate target list for subplan; may be different from
1021                  * tlist if grouping or aggregation is needed.
1022                  */
1023                 sub_tlist = make_subplanTargetList(root, tlist,
1024                                                                                    &groupColIdx, &need_tlist_eval);
1025
1026                 /*
1027                  * Do aggregate preprocessing, if the query has any aggs.
1028                  *
1029                  * Note: think not that we can turn off hasAggs if we find no aggs. It
1030                  * is possible for constant-expression simplification to remove all
1031                  * explicit references to aggs, but we still have to follow the
1032                  * aggregate semantics (eg, producing only one output row).
1033                  */
1034                 if (parse->hasAggs)
1035                 {
1036                         /*
1037                          * Collect statistics about aggregates for estimating costs. Note:
1038                          * we do not attempt to detect duplicate aggregates here; a
1039                          * somewhat-overestimated cost is okay for our present purposes.
1040                          */
1041                         count_agg_clauses(root, (Node *) tlist, &agg_costs);
1042                         count_agg_clauses(root, parse->havingQual, &agg_costs);
1043
1044                         /*
1045                          * Preprocess MIN/MAX aggregates, if any.  Note: be careful about
1046                          * adding logic between here and the optimize_minmax_aggregates
1047                          * call.  Anything that is needed in MIN/MAX-optimizable cases
1048                          * will have to be duplicated in planagg.c.
1049                          */
1050                         preprocess_minmax_aggregates(root, tlist);
1051                 }
1052
1053                 /*
1054                  * Calculate pathkeys that represent grouping/ordering requirements.
1055                  * Stash them in PlannerInfo so that query_planner can canonicalize
1056                  * them after EquivalenceClasses have been formed.      The sortClause is
1057                  * certainly sort-able, but GROUP BY and DISTINCT might not be, in
1058                  * which case we just leave their pathkeys empty.
1059                  */
1060                 if (parse->groupClause &&
1061                         grouping_is_sortable(parse->groupClause))
1062                         root->group_pathkeys =
1063                                 make_pathkeys_for_sortclauses(root,
1064                                                                                           parse->groupClause,
1065                                                                                           tlist,
1066                                                                                           false);
1067                 else
1068                         root->group_pathkeys = NIL;
1069
1070                 /* We consider only the first (bottom) window in pathkeys logic */
1071                 if (activeWindows != NIL)
1072                 {
1073                         WindowClause *wc = (WindowClause *) linitial(activeWindows);
1074
1075                         root->window_pathkeys = make_pathkeys_for_window(root,
1076                                                                                                                          wc,
1077                                                                                                                          tlist,
1078                                                                                                                          false);
1079                 }
1080                 else
1081                         root->window_pathkeys = NIL;
1082
1083                 if (parse->distinctClause &&
1084                         grouping_is_sortable(parse->distinctClause))
1085                         root->distinct_pathkeys =
1086                                 make_pathkeys_for_sortclauses(root,
1087                                                                                           parse->distinctClause,
1088                                                                                           tlist,
1089                                                                                           false);
1090                 else
1091                         root->distinct_pathkeys = NIL;
1092
1093                 root->sort_pathkeys =
1094                         make_pathkeys_for_sortclauses(root,
1095                                                                                   parse->sortClause,
1096                                                                                   tlist,
1097                                                                                   false);
1098
1099                 /*
1100                  * Figure out whether we want a sorted result from query_planner.
1101                  *
1102                  * If we have a sortable GROUP BY clause, then we want a result sorted
1103                  * properly for grouping.  Otherwise, if we have window functions to
1104                  * evaluate, we try to sort for the first window.  Otherwise, if
1105                  * there's a sortable DISTINCT clause that's more rigorous than the
1106                  * ORDER BY clause, we try to produce output that's sufficiently well
1107                  * sorted for the DISTINCT.  Otherwise, if there is an ORDER BY
1108                  * clause, we want to sort by the ORDER BY clause.
1109                  *
1110                  * Note: if we have both ORDER BY and GROUP BY, and ORDER BY is a
1111                  * superset of GROUP BY, it would be tempting to request sort by ORDER
1112                  * BY --- but that might just leave us failing to exploit an available
1113                  * sort order at all.  Needs more thought.      The choice for DISTINCT
1114                  * versus ORDER BY is much easier, since we know that the parser
1115                  * ensured that one is a superset of the other.
1116                  */
1117                 if (root->group_pathkeys)
1118                         root->query_pathkeys = root->group_pathkeys;
1119                 else if (root->window_pathkeys)
1120                         root->query_pathkeys = root->window_pathkeys;
1121                 else if (list_length(root->distinct_pathkeys) >
1122                                  list_length(root->sort_pathkeys))
1123                         root->query_pathkeys = root->distinct_pathkeys;
1124                 else if (root->sort_pathkeys)
1125                         root->query_pathkeys = root->sort_pathkeys;
1126                 else
1127                         root->query_pathkeys = NIL;
1128
1129                 /*
1130                  * Figure out whether there's a hard limit on the number of rows that
1131                  * query_planner's result subplan needs to return.  Even if we know a
1132                  * hard limit overall, it doesn't apply if the query has any
1133                  * grouping/aggregation operations.
1134                  */
1135                 if (parse->groupClause ||
1136                         parse->distinctClause ||
1137                         parse->hasAggs ||
1138                         parse->hasWindowFuncs ||
1139                         root->hasHavingQual)
1140                         sub_limit_tuples = -1.0;
1141                 else
1142                         sub_limit_tuples = limit_tuples;
1143
1144                 /*
1145                  * Generate the best unsorted and presorted paths for this Query (but
1146                  * note there may not be any presorted path).  query_planner will also
1147                  * estimate the number of groups in the query, and canonicalize all
1148                  * the pathkeys.
1149                  */
1150                 query_planner(root, sub_tlist, tuple_fraction, sub_limit_tuples,
1151                                           &cheapest_path, &sorted_path, &dNumGroups);
1152
1153                 /*
1154                  * Extract rowcount and width estimates for possible use in grouping
1155                  * decisions.  Beware here of the possibility that
1156                  * cheapest_path->parent is NULL (ie, there is no FROM clause).
1157                  */
1158                 if (cheapest_path->parent)
1159                 {
1160                         path_rows = cheapest_path->parent->rows;
1161                         path_width = cheapest_path->parent->width;
1162                 }
1163                 else
1164                 {
1165                         path_rows = 1;          /* assume non-set result */
1166                         path_width = 100;       /* arbitrary */
1167                 }
1168
1169                 if (parse->groupClause)
1170                 {
1171                         /*
1172                          * If grouping, decide whether to use sorted or hashed grouping.
1173                          */
1174                         use_hashed_grouping =
1175                                 choose_hashed_grouping(root,
1176                                                                            tuple_fraction, limit_tuples,
1177                                                                            path_rows, path_width,
1178                                                                            cheapest_path, sorted_path,
1179                                                                            dNumGroups, &agg_costs);
1180                         /* Also convert # groups to long int --- but 'ware overflow! */
1181                         numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
1182                 }
1183                 else if (parse->distinctClause && sorted_path &&
1184                                  !root->hasHavingQual && !parse->hasAggs && !activeWindows)
1185                 {
1186                         /*
1187                          * We'll reach the DISTINCT stage without any intermediate
1188                          * processing, so figure out whether we will want to hash or not
1189                          * so we can choose whether to use cheapest or sorted path.
1190                          */
1191                         use_hashed_distinct =
1192                                 choose_hashed_distinct(root,
1193                                                                            tuple_fraction, limit_tuples,
1194                                                                            path_rows, path_width,
1195                                                                            cheapest_path->startup_cost,
1196                                                                            cheapest_path->total_cost,
1197                                                                            sorted_path->startup_cost,
1198                                                                            sorted_path->total_cost,
1199                                                                            sorted_path->pathkeys,
1200                                                                            dNumGroups);
1201                         tested_hashed_distinct = true;
1202                 }
1203
1204                 /*
1205                  * Select the best path.  If we are doing hashed grouping, we will
1206                  * always read all the input tuples, so use the cheapest-total path.
1207                  * Otherwise, trust query_planner's decision about which to use.
1208                  */
1209                 if (use_hashed_grouping || use_hashed_distinct || !sorted_path)
1210                         best_path = cheapest_path;
1211                 else
1212                         best_path = sorted_path;
1213
1214                 /*
1215                  * Check to see if it's possible to optimize MIN/MAX aggregates. If
1216                  * so, we will forget all the work we did so far to choose a "regular"
1217                  * path ... but we had to do it anyway to be able to tell which way is
1218                  * cheaper.
1219                  */
1220                 result_plan = optimize_minmax_aggregates(root,
1221                                                                                                  tlist,
1222                                                                                                  &agg_costs,
1223                                                                                                  best_path);
1224                 if (result_plan != NULL)
1225                 {
1226                         /*
1227                          * optimize_minmax_aggregates generated the full plan, with the
1228                          * right tlist, and it has no sort order.
1229                          */
1230                         current_pathkeys = NIL;
1231                 }
1232                 else
1233                 {
1234                         /*
1235                          * Normal case --- create a plan according to query_planner's
1236                          * results.
1237                          */
1238                         bool            need_sort_for_grouping = false;
1239
1240                         result_plan = create_plan(root, best_path);
1241                         current_pathkeys = best_path->pathkeys;
1242
1243                         /* Detect if we'll need an explicit sort for grouping */
1244                         if (parse->groupClause && !use_hashed_grouping &&
1245                           !pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1246                         {
1247                                 need_sort_for_grouping = true;
1248
1249                                 /*
1250                                  * Always override query_planner's tlist, so that we don't
1251                                  * sort useless data from a "physical" tlist.
1252                                  */
1253                                 need_tlist_eval = true;
1254                         }
1255
1256                         /*
1257                          * create_plan() returns a plan with just a "flat" tlist of
1258                          * required Vars.  Usually we need to insert the sub_tlist as the
1259                          * tlist of the top plan node.  However, we can skip that if we
1260                          * determined that whatever query_planner chose to return will be
1261                          * good enough.
1262                          */
1263                         if (need_tlist_eval)
1264                         {
1265                                 /*
1266                                  * If the top-level plan node is one that cannot do expression
1267                                  * evaluation, we must insert a Result node to project the
1268                                  * desired tlist.
1269                                  */
1270                                 if (!is_projection_capable_plan(result_plan))
1271                                 {
1272                                         result_plan = (Plan *) make_result(root,
1273                                                                                                            sub_tlist,
1274                                                                                                            NULL,
1275                                                                                                            result_plan);
1276                                 }
1277                                 else
1278                                 {
1279                                         /*
1280                                          * Otherwise, just replace the subplan's flat tlist with
1281                                          * the desired tlist.
1282                                          */
1283                                         result_plan->targetlist = sub_tlist;
1284                                 }
1285
1286                                 /*
1287                                  * Also, account for the cost of evaluation of the sub_tlist.
1288                                  *
1289                                  * Up to now, we have only been dealing with "flat" tlists,
1290                                  * containing just Vars.  So their evaluation cost is zero
1291                                  * according to the model used by cost_qual_eval() (or if you
1292                                  * prefer, the cost is factored into cpu_tuple_cost).  Thus we
1293                                  * can avoid accounting for tlist cost throughout
1294                                  * query_planner() and subroutines.  But now we've inserted a
1295                                  * tlist that might contain actual operators, sub-selects, etc
1296                                  * --- so we'd better account for its cost.
1297                                  *
1298                                  * Below this point, any tlist eval cost for added-on nodes
1299                                  * should be accounted for as we create those nodes.
1300                                  * Presently, of the node types we can add on, only Agg,
1301                                  * WindowAgg, and Group project new tlists (the rest just copy
1302                                  * their input tuples) --- so make_agg(), make_windowagg() and
1303                                  * make_group() are responsible for computing the added cost.
1304                                  */
1305                                 cost_qual_eval(&tlist_cost, sub_tlist, root);
1306                                 result_plan->startup_cost += tlist_cost.startup;
1307                                 result_plan->total_cost += tlist_cost.startup +
1308                                         tlist_cost.per_tuple * result_plan->plan_rows;
1309                         }
1310                         else
1311                         {
1312                                 /*
1313                                  * Since we're using query_planner's tlist and not the one
1314                                  * make_subplanTargetList calculated, we have to refigure any
1315                                  * grouping-column indexes make_subplanTargetList computed.
1316                                  */
1317                                 locate_grouping_columns(root, tlist, result_plan->targetlist,
1318                                                                                 groupColIdx);
1319                         }
1320
1321                         /*
1322                          * Insert AGG or GROUP node if needed, plus an explicit sort step
1323                          * if necessary.
1324                          *
1325                          * HAVING clause, if any, becomes qual of the Agg or Group node.
1326                          */
1327                         if (use_hashed_grouping)
1328                         {
1329                                 /* Hashed aggregate plan --- no sort needed */
1330                                 result_plan = (Plan *) make_agg(root,
1331                                                                                                 tlist,
1332                                                                                                 (List *) parse->havingQual,
1333                                                                                                 AGG_HASHED,
1334                                                                                                 &agg_costs,
1335                                                                                                 numGroupCols,
1336                                                                                                 groupColIdx,
1337                                                                         extract_grouping_ops(parse->groupClause),
1338                                                                                                 numGroups,
1339                                                                                                 result_plan);
1340                                 /* Hashed aggregation produces randomly-ordered results */
1341                                 current_pathkeys = NIL;
1342                         }
1343                         else if (parse->hasAggs)
1344                         {
1345                                 /* Plain aggregate plan --- sort if needed */
1346                                 AggStrategy aggstrategy;
1347
1348                                 if (parse->groupClause)
1349                                 {
1350                                         if (need_sort_for_grouping)
1351                                         {
1352                                                 result_plan = (Plan *)
1353                                                         make_sort_from_groupcols(root,
1354                                                                                                          parse->groupClause,
1355                                                                                                          groupColIdx,
1356                                                                                                          result_plan);
1357                                                 current_pathkeys = root->group_pathkeys;
1358                                         }
1359                                         aggstrategy = AGG_SORTED;
1360
1361                                         /*
1362                                          * The AGG node will not change the sort ordering of its
1363                                          * groups, so current_pathkeys describes the result too.
1364                                          */
1365                                 }
1366                                 else
1367                                 {
1368                                         aggstrategy = AGG_PLAIN;
1369                                         /* Result will be only one row anyway; no sort order */
1370                                         current_pathkeys = NIL;
1371                                 }
1372
1373                                 result_plan = (Plan *) make_agg(root,
1374                                                                                                 tlist,
1375                                                                                                 (List *) parse->havingQual,
1376                                                                                                 aggstrategy,
1377                                                                                                 &agg_costs,
1378                                                                                                 numGroupCols,
1379                                                                                                 groupColIdx,
1380                                                                         extract_grouping_ops(parse->groupClause),
1381                                                                                                 numGroups,
1382                                                                                                 result_plan);
1383                         }
1384                         else if (parse->groupClause)
1385                         {
1386                                 /*
1387                                  * GROUP BY without aggregation, so insert a group node (plus
1388                                  * the appropriate sort node, if necessary).
1389                                  *
1390                                  * Add an explicit sort if we couldn't make the path come out
1391                                  * the way the GROUP node needs it.
1392                                  */
1393                                 if (need_sort_for_grouping)
1394                                 {
1395                                         result_plan = (Plan *)
1396                                                 make_sort_from_groupcols(root,
1397                                                                                                  parse->groupClause,
1398                                                                                                  groupColIdx,
1399                                                                                                  result_plan);
1400                                         current_pathkeys = root->group_pathkeys;
1401                                 }
1402
1403                                 result_plan = (Plan *) make_group(root,
1404                                                                                                   tlist,
1405                                                                                                   (List *) parse->havingQual,
1406                                                                                                   numGroupCols,
1407                                                                                                   groupColIdx,
1408                                                                         extract_grouping_ops(parse->groupClause),
1409                                                                                                   dNumGroups,
1410                                                                                                   result_plan);
1411                                 /* The Group node won't change sort ordering */
1412                         }
1413                         else if (root->hasHavingQual)
1414                         {
1415                                 /*
1416                                  * No aggregates, and no GROUP BY, but we have a HAVING qual.
1417                                  * This is a degenerate case in which we are supposed to emit
1418                                  * either 0 or 1 row depending on whether HAVING succeeds.
1419                                  * Furthermore, there cannot be any variables in either HAVING
1420                                  * or the targetlist, so we actually do not need the FROM
1421                                  * table at all!  We can just throw away the plan-so-far and
1422                                  * generate a Result node.      This is a sufficiently unusual
1423                                  * corner case that it's not worth contorting the structure of
1424                                  * this routine to avoid having to generate the plan in the
1425                                  * first place.
1426                                  */
1427                                 result_plan = (Plan *) make_result(root,
1428                                                                                                    tlist,
1429                                                                                                    parse->havingQual,
1430                                                                                                    NULL);
1431                         }
1432                 }                                               /* end of non-minmax-aggregate case */
1433
1434                 /*
1435                  * Since each window function could require a different sort order, we
1436                  * stack up a WindowAgg node for each window, with sort steps between
1437                  * them as needed.
1438                  */
1439                 if (activeWindows)
1440                 {
1441                         List       *window_tlist;
1442                         ListCell   *l;
1443
1444                         /*
1445                          * If the top-level plan node is one that cannot do expression
1446                          * evaluation, we must insert a Result node to project the desired
1447                          * tlist.  (In some cases this might not really be required, but
1448                          * it's not worth trying to avoid it.)  Note that on second and
1449                          * subsequent passes through the following loop, the top-level
1450                          * node will be a WindowAgg which we know can project; so we only
1451                          * need to check once.
1452                          */
1453                         if (!is_projection_capable_plan(result_plan))
1454                         {
1455                                 result_plan = (Plan *) make_result(root,
1456                                                                                                    NIL,
1457                                                                                                    NULL,
1458                                                                                                    result_plan);
1459                         }
1460
1461                         /*
1462                          * The "base" targetlist for all steps of the windowing process is
1463                          * a flat tlist of all Vars and Aggs needed in the result. (In
1464                          * some cases we wouldn't need to propagate all of these all the
1465                          * way to the top, since they might only be needed as inputs to
1466                          * WindowFuncs.  It's probably not worth trying to optimize that
1467                          * though.)  We also need any volatile sort expressions, because
1468                          * make_sort_from_pathkeys won't add those on its own, and anyway
1469                          * we want them evaluated only once at the bottom of the stack. As
1470                          * we climb up the stack, we add outputs for the WindowFuncs
1471                          * computed at each level.      Also, each input tlist has to present
1472                          * all the columns needed to sort the data for the next WindowAgg
1473                          * step.  That's handled internally by make_sort_from_pathkeys,
1474                          * but we need the copyObject steps here to ensure that each plan
1475                          * node has a separately modifiable tlist.
1476                          */
1477                         window_tlist = flatten_tlist(tlist);
1478                         if (parse->hasAggs)
1479                                 window_tlist = add_to_flat_tlist(window_tlist,
1480                                                                                         pull_agg_clause((Node *) tlist));
1481                         window_tlist = add_volatile_sort_exprs(window_tlist, tlist,
1482                                                                                                    activeWindows);
1483                         result_plan->targetlist = (List *) copyObject(window_tlist);
1484
1485                         foreach(l, activeWindows)
1486                         {
1487                                 WindowClause *wc = (WindowClause *) lfirst(l);
1488                                 List       *window_pathkeys;
1489                                 int                     partNumCols;
1490                                 AttrNumber *partColIdx;
1491                                 Oid                *partOperators;
1492                                 int                     ordNumCols;
1493                                 AttrNumber *ordColIdx;
1494                                 Oid                *ordOperators;
1495
1496                                 window_pathkeys = make_pathkeys_for_window(root,
1497                                                                                                                    wc,
1498                                                                                                                    tlist,
1499                                                                                                                    true);
1500
1501                                 /*
1502                                  * This is a bit tricky: we build a sort node even if we don't
1503                                  * really have to sort.  Even when no explicit sort is needed,
1504                                  * we need to have suitable resjunk items added to the input
1505                                  * plan's tlist for any partitioning or ordering columns that
1506                                  * aren't plain Vars.  Furthermore, this way we can use
1507                                  * existing infrastructure to identify which input columns are
1508                                  * the interesting ones.
1509                                  */
1510                                 if (window_pathkeys)
1511                                 {
1512                                         Sort       *sort_plan;
1513
1514                                         sort_plan = make_sort_from_pathkeys(root,
1515                                                                                                                 result_plan,
1516                                                                                                                 window_pathkeys,
1517                                                                                                                 -1.0);
1518                                         if (!pathkeys_contained_in(window_pathkeys,
1519                                                                                            current_pathkeys))
1520                                         {
1521                                                 /* we do indeed need to sort */
1522                                                 result_plan = (Plan *) sort_plan;
1523                                                 current_pathkeys = window_pathkeys;
1524                                         }
1525                                         /* In either case, extract the per-column information */
1526                                         get_column_info_for_window(root, wc, tlist,
1527                                                                                            sort_plan->numCols,
1528                                                                                            sort_plan->sortColIdx,
1529                                                                                            &partNumCols,
1530                                                                                            &partColIdx,
1531                                                                                            &partOperators,
1532                                                                                            &ordNumCols,
1533                                                                                            &ordColIdx,
1534                                                                                            &ordOperators);
1535                                 }
1536                                 else
1537                                 {
1538                                         /* empty window specification, nothing to sort */
1539                                         partNumCols = 0;
1540                                         partColIdx = NULL;
1541                                         partOperators = NULL;
1542                                         ordNumCols = 0;
1543                                         ordColIdx = NULL;
1544                                         ordOperators = NULL;
1545                                 }
1546
1547                                 if (lnext(l))
1548                                 {
1549                                         /* Add the current WindowFuncs to the running tlist */
1550                                         window_tlist = add_to_flat_tlist(window_tlist,
1551                                                                                    wflists->windowFuncs[wc->winref]);
1552                                 }
1553                                 else
1554                                 {
1555                                         /* Install the original tlist in the topmost WindowAgg */
1556                                         window_tlist = tlist;
1557                                 }
1558
1559                                 /* ... and make the WindowAgg plan node */
1560                                 result_plan = (Plan *)
1561                                         make_windowagg(root,
1562                                                                    (List *) copyObject(window_tlist),
1563                                                                    wflists->windowFuncs[wc->winref],
1564                                                                    wc->winref,
1565                                                                    partNumCols,
1566                                                                    partColIdx,
1567                                                                    partOperators,
1568                                                                    ordNumCols,
1569                                                                    ordColIdx,
1570                                                                    ordOperators,
1571                                                                    wc->frameOptions,
1572                                                                    wc->startOffset,
1573                                                                    wc->endOffset,
1574                                                                    result_plan);
1575                         }
1576                 }
1577         }                                                       /* end of if (setOperations) */
1578
1579         /*
1580          * If there is a DISTINCT clause, add the necessary node(s).
1581          */
1582         if (parse->distinctClause)
1583         {
1584                 double          dNumDistinctRows;
1585                 long            numDistinctRows;
1586
1587                 /*
1588                  * If there was grouping or aggregation, use the current number of
1589                  * rows as the estimated number of DISTINCT rows (ie, assume the
1590                  * result was already mostly unique).  If not, use the number of
1591                  * distinct-groups calculated by query_planner.
1592                  */
1593                 if (parse->groupClause || root->hasHavingQual || parse->hasAggs)
1594                         dNumDistinctRows = result_plan->plan_rows;
1595                 else
1596                         dNumDistinctRows = dNumGroups;
1597
1598                 /* Also convert to long int --- but 'ware overflow! */
1599                 numDistinctRows = (long) Min(dNumDistinctRows, (double) LONG_MAX);
1600
1601                 /* Choose implementation method if we didn't already */
1602                 if (!tested_hashed_distinct)
1603                 {
1604                         /*
1605                          * At this point, either hashed or sorted grouping will have to
1606                          * work from result_plan, so we pass that as both "cheapest" and
1607                          * "sorted".
1608                          */
1609                         use_hashed_distinct =
1610                                 choose_hashed_distinct(root,
1611                                                                            tuple_fraction, limit_tuples,
1612                                                                            result_plan->plan_rows,
1613                                                                            result_plan->plan_width,
1614                                                                            result_plan->startup_cost,
1615                                                                            result_plan->total_cost,
1616                                                                            result_plan->startup_cost,
1617                                                                            result_plan->total_cost,
1618                                                                            current_pathkeys,
1619                                                                            dNumDistinctRows);
1620                 }
1621
1622                 if (use_hashed_distinct)
1623                 {
1624                         /* Hashed aggregate plan --- no sort needed */
1625                         result_plan = (Plan *) make_agg(root,
1626                                                                                         result_plan->targetlist,
1627                                                                                         NIL,
1628                                                                                         AGG_HASHED,
1629                                                                                         NULL,
1630                                                                                   list_length(parse->distinctClause),
1631                                                                  extract_grouping_cols(parse->distinctClause,
1632                                                                                                         result_plan->targetlist),
1633                                                                  extract_grouping_ops(parse->distinctClause),
1634                                                                                         numDistinctRows,
1635                                                                                         result_plan);
1636                         /* Hashed aggregation produces randomly-ordered results */
1637                         current_pathkeys = NIL;
1638                 }
1639                 else
1640                 {
1641                         /*
1642                          * Use a Unique node to implement DISTINCT.  Add an explicit sort
1643                          * if we couldn't make the path come out the way the Unique node
1644                          * needs it.  If we do have to sort, always sort by the more
1645                          * rigorous of DISTINCT and ORDER BY, to avoid a second sort
1646                          * below.  However, for regular DISTINCT, don't sort now if we
1647                          * don't have to --- sorting afterwards will likely be cheaper,
1648                          * and also has the possibility of optimizing via LIMIT.  But for
1649                          * DISTINCT ON, we *must* force the final sort now, else it won't
1650                          * have the desired behavior.
1651                          */
1652                         List       *needed_pathkeys;
1653
1654                         if (parse->hasDistinctOn &&
1655                                 list_length(root->distinct_pathkeys) <
1656                                 list_length(root->sort_pathkeys))
1657                                 needed_pathkeys = root->sort_pathkeys;
1658                         else
1659                                 needed_pathkeys = root->distinct_pathkeys;
1660
1661                         if (!pathkeys_contained_in(needed_pathkeys, current_pathkeys))
1662                         {
1663                                 if (list_length(root->distinct_pathkeys) >=
1664                                         list_length(root->sort_pathkeys))
1665                                         current_pathkeys = root->distinct_pathkeys;
1666                                 else
1667                                 {
1668                                         current_pathkeys = root->sort_pathkeys;
1669                                         /* Assert checks that parser didn't mess up... */
1670                                         Assert(pathkeys_contained_in(root->distinct_pathkeys,
1671                                                                                                  current_pathkeys));
1672                                 }
1673
1674                                 result_plan = (Plan *) make_sort_from_pathkeys(root,
1675                                                                                                                            result_plan,
1676                                                                                                                         current_pathkeys,
1677                                                                                                                            -1.0);
1678                         }
1679
1680                         result_plan = (Plan *) make_unique(result_plan,
1681                                                                                            parse->distinctClause);
1682                         result_plan->plan_rows = dNumDistinctRows;
1683                         /* The Unique node won't change sort ordering */
1684                 }
1685         }
1686
1687         /*
1688          * If ORDER BY was given and we were not able to make the plan come out in
1689          * the right order, add an explicit sort step.
1690          */
1691         if (parse->sortClause)
1692         {
1693                 if (!pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1694                 {
1695                         result_plan = (Plan *) make_sort_from_pathkeys(root,
1696                                                                                                                    result_plan,
1697                                                                                                                  root->sort_pathkeys,
1698                                                                                                                    limit_tuples);
1699                         current_pathkeys = root->sort_pathkeys;
1700                 }
1701         }
1702
1703         /*
1704          * If there is a FOR UPDATE/SHARE clause, add the LockRows node. (Note: we
1705          * intentionally test parse->rowMarks not root->rowMarks here. If there
1706          * are only non-locking rowmarks, they should be handled by the
1707          * ModifyTable node instead.)
1708          */
1709         if (parse->rowMarks)
1710         {
1711                 result_plan = (Plan *) make_lockrows(result_plan,
1712                                                                                          root->rowMarks,
1713                                                                                          SS_assign_special_param(root));
1714
1715                 /*
1716                  * The result can no longer be assumed sorted, since locking might
1717                  * cause the sort key columns to be replaced with new values.
1718                  */
1719                 current_pathkeys = NIL;
1720         }
1721
1722         /*
1723          * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1724          */
1725         if (parse->limitCount || parse->limitOffset)
1726         {
1727                 result_plan = (Plan *) make_limit(result_plan,
1728                                                                                   parse->limitOffset,
1729                                                                                   parse->limitCount,
1730                                                                                   offset_est,
1731                                                                                   count_est);
1732         }
1733
1734         /*
1735          * Return the actual output ordering in query_pathkeys for possible use by
1736          * an outer query level.
1737          */
1738         root->query_pathkeys = current_pathkeys;
1739
1740         return result_plan;
1741 }
1742
1743 /*
1744  * Detect whether a plan node is a "dummy" plan created when a relation
1745  * is deemed not to need scanning due to constraint exclusion.
1746  *
1747  * Currently, such dummy plans are Result nodes with constant FALSE
1748  * filter quals.
1749  */
1750 static bool
1751 is_dummy_plan(Plan *plan)
1752 {
1753         if (IsA(plan, Result))
1754         {
1755                 List       *rcqual = (List *) ((Result *) plan)->resconstantqual;
1756
1757                 if (list_length(rcqual) == 1)
1758                 {
1759                         Const      *constqual = (Const *) linitial(rcqual);
1760
1761                         if (constqual && IsA(constqual, Const))
1762                         {
1763                                 if (!constqual->constisnull &&
1764                                         !DatumGetBool(constqual->constvalue))
1765                                         return true;
1766                         }
1767                 }
1768         }
1769         return false;
1770 }
1771
1772 /*
1773  * Create a bitmapset of the RT indexes of live base relations
1774  *
1775  * Helper for preprocess_rowmarks ... at this point in the proceedings,
1776  * the only good way to distinguish baserels from appendrel children
1777  * is to see what is in the join tree.
1778  */
1779 static Bitmapset *
1780 get_base_rel_indexes(Node *jtnode)
1781 {
1782         Bitmapset  *result;
1783
1784         if (jtnode == NULL)
1785                 return NULL;
1786         if (IsA(jtnode, RangeTblRef))
1787         {
1788                 int                     varno = ((RangeTblRef *) jtnode)->rtindex;
1789
1790                 result = bms_make_singleton(varno);
1791         }
1792         else if (IsA(jtnode, FromExpr))
1793         {
1794                 FromExpr   *f = (FromExpr *) jtnode;
1795                 ListCell   *l;
1796
1797                 result = NULL;
1798                 foreach(l, f->fromlist)
1799                         result = bms_join(result,
1800                                                           get_base_rel_indexes(lfirst(l)));
1801         }
1802         else if (IsA(jtnode, JoinExpr))
1803         {
1804                 JoinExpr   *j = (JoinExpr *) jtnode;
1805
1806                 result = bms_join(get_base_rel_indexes(j->larg),
1807                                                   get_base_rel_indexes(j->rarg));
1808         }
1809         else
1810         {
1811                 elog(ERROR, "unrecognized node type: %d",
1812                          (int) nodeTag(jtnode));
1813                 result = NULL;                  /* keep compiler quiet */
1814         }
1815         return result;
1816 }
1817
1818 /*
1819  * preprocess_rowmarks - set up PlanRowMarks if needed
1820  */
1821 static void
1822 preprocess_rowmarks(PlannerInfo *root)
1823 {
1824         Query      *parse = root->parse;
1825         Bitmapset  *rels;
1826         List       *prowmarks;
1827         ListCell   *l;
1828         int                     i;
1829
1830         if (parse->rowMarks)
1831         {
1832                 /*
1833                  * We've got trouble if FOR UPDATE/SHARE appears inside grouping,
1834                  * since grouping renders a reference to individual tuple CTIDs
1835                  * invalid.  This is also checked at parse time, but that's
1836                  * insufficient because of rule substitution, query pullup, etc.
1837                  */
1838                 CheckSelectLocking(parse);
1839         }
1840         else
1841         {
1842                 /*
1843                  * We only need rowmarks for UPDATE, DELETE, or FOR UPDATE/SHARE.
1844                  */
1845                 if (parse->commandType != CMD_UPDATE &&
1846                         parse->commandType != CMD_DELETE)
1847                         return;
1848         }
1849
1850         /*
1851          * We need to have rowmarks for all base relations except the target. We
1852          * make a bitmapset of all base rels and then remove the items we don't
1853          * need or have FOR UPDATE/SHARE marks for.
1854          */
1855         rels = get_base_rel_indexes((Node *) parse->jointree);
1856         if (parse->resultRelation)
1857                 rels = bms_del_member(rels, parse->resultRelation);
1858
1859         /*
1860          * Convert RowMarkClauses to PlanRowMark representation.
1861          */
1862         prowmarks = NIL;
1863         foreach(l, parse->rowMarks)
1864         {
1865                 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
1866                 RangeTblEntry *rte = rt_fetch(rc->rti, parse->rtable);
1867                 PlanRowMark *newrc;
1868
1869                 /*
1870                  * Currently, it is syntactically impossible to have FOR UPDATE
1871                  * applied to an update/delete target rel.      If that ever becomes
1872                  * possible, we should drop the target from the PlanRowMark list.
1873                  */
1874                 Assert(rc->rti != parse->resultRelation);
1875
1876                 /*
1877                  * Ignore RowMarkClauses for subqueries; they aren't real tables and
1878                  * can't support true locking.  Subqueries that got flattened into the
1879                  * main query should be ignored completely.  Any that didn't will get
1880                  * ROW_MARK_COPY items in the next loop.
1881                  */
1882                 if (rte->rtekind != RTE_RELATION)
1883                         continue;
1884
1885                 rels = bms_del_member(rels, rc->rti);
1886
1887                 newrc = makeNode(PlanRowMark);
1888                 newrc->rti = newrc->prti = rc->rti;
1889                 newrc->rowmarkId = ++(root->glob->lastRowMarkId);
1890                 if (rc->forUpdate)
1891                         newrc->markType = ROW_MARK_EXCLUSIVE;
1892                 else
1893                         newrc->markType = ROW_MARK_SHARE;
1894                 newrc->noWait = rc->noWait;
1895                 newrc->isParent = false;
1896
1897                 prowmarks = lappend(prowmarks, newrc);
1898         }
1899
1900         /*
1901          * Now, add rowmarks for any non-target, non-locked base relations.
1902          */
1903         i = 0;
1904         foreach(l, parse->rtable)
1905         {
1906                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
1907                 PlanRowMark *newrc;
1908
1909                 i++;
1910                 if (!bms_is_member(i, rels))
1911                         continue;
1912
1913                 newrc = makeNode(PlanRowMark);
1914                 newrc->rti = newrc->prti = i;
1915                 newrc->rowmarkId = ++(root->glob->lastRowMarkId);
1916                 /* real tables support REFERENCE, anything else needs COPY */
1917                 if (rte->rtekind == RTE_RELATION &&
1918                         rte->relkind != RELKIND_FOREIGN_TABLE)
1919                         newrc->markType = ROW_MARK_REFERENCE;
1920                 else
1921                         newrc->markType = ROW_MARK_COPY;
1922                 newrc->noWait = false;  /* doesn't matter */
1923                 newrc->isParent = false;
1924
1925                 prowmarks = lappend(prowmarks, newrc);
1926         }
1927
1928         root->rowMarks = prowmarks;
1929 }
1930
1931 /*
1932  * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1933  *
1934  * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1935  * results back in *count_est and *offset_est.  These variables are set to
1936  * 0 if the corresponding clause is not present, and -1 if it's present
1937  * but we couldn't estimate the value for it.  (The "0" convention is OK
1938  * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1939  * LIMIT 0 as though it were LIMIT 1.  But this is in line with the planner's
1940  * usual practice of never estimating less than one row.)  These values will
1941  * be passed to make_limit, which see if you change this code.
1942  *
1943  * The return value is the suitably adjusted tuple_fraction to use for
1944  * planning the query.  This adjustment is not overridable, since it reflects
1945  * plan actions that grouping_planner() will certainly take, not assumptions
1946  * about context.
1947  */
1948 static double
1949 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1950                                  int64 *offset_est, int64 *count_est)
1951 {
1952         Query      *parse = root->parse;
1953         Node       *est;
1954         double          limit_fraction;
1955
1956         /* Should not be called unless LIMIT or OFFSET */
1957         Assert(parse->limitCount || parse->limitOffset);
1958
1959         /*
1960          * Try to obtain the clause values.  We use estimate_expression_value
1961          * primarily because it can sometimes do something useful with Params.
1962          */
1963         if (parse->limitCount)
1964         {
1965                 est = estimate_expression_value(root, parse->limitCount);
1966                 if (est && IsA(est, Const))
1967                 {
1968                         if (((Const *) est)->constisnull)
1969                         {
1970                                 /* NULL indicates LIMIT ALL, ie, no limit */
1971                                 *count_est = 0; /* treat as not present */
1972                         }
1973                         else
1974                         {
1975                                 *count_est = DatumGetInt64(((Const *) est)->constvalue);
1976                                 if (*count_est <= 0)
1977                                         *count_est = 1;         /* force to at least 1 */
1978                         }
1979                 }
1980                 else
1981                         *count_est = -1;        /* can't estimate */
1982         }
1983         else
1984                 *count_est = 0;                 /* not present */
1985
1986         if (parse->limitOffset)
1987         {
1988                 est = estimate_expression_value(root, parse->limitOffset);
1989                 if (est && IsA(est, Const))
1990                 {
1991                         if (((Const *) est)->constisnull)
1992                         {
1993                                 /* Treat NULL as no offset; the executor will too */
1994                                 *offset_est = 0;        /* treat as not present */
1995                         }
1996                         else
1997                         {
1998                                 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
1999                                 if (*offset_est < 0)
2000                                         *offset_est = 0;        /* less than 0 is same as 0 */
2001                         }
2002                 }
2003                 else
2004                         *offset_est = -1;       /* can't estimate */
2005         }
2006         else
2007                 *offset_est = 0;                /* not present */
2008
2009         if (*count_est != 0)
2010         {
2011                 /*
2012                  * A LIMIT clause limits the absolute number of tuples returned.
2013                  * However, if it's not a constant LIMIT then we have to guess; for
2014                  * lack of a better idea, assume 10% of the plan's result is wanted.
2015                  */
2016                 if (*count_est < 0 || *offset_est < 0)
2017                 {
2018                         /* LIMIT or OFFSET is an expression ... punt ... */
2019                         limit_fraction = 0.10;
2020                 }
2021                 else
2022                 {
2023                         /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
2024                         limit_fraction = (double) *count_est + (double) *offset_est;
2025                 }
2026
2027                 /*
2028                  * If we have absolute limits from both caller and LIMIT, use the
2029                  * smaller value; likewise if they are both fractional.  If one is
2030                  * fractional and the other absolute, we can't easily determine which
2031                  * is smaller, but we use the heuristic that the absolute will usually
2032                  * be smaller.
2033                  */
2034                 if (tuple_fraction >= 1.0)
2035                 {
2036                         if (limit_fraction >= 1.0)
2037                         {
2038                                 /* both absolute */
2039                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
2040                         }
2041                         else
2042                         {
2043                                 /* caller absolute, limit fractional; use caller's value */
2044                         }
2045                 }
2046                 else if (tuple_fraction > 0.0)
2047                 {
2048                         if (limit_fraction >= 1.0)
2049                         {
2050                                 /* caller fractional, limit absolute; use limit */
2051                                 tuple_fraction = limit_fraction;
2052                         }
2053                         else
2054                         {
2055                                 /* both fractional */
2056                                 tuple_fraction = Min(tuple_fraction, limit_fraction);
2057                         }
2058                 }
2059                 else
2060                 {
2061                         /* no info from caller, just use limit */
2062                         tuple_fraction = limit_fraction;
2063                 }
2064         }
2065         else if (*offset_est != 0 && tuple_fraction > 0.0)
2066         {
2067                 /*
2068                  * We have an OFFSET but no LIMIT.      This acts entirely differently
2069                  * from the LIMIT case: here, we need to increase rather than decrease
2070                  * the caller's tuple_fraction, because the OFFSET acts to cause more
2071                  * tuples to be fetched instead of fewer.  This only matters if we got
2072                  * a tuple_fraction > 0, however.
2073                  *
2074                  * As above, use 10% if OFFSET is present but unestimatable.
2075                  */
2076                 if (*offset_est < 0)
2077                         limit_fraction = 0.10;
2078                 else
2079                         limit_fraction = (double) *offset_est;
2080
2081                 /*
2082                  * If we have absolute counts from both caller and OFFSET, add them
2083                  * together; likewise if they are both fractional.      If one is
2084                  * fractional and the other absolute, we want to take the larger, and
2085                  * we heuristically assume that's the fractional one.
2086                  */
2087                 if (tuple_fraction >= 1.0)
2088                 {
2089                         if (limit_fraction >= 1.0)
2090                         {
2091                                 /* both absolute, so add them together */
2092                                 tuple_fraction += limit_fraction;
2093                         }
2094                         else
2095                         {
2096                                 /* caller absolute, limit fractional; use limit */
2097                                 tuple_fraction = limit_fraction;
2098                         }
2099                 }
2100                 else
2101                 {
2102                         if (limit_fraction >= 1.0)
2103                         {
2104                                 /* caller fractional, limit absolute; use caller's value */
2105                         }
2106                         else
2107                         {
2108                                 /* both fractional, so add them together */
2109                                 tuple_fraction += limit_fraction;
2110                                 if (tuple_fraction >= 1.0)
2111                                         tuple_fraction = 0.0;           /* assume fetch all */
2112                         }
2113                 }
2114         }
2115
2116         return tuple_fraction;
2117 }
2118
2119
2120 /*
2121  * preprocess_groupclause - do preparatory work on GROUP BY clause
2122  *
2123  * The idea here is to adjust the ordering of the GROUP BY elements
2124  * (which in itself is semantically insignificant) to match ORDER BY,
2125  * thereby allowing a single sort operation to both implement the ORDER BY
2126  * requirement and set up for a Unique step that implements GROUP BY.
2127  *
2128  * In principle it might be interesting to consider other orderings of the
2129  * GROUP BY elements, which could match the sort ordering of other
2130  * possible plans (eg an indexscan) and thereby reduce cost.  We don't
2131  * bother with that, though.  Hashed grouping will frequently win anyway.
2132  *
2133  * Note: we need no comparable processing of the distinctClause because
2134  * the parser already enforced that that matches ORDER BY.
2135  */
2136 static void
2137 preprocess_groupclause(PlannerInfo *root)
2138 {
2139         Query      *parse = root->parse;
2140         List       *new_groupclause;
2141         bool            partial_match;
2142         ListCell   *sl;
2143         ListCell   *gl;
2144
2145         /* If no ORDER BY, nothing useful to do here */
2146         if (parse->sortClause == NIL)
2147                 return;
2148
2149         /*
2150          * Scan the ORDER BY clause and construct a list of matching GROUP BY
2151          * items, but only as far as we can make a matching prefix.
2152          *
2153          * This code assumes that the sortClause contains no duplicate items.
2154          */
2155         new_groupclause = NIL;
2156         foreach(sl, parse->sortClause)
2157         {
2158                 SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
2159
2160                 foreach(gl, parse->groupClause)
2161                 {
2162                         SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
2163
2164                         if (equal(gc, sc))
2165                         {
2166                                 new_groupclause = lappend(new_groupclause, gc);
2167                                 break;
2168                         }
2169                 }
2170                 if (gl == NULL)
2171                         break;                          /* no match, so stop scanning */
2172         }
2173
2174         /* Did we match all of the ORDER BY list, or just some of it? */
2175         partial_match = (sl != NULL);
2176
2177         /* If no match at all, no point in reordering GROUP BY */
2178         if (new_groupclause == NIL)
2179                 return;
2180
2181         /*
2182          * Add any remaining GROUP BY items to the new list, but only if we were
2183          * able to make a complete match.  In other words, we only rearrange the
2184          * GROUP BY list if the result is that one list is a prefix of the other
2185          * --- otherwise there's no possibility of a common sort.  Also, give up
2186          * if there are any non-sortable GROUP BY items, since then there's no
2187          * hope anyway.
2188          */
2189         foreach(gl, parse->groupClause)
2190         {
2191                 SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
2192
2193                 if (list_member_ptr(new_groupclause, gc))
2194                         continue;                       /* it matched an ORDER BY item */
2195                 if (partial_match)
2196                         return;                         /* give up, no common sort possible */
2197                 if (!OidIsValid(gc->sortop))
2198                         return;                         /* give up, GROUP BY can't be sorted */
2199                 new_groupclause = lappend(new_groupclause, gc);
2200         }
2201
2202         /* Success --- install the rearranged GROUP BY list */
2203         Assert(list_length(parse->groupClause) == list_length(new_groupclause));
2204         parse->groupClause = new_groupclause;
2205 }
2206
2207 /*
2208  * choose_hashed_grouping - should we use hashed grouping?
2209  *
2210  * Returns TRUE to select hashing, FALSE to select sorting.
2211  */
2212 static bool
2213 choose_hashed_grouping(PlannerInfo *root,
2214                                            double tuple_fraction, double limit_tuples,
2215                                            double path_rows, int path_width,
2216                                            Path *cheapest_path, Path *sorted_path,
2217                                            double dNumGroups, AggClauseCosts *agg_costs)
2218 {
2219         Query      *parse = root->parse;
2220         int                     numGroupCols = list_length(parse->groupClause);
2221         bool            can_hash;
2222         bool            can_sort;
2223         Size            hashentrysize;
2224         List       *target_pathkeys;
2225         List       *current_pathkeys;
2226         Path            hashed_p;
2227         Path            sorted_p;
2228
2229         /*
2230          * Executor doesn't support hashed aggregation with DISTINCT or ORDER BY
2231          * aggregates.  (Doing so would imply storing *all* the input values in
2232          * the hash table, and/or running many sorts in parallel, either of which
2233          * seems like a certain loser.)
2234          */
2235         can_hash = (agg_costs->numOrderedAggs == 0 &&
2236                                 grouping_is_hashable(parse->groupClause));
2237         can_sort = grouping_is_sortable(parse->groupClause);
2238
2239         /* Quick out if only one choice is workable */
2240         if (!(can_hash && can_sort))
2241         {
2242                 if (can_hash)
2243                         return true;
2244                 else if (can_sort)
2245                         return false;
2246                 else
2247                         ereport(ERROR,
2248                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2249                                          errmsg("could not implement GROUP BY"),
2250                                          errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
2251         }
2252
2253         /* Prefer sorting when enable_hashagg is off */
2254         if (!enable_hashagg)
2255                 return false;
2256
2257         /*
2258          * Don't do it if it doesn't look like the hashtable will fit into
2259          * work_mem.
2260          */
2261
2262         /* Estimate per-hash-entry space at tuple width... */
2263         hashentrysize = MAXALIGN(path_width) + MAXALIGN(sizeof(MinimalTupleData));
2264         /* plus space for pass-by-ref transition values... */
2265         hashentrysize += agg_costs->transitionSpace;
2266         /* plus the per-hash-entry overhead */
2267         hashentrysize += hash_agg_entry_size(agg_costs->numAggs);
2268
2269         if (hashentrysize * dNumGroups > work_mem * 1024L)
2270                 return false;
2271
2272         /*
2273          * When we have both GROUP BY and DISTINCT, use the more-rigorous of
2274          * DISTINCT and ORDER BY as the assumed required output sort order. This
2275          * is an oversimplification because the DISTINCT might get implemented via
2276          * hashing, but it's not clear that the case is common enough (or that our
2277          * estimates are good enough) to justify trying to solve it exactly.
2278          */
2279         if (list_length(root->distinct_pathkeys) >
2280                 list_length(root->sort_pathkeys))
2281                 target_pathkeys = root->distinct_pathkeys;
2282         else
2283                 target_pathkeys = root->sort_pathkeys;
2284
2285         /*
2286          * See if the estimated cost is no more than doing it the other way. While
2287          * avoiding the need for sorted input is usually a win, the fact that the
2288          * output won't be sorted may be a loss; so we need to do an actual cost
2289          * comparison.
2290          *
2291          * We need to consider cheapest_path + hashagg [+ final sort] versus
2292          * either cheapest_path [+ sort] + group or agg [+ final sort] or
2293          * presorted_path + group or agg [+ final sort] where brackets indicate a
2294          * step that may not be needed. We assume query_planner() will have
2295          * returned a presorted path only if it's a winner compared to
2296          * cheapest_path for this purpose.
2297          *
2298          * These path variables are dummies that just hold cost fields; we don't
2299          * make actual Paths for these steps.
2300          */
2301         cost_agg(&hashed_p, root, AGG_HASHED, agg_costs,
2302                          numGroupCols, dNumGroups,
2303                          cheapest_path->startup_cost, cheapest_path->total_cost,
2304                          path_rows);
2305         /* Result of hashed agg is always unsorted */
2306         if (target_pathkeys)
2307                 cost_sort(&hashed_p, root, target_pathkeys, hashed_p.total_cost,
2308                                   dNumGroups, path_width,
2309                                   0.0, work_mem, limit_tuples);
2310
2311         if (sorted_path)
2312         {
2313                 sorted_p.startup_cost = sorted_path->startup_cost;
2314                 sorted_p.total_cost = sorted_path->total_cost;
2315                 current_pathkeys = sorted_path->pathkeys;
2316         }
2317         else
2318         {
2319                 sorted_p.startup_cost = cheapest_path->startup_cost;
2320                 sorted_p.total_cost = cheapest_path->total_cost;
2321                 current_pathkeys = cheapest_path->pathkeys;
2322         }
2323         if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
2324         {
2325                 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
2326                                   path_rows, path_width,
2327                                   0.0, work_mem, -1.0);
2328                 current_pathkeys = root->group_pathkeys;
2329         }
2330
2331         if (parse->hasAggs)
2332                 cost_agg(&sorted_p, root, AGG_SORTED, agg_costs,
2333                                  numGroupCols, dNumGroups,
2334                                  sorted_p.startup_cost, sorted_p.total_cost,
2335                                  path_rows);
2336         else
2337                 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
2338                                    sorted_p.startup_cost, sorted_p.total_cost,
2339                                    path_rows);
2340         /* The Agg or Group node will preserve ordering */
2341         if (target_pathkeys &&
2342                 !pathkeys_contained_in(target_pathkeys, current_pathkeys))
2343                 cost_sort(&sorted_p, root, target_pathkeys, sorted_p.total_cost,
2344                                   dNumGroups, path_width,
2345                                   0.0, work_mem, limit_tuples);
2346
2347         /*
2348          * Now make the decision using the top-level tuple fraction.  First we
2349          * have to convert an absolute count (LIMIT) into fractional form.
2350          */
2351         if (tuple_fraction >= 1.0)
2352                 tuple_fraction /= dNumGroups;
2353
2354         if (compare_fractional_path_costs(&hashed_p, &sorted_p,
2355                                                                           tuple_fraction) < 0)
2356         {
2357                 /* Hashed is cheaper, so use it */
2358                 return true;
2359         }
2360         return false;
2361 }
2362
2363 /*
2364  * choose_hashed_distinct - should we use hashing for DISTINCT?
2365  *
2366  * This is fairly similar to choose_hashed_grouping, but there are enough
2367  * differences that it doesn't seem worth trying to unify the two functions.
2368  * (One difference is that we sometimes apply this after forming a Plan,
2369  * so the input alternatives can't be represented as Paths --- instead we
2370  * pass in the costs as individual variables.)
2371  *
2372  * But note that making the two choices independently is a bit bogus in
2373  * itself.      If the two could be combined into a single choice operation
2374  * it'd probably be better, but that seems far too unwieldy to be practical,
2375  * especially considering that the combination of GROUP BY and DISTINCT
2376  * isn't very common in real queries.  By separating them, we are giving
2377  * extra preference to using a sorting implementation when a common sort key
2378  * is available ... and that's not necessarily wrong anyway.
2379  *
2380  * Returns TRUE to select hashing, FALSE to select sorting.
2381  */
2382 static bool
2383 choose_hashed_distinct(PlannerInfo *root,
2384                                            double tuple_fraction, double limit_tuples,
2385                                            double path_rows, int path_width,
2386                                            Cost cheapest_startup_cost, Cost cheapest_total_cost,
2387                                            Cost sorted_startup_cost, Cost sorted_total_cost,
2388                                            List *sorted_pathkeys,
2389                                            double dNumDistinctRows)
2390 {
2391         Query      *parse = root->parse;
2392         int                     numDistinctCols = list_length(parse->distinctClause);
2393         bool            can_sort;
2394         bool            can_hash;
2395         Size            hashentrysize;
2396         List       *current_pathkeys;
2397         List       *needed_pathkeys;
2398         Path            hashed_p;
2399         Path            sorted_p;
2400
2401         /*
2402          * If we have a sortable DISTINCT ON clause, we always use sorting. This
2403          * enforces the expected behavior of DISTINCT ON.
2404          */
2405         can_sort = grouping_is_sortable(parse->distinctClause);
2406         if (can_sort && parse->hasDistinctOn)
2407                 return false;
2408
2409         can_hash = grouping_is_hashable(parse->distinctClause);
2410
2411         /* Quick out if only one choice is workable */
2412         if (!(can_hash && can_sort))
2413         {
2414                 if (can_hash)
2415                         return true;
2416                 else if (can_sort)
2417                         return false;
2418                 else
2419                         ereport(ERROR,
2420                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2421                                          errmsg("could not implement DISTINCT"),
2422                                          errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
2423         }
2424
2425         /* Prefer sorting when enable_hashagg is off */
2426         if (!enable_hashagg)
2427                 return false;
2428
2429         /*
2430          * Don't do it if it doesn't look like the hashtable will fit into
2431          * work_mem.
2432          */
2433         hashentrysize = MAXALIGN(path_width) + MAXALIGN(sizeof(MinimalTupleData));
2434
2435         if (hashentrysize * dNumDistinctRows > work_mem * 1024L)
2436                 return false;
2437
2438         /*
2439          * See if the estimated cost is no more than doing it the other way. While
2440          * avoiding the need for sorted input is usually a win, the fact that the
2441          * output won't be sorted may be a loss; so we need to do an actual cost
2442          * comparison.
2443          *
2444          * We need to consider cheapest_path + hashagg [+ final sort] versus
2445          * sorted_path [+ sort] + group [+ final sort] where brackets indicate a
2446          * step that may not be needed.
2447          *
2448          * These path variables are dummies that just hold cost fields; we don't
2449          * make actual Paths for these steps.
2450          */
2451         cost_agg(&hashed_p, root, AGG_HASHED, NULL,
2452                          numDistinctCols, dNumDistinctRows,
2453                          cheapest_startup_cost, cheapest_total_cost,
2454                          path_rows);
2455
2456         /*
2457          * Result of hashed agg is always unsorted, so if ORDER BY is present we
2458          * need to charge for the final sort.
2459          */
2460         if (parse->sortClause)
2461                 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
2462                                   dNumDistinctRows, path_width,
2463                                   0.0, work_mem, limit_tuples);
2464
2465         /*
2466          * Now for the GROUP case.      See comments in grouping_planner about the
2467          * sorting choices here --- this code should match that code.
2468          */
2469         sorted_p.startup_cost = sorted_startup_cost;
2470         sorted_p.total_cost = sorted_total_cost;
2471         current_pathkeys = sorted_pathkeys;
2472         if (parse->hasDistinctOn &&
2473                 list_length(root->distinct_pathkeys) <
2474                 list_length(root->sort_pathkeys))
2475                 needed_pathkeys = root->sort_pathkeys;
2476         else
2477                 needed_pathkeys = root->distinct_pathkeys;
2478         if (!pathkeys_contained_in(needed_pathkeys, current_pathkeys))
2479         {
2480                 if (list_length(root->distinct_pathkeys) >=
2481                         list_length(root->sort_pathkeys))
2482                         current_pathkeys = root->distinct_pathkeys;
2483                 else
2484                         current_pathkeys = root->sort_pathkeys;
2485                 cost_sort(&sorted_p, root, current_pathkeys, sorted_p.total_cost,
2486                                   path_rows, path_width,
2487                                   0.0, work_mem, -1.0);
2488         }
2489         cost_group(&sorted_p, root, numDistinctCols, dNumDistinctRows,
2490                            sorted_p.startup_cost, sorted_p.total_cost,
2491                            path_rows);
2492         if (parse->sortClause &&
2493                 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
2494                 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
2495                                   dNumDistinctRows, path_width,
2496                                   0.0, work_mem, limit_tuples);
2497
2498         /*
2499          * Now make the decision using the top-level tuple fraction.  First we
2500          * have to convert an absolute count (LIMIT) into fractional form.
2501          */
2502         if (tuple_fraction >= 1.0)
2503                 tuple_fraction /= dNumDistinctRows;
2504
2505         if (compare_fractional_path_costs(&hashed_p, &sorted_p,
2506                                                                           tuple_fraction) < 0)
2507         {
2508                 /* Hashed is cheaper, so use it */
2509                 return true;
2510         }
2511         return false;
2512 }
2513
2514 /*
2515  * make_subplanTargetList
2516  *        Generate appropriate target list when grouping is required.
2517  *
2518  * When grouping_planner inserts Aggregate, Group, or Result plan nodes
2519  * above the result of query_planner, we typically want to pass a different
2520  * target list to query_planner than the outer plan nodes should have.
2521  * This routine generates the correct target list for the subplan.
2522  *
2523  * The initial target list passed from the parser already contains entries
2524  * for all ORDER BY and GROUP BY expressions, but it will not have entries
2525  * for variables used only in HAVING clauses; so we need to add those
2526  * variables to the subplan target list.  Also, we flatten all expressions
2527  * except GROUP BY items into their component variables; the other expressions
2528  * will be computed by the inserted nodes rather than by the subplan.
2529  * For example, given a query like
2530  *              SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
2531  * we want to pass this targetlist to the subplan:
2532  *              a,b,c,d,a+b
2533  * where the a+b target will be used by the Sort/Group steps, and the
2534  * other targets will be used for computing the final results.  (In the
2535  * above example we could theoretically suppress the a and b targets and
2536  * pass down only c,d,a+b, but it's not really worth the trouble to
2537  * eliminate simple var references from the subplan.  We will avoid doing
2538  * the extra computation to recompute a+b at the outer level; see
2539  * fix_upper_expr() in setrefs.c.)
2540  *
2541  * If we are grouping or aggregating, *and* there are no non-Var grouping
2542  * expressions, then the returned tlist is effectively dummy; we do not
2543  * need to force it to be evaluated, because all the Vars it contains
2544  * should be present in the output of query_planner anyway.
2545  *
2546  * 'tlist' is the query's target list.
2547  * 'groupColIdx' receives an array of column numbers for the GROUP BY
2548  *                      expressions (if there are any) in the subplan's target list.
2549  * 'need_tlist_eval' is set true if we really need to evaluate the
2550  *                      result tlist.
2551  *
2552  * The result is the targetlist to be passed to the subplan.
2553  */
2554 static List *
2555 make_subplanTargetList(PlannerInfo *root,
2556                                            List *tlist,
2557                                            AttrNumber **groupColIdx,
2558                                            bool *need_tlist_eval)
2559 {
2560         Query      *parse = root->parse;
2561         List       *sub_tlist;
2562         List       *extravars;
2563         int                     numCols;
2564
2565         *groupColIdx = NULL;
2566
2567         /*
2568          * If we're not grouping or aggregating, there's nothing to do here;
2569          * query_planner should receive the unmodified target list.
2570          */
2571         if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual &&
2572                 !parse->hasWindowFuncs)
2573         {
2574                 *need_tlist_eval = true;
2575                 return tlist;
2576         }
2577
2578         /*
2579          * Otherwise, start with a "flattened" tlist (having just the vars
2580          * mentioned in the targetlist and HAVING qual --- but not upper-level
2581          * Vars; they will be replaced by Params later on).  Note this includes
2582          * vars used in resjunk items, so we are covering the needs of ORDER BY
2583          * and window specifications.
2584          */
2585         sub_tlist = flatten_tlist(tlist);
2586         extravars = pull_var_clause(parse->havingQual, PVC_INCLUDE_PLACEHOLDERS);
2587         sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
2588         list_free(extravars);
2589         *need_tlist_eval = false;       /* only eval if not flat tlist */
2590
2591         /*
2592          * If grouping, create sub_tlist entries for all GROUP BY expressions
2593          * (GROUP BY items that are simple Vars should be in the list already),
2594          * and make an array showing where the group columns are in the sub_tlist.
2595          */
2596         numCols = list_length(parse->groupClause);
2597         if (numCols > 0)
2598         {
2599                 int                     keyno = 0;
2600                 AttrNumber *grpColIdx;
2601                 ListCell   *gl;
2602
2603                 grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
2604                 *groupColIdx = grpColIdx;
2605
2606                 foreach(gl, parse->groupClause)
2607                 {
2608                         SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
2609                         Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
2610                         TargetEntry *te;
2611
2612                         /*
2613                          * Find or make a matching sub_tlist entry.  If the groupexpr
2614                          * isn't a Var, no point in searching.  (Note that the parser
2615                          * won't make multiple groupClause entries for the same TLE.)
2616                          */
2617                         if (groupexpr && IsA(groupexpr, Var))
2618                                 te = tlist_member(groupexpr, sub_tlist);
2619                         else
2620                                 te = NULL;
2621
2622                         if (!te)
2623                         {
2624                                 te = makeTargetEntry((Expr *) groupexpr,
2625                                                                          list_length(sub_tlist) + 1,
2626                                                                          NULL,
2627                                                                          false);
2628                                 sub_tlist = lappend(sub_tlist, te);
2629                                 *need_tlist_eval = true;                /* it's not flat anymore */
2630                         }
2631
2632                         /* and save its resno */
2633                         grpColIdx[keyno++] = te->resno;
2634                 }
2635         }
2636
2637         return sub_tlist;
2638 }
2639
2640 /*
2641  * locate_grouping_columns
2642  *              Locate grouping columns in the tlist chosen by query_planner.
2643  *
2644  * This is only needed if we don't use the sub_tlist chosen by
2645  * make_subplanTargetList.      We have to forget the column indexes found
2646  * by that routine and re-locate the grouping exprs in the real sub_tlist.
2647  */
2648 static void
2649 locate_grouping_columns(PlannerInfo *root,
2650                                                 List *tlist,
2651                                                 List *sub_tlist,
2652                                                 AttrNumber *groupColIdx)
2653 {
2654         int                     keyno = 0;
2655         ListCell   *gl;
2656
2657         /*
2658          * No work unless grouping.
2659          */
2660         if (!root->parse->groupClause)
2661         {
2662                 Assert(groupColIdx == NULL);
2663                 return;
2664         }
2665         Assert(groupColIdx != NULL);
2666
2667         foreach(gl, root->parse->groupClause)
2668         {
2669                 SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
2670                 Node       *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
2671                 TargetEntry *te = tlist_member(groupexpr, sub_tlist);
2672
2673                 if (!te)
2674                         elog(ERROR, "failed to locate grouping columns");
2675                 groupColIdx[keyno++] = te->resno;
2676         }
2677 }
2678
2679 /*
2680  * postprocess_setop_tlist
2681  *        Fix up targetlist returned by plan_set_operations().
2682  *
2683  * We need to transpose sort key info from the orig_tlist into new_tlist.
2684  * NOTE: this would not be good enough if we supported resjunk sort keys
2685  * for results of set operations --- then, we'd need to project a whole
2686  * new tlist to evaluate the resjunk columns.  For now, just ereport if we
2687  * find any resjunk columns in orig_tlist.
2688  */
2689 static List *
2690 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
2691 {
2692         ListCell   *l;
2693         ListCell   *orig_tlist_item = list_head(orig_tlist);
2694
2695         foreach(l, new_tlist)
2696         {
2697                 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
2698                 TargetEntry *orig_tle;
2699
2700                 /* ignore resjunk columns in setop result */
2701                 if (new_tle->resjunk)
2702                         continue;
2703
2704                 Assert(orig_tlist_item != NULL);
2705                 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
2706                 orig_tlist_item = lnext(orig_tlist_item);
2707                 if (orig_tle->resjunk)  /* should not happen */
2708                         elog(ERROR, "resjunk output columns are not implemented");
2709                 Assert(new_tle->resno == orig_tle->resno);
2710                 new_tle->ressortgroupref = orig_tle->ressortgroupref;
2711         }
2712         if (orig_tlist_item != NULL)
2713                 elog(ERROR, "resjunk output columns are not implemented");
2714         return new_tlist;
2715 }
2716
2717 /*
2718  * select_active_windows
2719  *              Create a list of the "active" window clauses (ie, those referenced
2720  *              by non-deleted WindowFuncs) in the order they are to be executed.
2721  */
2722 static List *
2723 select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
2724 {
2725         List       *result;
2726         List       *actives;
2727         ListCell   *lc;
2728
2729         /* First, make a list of the active windows */
2730         actives = NIL;
2731         foreach(lc, root->parse->windowClause)
2732         {
2733                 WindowClause *wc = (WindowClause *) lfirst(lc);
2734
2735                 /* It's only active if wflists shows some related WindowFuncs */
2736                 Assert(wc->winref <= wflists->maxWinRef);
2737                 if (wflists->windowFuncs[wc->winref] != NIL)
2738                         actives = lappend(actives, wc);
2739         }
2740
2741         /*
2742          * Now, ensure that windows with identical partitioning/ordering clauses
2743          * are adjacent in the list.  This is required by the SQL standard, which
2744          * says that only one sort is to be used for such windows, even if they
2745          * are otherwise distinct (eg, different names or framing clauses).
2746          *
2747          * There is room to be much smarter here, for example detecting whether
2748          * one window's sort keys are a prefix of another's (so that sorting for
2749          * the latter would do for the former), or putting windows first that
2750          * match a sort order available for the underlying query.  For the moment
2751          * we are content with meeting the spec.
2752          */
2753         result = NIL;
2754         while (actives != NIL)
2755         {
2756                 WindowClause *wc = (WindowClause *) linitial(actives);
2757                 ListCell   *prev;
2758                 ListCell   *next;
2759
2760                 /* Move wc from actives to result */
2761                 actives = list_delete_first(actives);
2762                 result = lappend(result, wc);
2763
2764                 /* Now move any matching windows from actives to result */
2765                 prev = NULL;
2766                 for (lc = list_head(actives); lc; lc = next)
2767                 {
2768                         WindowClause *wc2 = (WindowClause *) lfirst(lc);
2769
2770                         next = lnext(lc);
2771                         /* framing options are NOT to be compared here! */
2772                         if (equal(wc->partitionClause, wc2->partitionClause) &&
2773                                 equal(wc->orderClause, wc2->orderClause))
2774                         {
2775                                 actives = list_delete_cell(actives, lc, prev);
2776                                 result = lappend(result, wc2);
2777                         }
2778                         else
2779                                 prev = lc;
2780                 }
2781         }
2782
2783         return result;
2784 }
2785
2786 /*
2787  * add_volatile_sort_exprs
2788  *              Identify any volatile sort/group expressions used by the active
2789  *              windows, and add them to window_tlist if not already present.
2790  *              Return the modified window_tlist.
2791  */
2792 static List *
2793 add_volatile_sort_exprs(List *window_tlist, List *tlist, List *activeWindows)
2794 {
2795         Bitmapset  *sgrefs = NULL;
2796         ListCell   *lc;
2797
2798         /* First, collect the sortgrouprefs of the windows into a bitmapset */
2799         foreach(lc, activeWindows)
2800         {
2801                 WindowClause *wc = (WindowClause *) lfirst(lc);
2802                 ListCell   *lc2;
2803
2804                 foreach(lc2, wc->partitionClause)
2805                 {
2806                         SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc2);
2807
2808                         sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
2809                 }
2810                 foreach(lc2, wc->orderClause)
2811                 {
2812                         SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc2);
2813
2814                         sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
2815                 }
2816         }
2817
2818         /*
2819          * Now scan the original tlist to find the referenced expressions. Any
2820          * that are volatile must be added to window_tlist.
2821          *
2822          * Note: we know that the input window_tlist contains no items marked with
2823          * ressortgrouprefs, so we don't have to worry about collisions of the
2824          * reference numbers.
2825          */
2826         foreach(lc, tlist)
2827         {
2828                 TargetEntry *tle = (TargetEntry *) lfirst(lc);
2829
2830                 if (tle->ressortgroupref != 0 &&
2831                         bms_is_member(tle->ressortgroupref, sgrefs) &&
2832                         contain_volatile_functions((Node *) tle->expr))
2833                 {
2834                         TargetEntry *newtle;
2835
2836                         newtle = makeTargetEntry(tle->expr,
2837                                                                          list_length(window_tlist) + 1,
2838                                                                          NULL,
2839                                                                          false);
2840                         newtle->ressortgroupref = tle->ressortgroupref;
2841                         window_tlist = lappend(window_tlist, newtle);
2842                 }
2843         }
2844
2845         return window_tlist;
2846 }
2847
2848 /*
2849  * make_pathkeys_for_window
2850  *              Create a pathkeys list describing the required input ordering
2851  *              for the given WindowClause.
2852  *
2853  * The required ordering is first the PARTITION keys, then the ORDER keys.
2854  * In the future we might try to implement windowing using hashing, in which
2855  * case the ordering could be relaxed, but for now we always sort.
2856  */
2857 static List *
2858 make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc,
2859                                                  List *tlist, bool canonicalize)
2860 {
2861         List       *window_pathkeys;
2862         List       *window_sortclauses;
2863
2864         /* Throw error if can't sort */
2865         if (!grouping_is_sortable(wc->partitionClause))
2866                 ereport(ERROR,
2867                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2868                                  errmsg("could not implement window PARTITION BY"),
2869                                  errdetail("Window partitioning columns must be of sortable datatypes.")));
2870         if (!grouping_is_sortable(wc->orderClause))
2871                 ereport(ERROR,
2872                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2873                                  errmsg("could not implement window ORDER BY"),
2874                 errdetail("Window ordering columns must be of sortable datatypes.")));
2875
2876         /* Okay, make the combined pathkeys */
2877         window_sortclauses = list_concat(list_copy(wc->partitionClause),
2878                                                                          list_copy(wc->orderClause));
2879         window_pathkeys = make_pathkeys_for_sortclauses(root,
2880                                                                                                         window_sortclauses,
2881                                                                                                         tlist,
2882                                                                                                         canonicalize);
2883         list_free(window_sortclauses);
2884         return window_pathkeys;
2885 }
2886
2887 /*----------
2888  * get_column_info_for_window
2889  *              Get the partitioning/ordering column numbers and equality operators
2890  *              for a WindowAgg node.
2891  *
2892  * This depends on the behavior of make_pathkeys_for_window()!
2893  *
2894  * We are given the target WindowClause and an array of the input column
2895  * numbers associated with the resulting pathkeys.      In the easy case, there
2896  * are the same number of pathkey columns as partitioning + ordering columns
2897  * and we just have to copy some data around.  However, it's possible that
2898  * some of the original partitioning + ordering columns were eliminated as
2899  * redundant during the transformation to pathkeys.  (This can happen even
2900  * though the parser gets rid of obvious duplicates.  A typical scenario is a
2901  * window specification "PARTITION BY x ORDER BY y" coupled with a clause
2902  * "WHERE x = y" that causes the two sort columns to be recognized as
2903  * redundant.)  In that unusual case, we have to work a lot harder to
2904  * determine which keys are significant.
2905  *
2906  * The method used here is a bit brute-force: add the sort columns to a list
2907  * one at a time and note when the resulting pathkey list gets longer.  But
2908  * it's a sufficiently uncommon case that a faster way doesn't seem worth
2909  * the amount of code refactoring that'd be needed.
2910  *----------
2911  */
2912 static void
2913 get_column_info_for_window(PlannerInfo *root, WindowClause *wc, List *tlist,
2914                                                    int numSortCols, AttrNumber *sortColIdx,
2915                                                    int *partNumCols,
2916                                                    AttrNumber **partColIdx,
2917                                                    Oid **partOperators,
2918                                                    int *ordNumCols,
2919                                                    AttrNumber **ordColIdx,
2920                                                    Oid **ordOperators)
2921 {
2922         int                     numPart = list_length(wc->partitionClause);
2923         int                     numOrder = list_length(wc->orderClause);
2924
2925         if (numSortCols == numPart + numOrder)
2926         {
2927                 /* easy case */
2928                 *partNumCols = numPart;
2929                 *partColIdx = sortColIdx;
2930                 *partOperators = extract_grouping_ops(wc->partitionClause);
2931                 *ordNumCols = numOrder;
2932                 *ordColIdx = sortColIdx + numPart;
2933                 *ordOperators = extract_grouping_ops(wc->orderClause);
2934         }
2935         else
2936         {
2937                 List       *sortclauses;
2938                 List       *pathkeys;
2939                 int                     scidx;
2940                 ListCell   *lc;
2941
2942                 /* first, allocate what's certainly enough space for the arrays */
2943                 *partNumCols = 0;
2944                 *partColIdx = (AttrNumber *) palloc(numPart * sizeof(AttrNumber));
2945                 *partOperators = (Oid *) palloc(numPart * sizeof(Oid));
2946                 *ordNumCols = 0;
2947                 *ordColIdx = (AttrNumber *) palloc(numOrder * sizeof(AttrNumber));
2948                 *ordOperators = (Oid *) palloc(numOrder * sizeof(Oid));
2949                 sortclauses = NIL;
2950                 pathkeys = NIL;
2951                 scidx = 0;
2952                 foreach(lc, wc->partitionClause)
2953                 {
2954                         SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
2955                         List       *new_pathkeys;
2956
2957                         sortclauses = lappend(sortclauses, sgc);
2958                         new_pathkeys = make_pathkeys_for_sortclauses(root,
2959                                                                                                                  sortclauses,
2960                                                                                                                  tlist,
2961                                                                                                                  true);
2962                         if (list_length(new_pathkeys) > list_length(pathkeys))
2963                         {
2964                                 /* this sort clause is actually significant */
2965                                 (*partColIdx)[*partNumCols] = sortColIdx[scidx++];
2966                                 (*partOperators)[*partNumCols] = sgc->eqop;
2967                                 (*partNumCols)++;
2968                                 pathkeys = new_pathkeys;
2969                         }
2970                 }
2971                 foreach(lc, wc->orderClause)
2972                 {
2973                         SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
2974                         List       *new_pathkeys;
2975
2976                         sortclauses = lappend(sortclauses, sgc);
2977                         new_pathkeys = make_pathkeys_for_sortclauses(root,
2978                                                                                                                  sortclauses,
2979                                                                                                                  tlist,
2980                                                                                                                  true);
2981                         if (list_length(new_pathkeys) > list_length(pathkeys))
2982                         {
2983                                 /* this sort clause is actually significant */
2984                                 (*ordColIdx)[*ordNumCols] = sortColIdx[scidx++];
2985                                 (*ordOperators)[*ordNumCols] = sgc->eqop;
2986                                 (*ordNumCols)++;
2987                                 pathkeys = new_pathkeys;
2988                         }
2989                 }
2990                 /* complain if we didn't eat exactly the right number of sort cols */
2991                 if (scidx != numSortCols)
2992                         elog(ERROR, "failed to deconstruct sort operators into partitioning/ordering operators");
2993         }
2994 }
2995
2996
2997 /*
2998  * expression_planner
2999  *              Perform planner's transformations on a standalone expression.
3000  *
3001  * Various utility commands need to evaluate expressions that are not part
3002  * of a plannable query.  They can do so using the executor's regular
3003  * expression-execution machinery, but first the expression has to be fed
3004  * through here to transform it from parser output to something executable.
3005  *
3006  * Currently, we disallow sublinks in standalone expressions, so there's no
3007  * real "planning" involved here.  (That might not always be true though.)
3008  * What we must do is run eval_const_expressions to ensure that any function
3009  * calls are converted to positional notation and function default arguments
3010  * get inserted.  The fact that constant subexpressions get simplified is a
3011  * side-effect that is useful when the expression will get evaluated more than
3012  * once.  Also, we must fix operator function IDs.
3013  *
3014  * Note: this must not make any damaging changes to the passed-in expression
3015  * tree.  (It would actually be okay to apply fix_opfuncids to it, but since
3016  * we first do an expression_tree_mutator-based walk, what is returned will
3017  * be a new node tree.)
3018  */
3019 Expr *
3020 expression_planner(Expr *expr)
3021 {
3022         Node       *result;
3023
3024         /*
3025          * Convert named-argument function calls, insert default arguments and
3026          * simplify constant subexprs
3027          */
3028         result = eval_const_expressions(NULL, (Node *) expr);
3029
3030         /* Fill in opfuncid values if missing */
3031         fix_opfuncids(result);
3032
3033         return (Expr *) result;
3034 }
3035
3036
3037 /*
3038  * plan_cluster_use_sort
3039  *              Use the planner to decide how CLUSTER should implement sorting
3040  *
3041  * tableOid is the OID of a table to be clustered on its index indexOid
3042  * (which is already known to be a btree index).  Decide whether it's
3043  * cheaper to do an indexscan or a seqscan-plus-sort to execute the CLUSTER.
3044  * Return TRUE to use sorting, FALSE to use an indexscan.
3045  *
3046  * Note: caller had better already hold some type of lock on the table.
3047  */
3048 bool
3049 plan_cluster_use_sort(Oid tableOid, Oid indexOid)
3050 {
3051         PlannerInfo *root;
3052         Query      *query;
3053         PlannerGlobal *glob;
3054         RangeTblEntry *rte;
3055         RelOptInfo *rel;
3056         IndexOptInfo *indexInfo;
3057         QualCost        indexExprCost;
3058         Cost            comparisonCost;
3059         Path       *seqScanPath;
3060         Path            seqScanAndSortPath;
3061         IndexPath  *indexScanPath;
3062         ListCell   *lc;
3063
3064         /* Set up mostly-dummy planner state */
3065         query = makeNode(Query);
3066         query->commandType = CMD_SELECT;
3067
3068         glob = makeNode(PlannerGlobal);
3069
3070         root = makeNode(PlannerInfo);
3071         root->parse = query;
3072         root->glob = glob;
3073         root->query_level = 1;
3074         root->planner_cxt = CurrentMemoryContext;
3075         root->wt_param_id = -1;
3076
3077         /* Build a minimal RTE for the rel */
3078         rte = makeNode(RangeTblEntry);
3079         rte->rtekind = RTE_RELATION;
3080         rte->relid = tableOid;
3081         rte->relkind = RELKIND_RELATION;
3082         rte->inh = false;
3083         rte->inFromCl = true;
3084         query->rtable = list_make1(rte);
3085
3086         /* ... and insert it into PlannerInfo */
3087         root->simple_rel_array_size = 2;
3088         root->simple_rel_array = (RelOptInfo **)
3089                 palloc0(root->simple_rel_array_size * sizeof(RelOptInfo *));
3090         root->simple_rte_array = (RangeTblEntry **)
3091                 palloc0(root->simple_rel_array_size * sizeof(RangeTblEntry *));
3092         root->simple_rte_array[1] = rte;
3093
3094         /* Build RelOptInfo */
3095         rel = build_simple_rel(root, 1, RELOPT_BASEREL);
3096
3097         /* Locate IndexOptInfo for the target index */
3098         indexInfo = NULL;
3099         foreach(lc, rel->indexlist)
3100         {
3101                 indexInfo = (IndexOptInfo *) lfirst(lc);
3102                 if (indexInfo->indexoid == indexOid)
3103                         break;
3104         }
3105
3106         /*
3107          * It's possible that get_relation_info did not generate an IndexOptInfo
3108          * for the desired index; this could happen if it's not yet reached its
3109          * indcheckxmin usability horizon, or if it's a system index and we're
3110          * ignoring system indexes.  In such cases we should tell CLUSTER to not
3111          * trust the index contents but use seqscan-and-sort.
3112          */
3113         if (lc == NULL)                         /* not in the list? */
3114                 return true;                    /* use sort */
3115
3116         /*
3117          * Rather than doing all the pushups that would be needed to use
3118          * set_baserel_size_estimates, just do a quick hack for rows and width.
3119          */
3120         rel->rows = rel->tuples;
3121         rel->width = get_relation_data_width(tableOid, NULL);
3122
3123         root->total_table_pages = rel->pages;
3124
3125         /*
3126          * Determine eval cost of the index expressions, if any.  We need to
3127          * charge twice that amount for each tuple comparison that happens during
3128          * the sort, since tuplesort.c will have to re-evaluate the index
3129          * expressions each time.  (XXX that's pretty inefficient...)
3130          */
3131         cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
3132         comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
3133
3134         /* Estimate the cost of seq scan + sort */
3135         seqScanPath = create_seqscan_path(root, rel);
3136         cost_sort(&seqScanAndSortPath, root, NIL,
3137                           seqScanPath->total_cost, rel->tuples, rel->width,
3138                           comparisonCost, maintenance_work_mem, -1.0);
3139
3140         /* Estimate the cost of index scan */
3141         indexScanPath = create_index_path(root, indexInfo,
3142                                                                           NIL, NIL, NIL,
3143                                                                           ForwardScanDirection, NULL);
3144
3145         return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
3146 }