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