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