1 /*-------------------------------------------------------------------------
4 * The query optimizer external interface.
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/optimizer/plan/planner.c
13 *-------------------------------------------------------------------------
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"
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"
49 double cursor_tuple_fraction = DEFAULT_CURSOR_TUPLE_FRACTION;
51 /* Hook for plugins to get control in planner() */
52 planner_hook_type planner_hook = NULL;
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
64 static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
65 static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
66 static Plan *inheritance_planner(PlannerInfo *root);
67 static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
68 static bool is_dummy_plan(Plan *plan);
69 static void preprocess_rowmarks(PlannerInfo *root);
70 static double preprocess_limit(PlannerInfo *root,
71 double tuple_fraction,
72 int64 *offset_est, int64 *count_est);
73 static void preprocess_groupclause(PlannerInfo *root);
74 static bool choose_hashed_grouping(PlannerInfo *root,
75 double tuple_fraction, double limit_tuples,
76 double path_rows, int path_width,
77 Path *cheapest_path, Path *sorted_path,
78 double dNumGroups, AggClauseCosts *agg_costs);
79 static bool choose_hashed_distinct(PlannerInfo *root,
80 double tuple_fraction, double limit_tuples,
81 double path_rows, int path_width,
82 Cost cheapest_startup_cost, Cost cheapest_total_cost,
83 Cost sorted_startup_cost, Cost sorted_total_cost,
84 List *sorted_pathkeys,
85 double dNumDistinctRows);
86 static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
87 AttrNumber **groupColIdx, bool *need_tlist_eval);
88 static int get_grouping_column_index(Query *parse, TargetEntry *tle);
89 static void locate_grouping_columns(PlannerInfo *root,
92 AttrNumber *groupColIdx);
93 static List *postprocess_setop_tlist(List *new_tlist, List *orig_tlist);
94 static List *select_active_windows(PlannerInfo *root, WindowFuncLists *wflists);
95 static List *add_volatile_sort_exprs(List *window_tlist, List *tlist,
97 static List *make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc,
98 List *tlist, bool canonicalize);
99 static void get_column_info_for_window(PlannerInfo *root, WindowClause *wc,
101 int numSortCols, AttrNumber *sortColIdx,
103 AttrNumber **partColIdx,
106 AttrNumber **ordColIdx,
110 /*****************************************************************************
112 * Query optimizer entry point
114 * To support loadable plugins that monitor or modify planner behavior,
115 * we provide a hook variable that lets a plugin get control before and
116 * after the standard planning process. The plugin would normally call
117 * standard_planner().
119 * Note to plugin authors: standard_planner() scribbles on its Query input,
120 * so you'd better copy that data structure if you want to plan more than once.
122 *****************************************************************************/
124 planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
129 result = (*planner_hook) (parse, cursorOptions, boundParams);
131 result = standard_planner(parse, cursorOptions, boundParams);
136 standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
140 double tuple_fraction;
147 /* Cursor options may come from caller or from DECLARE CURSOR stmt */
148 if (parse->utilityStmt &&
149 IsA(parse->utilityStmt, DeclareCursorStmt))
150 cursorOptions |= ((DeclareCursorStmt *) parse->utilityStmt)->options;
153 * Set up global state for this planner invocation. This data is needed
154 * across all levels of sub-Query that might exist in the given command,
155 * so we keep it in a separate struct that's linked to by each per-Query
158 glob = makeNode(PlannerGlobal);
160 glob->boundParams = boundParams;
161 glob->paramlist = NIL;
162 glob->subplans = NIL;
163 glob->subrtables = NIL;
164 glob->subrowmarks = NIL;
165 glob->rewindPlanIDs = NULL;
166 glob->finalrtable = NIL;
167 glob->finalrowmarks = NIL;
168 glob->resultRelations = NIL;
169 glob->relationOids = NIL;
170 glob->invalItems = NIL;
172 glob->lastRowMarkId = 0;
173 glob->transientPlan = false;
175 /* Determine what fraction of the plan is likely to be scanned */
176 if (cursorOptions & CURSOR_OPT_FAST_PLAN)
179 * We have no real idea how many tuples the user will ultimately FETCH
180 * from a cursor, but it is often the case that he doesn't want 'em
181 * all, or would prefer a fast-start plan anyway so that he can
182 * process some of the tuples sooner. Use a GUC parameter to decide
183 * what fraction to optimize for.
185 tuple_fraction = cursor_tuple_fraction;
188 * We document cursor_tuple_fraction as simply being a fraction, which
189 * means the edge cases 0 and 1 have to be treated specially here. We
190 * convert 1 to 0 ("all the tuples") and 0 to a very small fraction.
192 if (tuple_fraction >= 1.0)
193 tuple_fraction = 0.0;
194 else if (tuple_fraction <= 0.0)
195 tuple_fraction = 1e-10;
199 /* Default assumption is we need all the tuples */
200 tuple_fraction = 0.0;
203 /* primary planning entry point (may recurse for subqueries) */
204 top_plan = subquery_planner(glob, parse, NULL,
205 false, tuple_fraction, &root);
208 * If creating a plan for a scrollable cursor, make sure it can run
209 * backwards on demand. Add a Material node at the top at need.
211 if (cursorOptions & CURSOR_OPT_SCROLL)
213 if (!ExecSupportsBackwardScan(top_plan))
214 top_plan = materialize_finished_plan(top_plan);
217 /* final cleanup of the plan */
218 Assert(glob->finalrtable == NIL);
219 Assert(glob->finalrowmarks == NIL);
220 Assert(glob->resultRelations == NIL);
221 top_plan = set_plan_references(glob, top_plan,
224 /* ... and the subplans (both regular subplans and initplans) */
225 Assert(list_length(glob->subplans) == list_length(glob->subrtables));
226 Assert(list_length(glob->subplans) == list_length(glob->subrowmarks));
227 lrt = list_head(glob->subrtables);
228 lrm = list_head(glob->subrowmarks);
229 foreach(lp, glob->subplans)
231 Plan *subplan = (Plan *) lfirst(lp);
232 List *subrtable = (List *) lfirst(lrt);
233 List *subrowmark = (List *) lfirst(lrm);
235 lfirst(lp) = set_plan_references(glob, subplan,
236 subrtable, subrowmark);
241 /* build the PlannedStmt result */
242 result = makeNode(PlannedStmt);
244 result->commandType = parse->commandType;
245 result->hasReturning = (parse->returningList != NIL);
246 result->hasModifyingCTE = parse->hasModifyingCTE;
247 result->canSetTag = parse->canSetTag;
248 result->transientPlan = glob->transientPlan;
249 result->planTree = top_plan;
250 result->rtable = glob->finalrtable;
251 result->resultRelations = glob->resultRelations;
252 result->utilityStmt = parse->utilityStmt;
253 result->intoClause = parse->intoClause;
254 result->subplans = glob->subplans;
255 result->rewindPlanIDs = glob->rewindPlanIDs;
256 result->rowMarks = glob->finalrowmarks;
257 result->relationOids = glob->relationOids;
258 result->invalItems = glob->invalItems;
259 result->nParamExec = list_length(glob->paramlist);
265 /*--------------------
267 * Invokes the planner on a subquery. We recurse to here for each
268 * sub-SELECT found in the query tree.
270 * glob is the global state for the current planner run.
271 * parse is the querytree produced by the parser & rewriter.
272 * parent_root is the immediate parent Query's info (NULL at the top level).
273 * hasRecursion is true if this is a recursive WITH query.
274 * tuple_fraction is the fraction of tuples we expect will be retrieved.
275 * tuple_fraction is interpreted as explained for grouping_planner, below.
277 * If subroot isn't NULL, we pass back the query's final PlannerInfo struct;
278 * among other things this tells the output sort ordering of the plan.
280 * Basically, this routine does the stuff that should only be done once
281 * per Query object. It then calls grouping_planner. At one time,
282 * grouping_planner could be invoked recursively on the same Query object;
283 * that's not currently true, but we keep the separation between the two
284 * routines anyway, in case we need it again someday.
286 * subquery_planner will be called recursively to handle sub-Query nodes
287 * found within the query's expressions and rangetable.
289 * Returns a query plan.
290 *--------------------
293 subquery_planner(PlannerGlobal *glob, Query *parse,
294 PlannerInfo *parent_root,
295 bool hasRecursion, double tuple_fraction,
296 PlannerInfo **subroot)
298 int num_old_subplans = list_length(glob->subplans);
305 /* Create a PlannerInfo data structure for this subquery */
306 root = makeNode(PlannerInfo);
309 root->query_level = parent_root ? parent_root->query_level + 1 : 1;
310 root->parent_root = parent_root;
311 root->planner_cxt = CurrentMemoryContext;
312 root->init_plans = NIL;
313 root->cte_plan_ids = NIL;
314 root->eq_classes = NIL;
315 root->append_rel_list = NIL;
316 root->rowMarks = NIL;
317 root->hasInheritedTarget = false;
319 root->hasRecursion = hasRecursion;
321 root->wt_param_id = SS_assign_special_param(root);
323 root->wt_param_id = -1;
324 root->non_recursive_plan = NULL;
327 * If there is a WITH list, process each WITH query and build an initplan
328 * SubPlan structure for it.
331 SS_process_ctes(root);
334 * Look for ANY and EXISTS SubLinks in WHERE and JOIN/ON clauses, and try
335 * to transform them into joins. Note that this step does not descend
336 * into subqueries; if we pull up any subqueries below, their SubLinks are
337 * processed just before pulling them up.
339 if (parse->hasSubLinks)
340 pull_up_sublinks(root);
343 * Scan the rangetable for set-returning functions, and inline them if
344 * possible (producing subqueries that might get pulled up next).
345 * Recursion issues here are handled in the same way as for SubLinks.
347 inline_set_returning_functions(root);
350 * Check to see if any subqueries in the jointree can be merged into this
353 parse->jointree = (FromExpr *)
354 pull_up_subqueries(root, (Node *) parse->jointree, NULL, NULL);
357 * If this is a simple UNION ALL query, flatten it into an appendrel. We
358 * do this now because it requires applying pull_up_subqueries to the leaf
359 * queries of the UNION ALL, which weren't touched above because they
360 * weren't referenced by the jointree (they will be after we do this).
362 if (parse->setOperations)
363 flatten_simple_union_all(root);
366 * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
367 * avoid the expense of doing flatten_join_alias_vars(). Also check for
368 * outer joins --- if none, we can skip reduce_outer_joins(). This must be
369 * done after we have done pull_up_subqueries, of course.
371 root->hasJoinRTEs = false;
372 hasOuterJoins = false;
373 foreach(l, parse->rtable)
375 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
377 if (rte->rtekind == RTE_JOIN)
379 root->hasJoinRTEs = true;
380 if (IS_OUTER_JOIN(rte->jointype))
382 hasOuterJoins = true;
383 /* Can quit scanning once we find an outer join */
390 * Preprocess RowMark information. We need to do this after subquery
391 * pullup (so that all non-inherited RTEs are present) and before
392 * inheritance expansion (so that the info is available for
393 * expand_inherited_tables to examine and modify).
395 preprocess_rowmarks(root);
398 * Expand any rangetable entries that are inheritance sets into "append
399 * relations". This can add entries to the rangetable, but they must be
400 * plain base relations not joins, so it's OK (and marginally more
401 * efficient) to do it after checking for join RTEs. We must do it after
402 * pulling up subqueries, else we'd fail to handle inherited tables in
405 expand_inherited_tables(root);
408 * Set hasHavingQual to remember if HAVING clause is present. Needed
409 * because preprocess_expression will reduce a constant-true condition to
410 * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
412 root->hasHavingQual = (parse->havingQual != NULL);
414 /* Clear this flag; might get set in distribute_qual_to_rels */
415 root->hasPseudoConstantQuals = false;
418 * Do expression preprocessing on targetlist and quals, as well as other
419 * random expressions in the querytree. Note that we do not need to
420 * handle sort/group expressions explicitly, because they are actually
421 * part of the targetlist.
423 parse->targetList = (List *)
424 preprocess_expression(root, (Node *) parse->targetList,
427 parse->returningList = (List *)
428 preprocess_expression(root, (Node *) parse->returningList,
431 preprocess_qual_conditions(root, (Node *) parse->jointree);
433 parse->havingQual = preprocess_expression(root, parse->havingQual,
436 foreach(l, parse->windowClause)
438 WindowClause *wc = (WindowClause *) lfirst(l);
440 /* partitionClause/orderClause are sort/group expressions */
441 wc->startOffset = preprocess_expression(root, wc->startOffset,
443 wc->endOffset = preprocess_expression(root, wc->endOffset,
447 parse->limitOffset = preprocess_expression(root, parse->limitOffset,
449 parse->limitCount = preprocess_expression(root, parse->limitCount,
452 root->append_rel_list = (List *)
453 preprocess_expression(root, (Node *) root->append_rel_list,
456 /* Also need to preprocess expressions for function and values RTEs */
457 foreach(l, parse->rtable)
459 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
461 if (rte->rtekind == RTE_FUNCTION)
462 rte->funcexpr = preprocess_expression(root, rte->funcexpr,
464 else if (rte->rtekind == RTE_VALUES)
465 rte->values_lists = (List *)
466 preprocess_expression(root, (Node *) rte->values_lists,
471 * In some cases we may want to transfer a HAVING clause into WHERE. We
472 * cannot do so if the HAVING clause contains aggregates (obviously) or
473 * volatile functions (since a HAVING clause is supposed to be executed
474 * only once per group). Also, it may be that the clause is so expensive
475 * to execute that we're better off doing it only once per group, despite
476 * the loss of selectivity. This is hard to estimate short of doing the
477 * entire planning process twice, so we use a heuristic: clauses
478 * containing subplans are left in HAVING. Otherwise, we move or copy the
479 * HAVING clause into WHERE, in hopes of eliminating tuples before
480 * aggregation instead of after.
482 * If the query has explicit grouping then we can simply move such a
483 * clause into WHERE; any group that fails the clause will not be in the
484 * output because none of its tuples will reach the grouping or
485 * aggregation stage. Otherwise we must have a degenerate (variable-free)
486 * HAVING clause, which we put in WHERE so that query_planner() can use it
487 * in a gating Result node, but also keep in HAVING to ensure that we
488 * don't emit a bogus aggregated row. (This could be done better, but it
489 * seems not worth optimizing.)
491 * Note that both havingQual and parse->jointree->quals are in
492 * implicitly-ANDed-list form at this point, even though they are declared
496 foreach(l, (List *) parse->havingQual)
498 Node *havingclause = (Node *) lfirst(l);
500 if (contain_agg_clause(havingclause) ||
501 contain_volatile_functions(havingclause) ||
502 contain_subplans(havingclause))
504 /* keep it in HAVING */
505 newHaving = lappend(newHaving, havingclause);
507 else if (parse->groupClause)
509 /* move it to WHERE */
510 parse->jointree->quals = (Node *)
511 lappend((List *) parse->jointree->quals, havingclause);
515 /* put a copy in WHERE, keep it in HAVING */
516 parse->jointree->quals = (Node *)
517 lappend((List *) parse->jointree->quals,
518 copyObject(havingclause));
519 newHaving = lappend(newHaving, havingclause);
522 parse->havingQual = (Node *) newHaving;
525 * If we have any outer joins, try to reduce them to plain inner joins.
526 * This step is most easily done after we've done expression
530 reduce_outer_joins(root);
533 * Do the main planning. If we have an inherited target relation, that
534 * needs special processing, else go straight to grouping_planner.
536 if (parse->resultRelation &&
537 rt_fetch(parse->resultRelation, parse->rtable)->inh)
538 plan = inheritance_planner(root);
541 plan = grouping_planner(root, tuple_fraction);
542 /* If it's not SELECT, we need a ModifyTable node */
543 if (parse->commandType != CMD_SELECT)
545 List *returningLists;
549 * Deal with the RETURNING clause if any. It's convenient to pass
550 * the returningList through setrefs.c now rather than at top
551 * level (if we waited, handling inherited UPDATE/DELETE would be
554 if (parse->returningList)
558 Assert(parse->resultRelation);
559 rlist = set_returning_clause_references(root->glob,
560 parse->returningList,
562 parse->resultRelation);
563 returningLists = list_make1(rlist);
566 returningLists = NIL;
569 * If there was a FOR UPDATE/SHARE clause, the LockRows node will
570 * have dealt with fetching non-locked marked rows, else we need
571 * to have ModifyTable do that.
576 rowMarks = root->rowMarks;
578 plan = (Plan *) make_modifytable(parse->commandType,
580 list_make1_int(parse->resultRelation),
584 SS_assign_special_param(root));
589 * If any subplans were generated, or if there are any parameters to worry
590 * about, build initPlan list and extParam/allParam sets for plan nodes,
591 * and attach the initPlans to the top plan node.
593 if (list_length(glob->subplans) != num_old_subplans ||
594 root->glob->paramlist != NIL)
595 SS_finalize_plan(root, plan, true);
597 /* Return internal info if caller wants it */
605 * preprocess_expression
606 * Do subquery_planner's preprocessing work for an expression,
607 * which can be a targetlist, a WHERE clause (including JOIN/ON
608 * conditions), or a HAVING clause.
611 preprocess_expression(PlannerInfo *root, Node *expr, int kind)
614 * Fall out quickly if expression is empty. This occurs often enough to
615 * be worth checking. Note that null->null is the correct conversion for
616 * implicit-AND result format, too.
622 * If the query has any join RTEs, replace join alias variables with
623 * base-relation variables. We must do this before sublink processing,
624 * else sublinks expanded out from join aliases wouldn't get processed. We
625 * can skip it in VALUES lists, however, since they can't contain any Vars
628 if (root->hasJoinRTEs && kind != EXPRKIND_VALUES)
629 expr = flatten_join_alias_vars(root, expr);
632 * Simplify constant expressions.
634 * Note: an essential effect of this is to convert named-argument function
635 * calls to positional notation and insert the current actual values of
636 * any default arguments for functions. To ensure that happens, we *must*
637 * process all expressions here. Previous PG versions sometimes skipped
638 * const-simplification if it didn't seem worth the trouble, but we can't
641 * Note: this also flattens nested AND and OR expressions into N-argument
642 * form. All processing of a qual expression after this point must be
643 * careful to maintain AND/OR flatness --- that is, do not generate a tree
644 * with AND directly under AND, nor OR directly under OR.
646 expr = eval_const_expressions(root, expr);
649 * If it's a qual or havingQual, canonicalize it.
651 if (kind == EXPRKIND_QUAL)
653 expr = (Node *) canonicalize_qual((Expr *) expr);
655 #ifdef OPTIMIZER_DEBUG
656 printf("After canonicalize_qual()\n");
661 /* Expand SubLinks to SubPlans */
662 if (root->parse->hasSubLinks)
663 expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL));
666 * XXX do not insert anything here unless you have grokked the comments in
667 * SS_replace_correlation_vars ...
670 /* Replace uplevel vars with Param nodes (this IS possible in VALUES) */
671 if (root->query_level > 1)
672 expr = SS_replace_correlation_vars(root, expr);
675 * If it's a qual or havingQual, convert it to implicit-AND format. (We
676 * don't want to do this before eval_const_expressions, since the latter
677 * would be unable to simplify a top-level AND correctly. Also,
678 * SS_process_sublinks expects explicit-AND format.)
680 if (kind == EXPRKIND_QUAL)
681 expr = (Node *) make_ands_implicit((Expr *) expr);
687 * preprocess_qual_conditions
688 * Recursively scan the query's jointree and do subquery_planner's
689 * preprocessing work on each qual condition found therein.
692 preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
696 if (IsA(jtnode, RangeTblRef))
698 /* nothing to do here */
700 else if (IsA(jtnode, FromExpr))
702 FromExpr *f = (FromExpr *) jtnode;
705 foreach(l, f->fromlist)
706 preprocess_qual_conditions(root, lfirst(l));
708 f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
710 else if (IsA(jtnode, JoinExpr))
712 JoinExpr *j = (JoinExpr *) jtnode;
714 preprocess_qual_conditions(root, j->larg);
715 preprocess_qual_conditions(root, j->rarg);
717 j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
720 elog(ERROR, "unrecognized node type: %d",
721 (int) nodeTag(jtnode));
725 * inheritance_planner
726 * Generate a plan in the case where the result relation is an
729 * We have to handle this case differently from cases where a source relation
730 * is an inheritance set. Source inheritance is expanded at the bottom of the
731 * plan tree (see allpaths.c), but target inheritance has to be expanded at
732 * the top. The reason is that for UPDATE, each target relation needs a
733 * different targetlist matching its own column set. Fortunately,
734 * the UPDATE/DELETE target can never be the nullable side of an outer join,
735 * so it's OK to generate the plan this way.
737 * Returns a query plan.
740 inheritance_planner(PlannerInfo *root)
742 Query *parse = root->parse;
743 int parentRTindex = parse->resultRelation;
744 List *subplans = NIL;
745 List *resultRelations = NIL;
746 List *returningLists = NIL;
753 foreach(l, root->append_rel_list)
755 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
758 /* append_rel_list contains all append rels; ignore others */
759 if (appinfo->parent_relid != parentRTindex)
763 * Generate modified query with this rel as target.
765 memcpy(&subroot, root, sizeof(PlannerInfo));
766 subroot.parse = (Query *)
767 adjust_appendrel_attrs((Node *) parse,
769 subroot.init_plans = NIL;
770 subroot.hasInheritedTarget = true;
771 /* We needn't modify the child's append_rel_list */
772 /* There shouldn't be any OJ info to translate, as yet */
773 Assert(subroot.join_info_list == NIL);
774 /* and we haven't created PlaceHolderInfos, either */
775 Assert(subroot.placeholder_list == NIL);
778 subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
781 * If this child rel was excluded by constraint exclusion, exclude it
784 if (is_dummy_plan(subplan))
787 /* Save rtable from first rel for use below */
789 rtable = subroot.parse->rtable;
791 subplans = lappend(subplans, subplan);
793 /* Make sure any initplans from this rel get into the outer list */
794 root->init_plans = list_concat(root->init_plans, subroot.init_plans);
796 /* Build list of target-relation RT indexes */
797 resultRelations = lappend_int(resultRelations, appinfo->child_relid);
799 /* Build list of per-relation RETURNING targetlists */
800 if (parse->returningList)
804 rlist = set_returning_clause_references(root->glob,
805 subroot.parse->returningList,
807 appinfo->child_relid);
808 returningLists = lappend(returningLists, rlist);
812 /* Mark result as unordered (probably unnecessary) */
813 root->query_pathkeys = NIL;
816 * If we managed to exclude every child rel, return a dummy plan; it
817 * doesn't even need a ModifyTable node.
821 /* although dummy, it must have a valid tlist for executor */
822 tlist = preprocess_targetlist(root, parse->targetList);
823 return (Plan *) make_result(root,
825 (Node *) list_make1(makeBoolConst(false,
831 * Planning might have modified the rangetable, due to changes of the
832 * Query structures inside subquery RTEs. We have to ensure that this
833 * gets propagated back to the master copy. But can't do this until we
834 * are done planning, because all the calls to grouping_planner need
835 * virgin sub-Queries to work from. (We are effectively assuming that
836 * sub-Queries will get planned identically each time, or at least that
837 * the impacts on their rangetables will be the same each time.)
839 * XXX should clean this up someday
841 parse->rtable = rtable;
844 * If there was a FOR UPDATE/SHARE clause, the LockRows node will have
845 * dealt with fetching non-locked marked rows, else we need to have
846 * ModifyTable do that.
851 rowMarks = root->rowMarks;
853 /* And last, tack on a ModifyTable node to do the UPDATE/DELETE work */
854 return (Plan *) make_modifytable(parse->commandType,
860 SS_assign_special_param(root));
863 /*--------------------
865 * Perform planning steps related to grouping, aggregation, etc.
866 * This primarily means adding top-level processing to the basic
867 * query plan produced by query_planner.
869 * tuple_fraction is the fraction of tuples we expect will be retrieved
871 * tuple_fraction is interpreted as follows:
872 * 0: expect all tuples to be retrieved (normal case)
873 * 0 < tuple_fraction < 1: expect the given fraction of tuples available
874 * from the plan to be retrieved
875 * tuple_fraction >= 1: tuple_fraction is the absolute number of tuples
876 * expected to be retrieved (ie, a LIMIT specification)
878 * Returns a query plan. Also, root->query_pathkeys is returned as the
879 * actual output ordering of the plan (in pathkey format).
880 *--------------------
883 grouping_planner(PlannerInfo *root, double tuple_fraction)
885 Query *parse = root->parse;
886 List *tlist = parse->targetList;
887 int64 offset_est = 0;
889 double limit_tuples = -1.0;
891 List *current_pathkeys;
892 double dNumGroups = 0;
893 bool use_hashed_distinct = false;
894 bool tested_hashed_distinct = false;
896 /* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
897 if (parse->limitCount || parse->limitOffset)
899 tuple_fraction = preprocess_limit(root, tuple_fraction,
900 &offset_est, &count_est);
903 * If we have a known LIMIT, and don't have an unknown OFFSET, we can
904 * estimate the effects of using a bounded sort.
906 if (count_est > 0 && offset_est >= 0)
907 limit_tuples = (double) count_est + (double) offset_est;
910 if (parse->setOperations)
912 List *set_sortclauses;
915 * If there's a top-level ORDER BY, assume we have to fetch all the
916 * tuples. This might be too simplistic given all the hackery below
917 * to possibly avoid the sort; but the odds of accurate estimates here
918 * are pretty low anyway.
920 if (parse->sortClause)
921 tuple_fraction = 0.0;
924 * Construct the plan for set operations. The result will not need
925 * any work except perhaps a top-level sort and/or LIMIT. Note that
926 * any special work for recursive unions is the responsibility of
927 * plan_set_operations.
929 result_plan = plan_set_operations(root, tuple_fraction,
933 * Calculate pathkeys representing the sort order (if any) of the set
934 * operation's result. We have to do this before overwriting the sort
937 current_pathkeys = make_pathkeys_for_sortclauses(root,
939 result_plan->targetlist,
943 * We should not need to call preprocess_targetlist, since we must be
944 * in a SELECT query node. Instead, use the targetlist returned by
945 * plan_set_operations (since this tells whether it returned any
946 * resjunk columns!), and transfer any sort key information from the
949 Assert(parse->commandType == CMD_SELECT);
951 tlist = postprocess_setop_tlist(copyObject(result_plan->targetlist),
955 * Can't handle FOR UPDATE/SHARE here (parser should have checked
956 * already, but let's make sure).
960 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
961 errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
964 * Calculate pathkeys that represent result ordering requirements
966 Assert(parse->distinctClause == NIL);
967 root->sort_pathkeys = make_pathkeys_for_sortclauses(root,
974 /* No set operations, do regular planning */
976 double sub_limit_tuples;
977 AttrNumber *groupColIdx = NULL;
978 bool need_tlist_eval = true;
984 AggClauseCosts agg_costs;
988 bool use_hashed_grouping = false;
989 WindowFuncLists *wflists = NULL;
990 List *activeWindows = NIL;
992 MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
994 /* A recursive query should always have setOperations */
995 Assert(!root->hasRecursion);
997 /* Preprocess GROUP BY clause, if any */
998 if (parse->groupClause)
999 preprocess_groupclause(root);
1000 numGroupCols = list_length(parse->groupClause);
1002 /* Preprocess targetlist */
1003 tlist = preprocess_targetlist(root, tlist);
1006 * Locate any window functions in the tlist. (We don't need to look
1007 * anywhere else, since expressions used in ORDER BY will be in there
1008 * too.) Note that they could all have been eliminated by constant
1009 * folding, in which case we don't need to do any more work.
1011 if (parse->hasWindowFuncs)
1013 wflists = find_window_functions((Node *) tlist,
1014 list_length(parse->windowClause));
1015 if (wflists->numWindowFuncs > 0)
1016 activeWindows = select_active_windows(root, wflists);
1018 parse->hasWindowFuncs = false;
1022 * Generate appropriate target list for subplan; may be different from
1023 * tlist if grouping or aggregation is needed.
1025 sub_tlist = make_subplanTargetList(root, tlist,
1026 &groupColIdx, &need_tlist_eval);
1029 * Do aggregate preprocessing, if the query has any aggs.
1031 * Note: think not that we can turn off hasAggs if we find no aggs. It
1032 * is possible for constant-expression simplification to remove all
1033 * explicit references to aggs, but we still have to follow the
1034 * aggregate semantics (eg, producing only one output row).
1039 * Collect statistics about aggregates for estimating costs. Note:
1040 * we do not attempt to detect duplicate aggregates here; a
1041 * somewhat-overestimated cost is okay for our present purposes.
1043 count_agg_clauses(root, (Node *) tlist, &agg_costs);
1044 count_agg_clauses(root, parse->havingQual, &agg_costs);
1047 * Preprocess MIN/MAX aggregates, if any. Note: be careful about
1048 * adding logic between here and the optimize_minmax_aggregates
1049 * call. Anything that is needed in MIN/MAX-optimizable cases
1050 * will have to be duplicated in planagg.c.
1052 preprocess_minmax_aggregates(root, tlist);
1056 * Calculate pathkeys that represent grouping/ordering requirements.
1057 * Stash them in PlannerInfo so that query_planner can canonicalize
1058 * them after EquivalenceClasses have been formed. The sortClause is
1059 * certainly sort-able, but GROUP BY and DISTINCT might not be, in
1060 * which case we just leave their pathkeys empty.
1062 if (parse->groupClause &&
1063 grouping_is_sortable(parse->groupClause))
1064 root->group_pathkeys =
1065 make_pathkeys_for_sortclauses(root,
1070 root->group_pathkeys = NIL;
1072 /* We consider only the first (bottom) window in pathkeys logic */
1073 if (activeWindows != NIL)
1075 WindowClause *wc = (WindowClause *) linitial(activeWindows);
1077 root->window_pathkeys = make_pathkeys_for_window(root,
1083 root->window_pathkeys = NIL;
1085 if (parse->distinctClause &&
1086 grouping_is_sortable(parse->distinctClause))
1087 root->distinct_pathkeys =
1088 make_pathkeys_for_sortclauses(root,
1089 parse->distinctClause,
1093 root->distinct_pathkeys = NIL;
1095 root->sort_pathkeys =
1096 make_pathkeys_for_sortclauses(root,
1102 * Figure out whether we want a sorted result from query_planner.
1104 * If we have a sortable GROUP BY clause, then we want a result sorted
1105 * properly for grouping. Otherwise, if we have window functions to
1106 * evaluate, we try to sort for the first window. Otherwise, if
1107 * there's a sortable DISTINCT clause that's more rigorous than the
1108 * ORDER BY clause, we try to produce output that's sufficiently well
1109 * sorted for the DISTINCT. Otherwise, if there is an ORDER BY
1110 * clause, we want to sort by the ORDER BY clause.
1112 * Note: if we have both ORDER BY and GROUP BY, and ORDER BY is a
1113 * superset of GROUP BY, it would be tempting to request sort by ORDER
1114 * BY --- but that might just leave us failing to exploit an available
1115 * sort order at all. Needs more thought. The choice for DISTINCT
1116 * versus ORDER BY is much easier, since we know that the parser
1117 * ensured that one is a superset of the other.
1119 if (root->group_pathkeys)
1120 root->query_pathkeys = root->group_pathkeys;
1121 else if (root->window_pathkeys)
1122 root->query_pathkeys = root->window_pathkeys;
1123 else if (list_length(root->distinct_pathkeys) >
1124 list_length(root->sort_pathkeys))
1125 root->query_pathkeys = root->distinct_pathkeys;
1126 else if (root->sort_pathkeys)
1127 root->query_pathkeys = root->sort_pathkeys;
1129 root->query_pathkeys = NIL;
1132 * Figure out whether there's a hard limit on the number of rows that
1133 * query_planner's result subplan needs to return. Even if we know a
1134 * hard limit overall, it doesn't apply if the query has any
1135 * grouping/aggregation operations.
1137 if (parse->groupClause ||
1138 parse->distinctClause ||
1140 parse->hasWindowFuncs ||
1141 root->hasHavingQual)
1142 sub_limit_tuples = -1.0;
1144 sub_limit_tuples = limit_tuples;
1147 * Generate the best unsorted and presorted paths for this Query (but
1148 * note there may not be any presorted path). query_planner will also
1149 * estimate the number of groups in the query, and canonicalize all
1152 query_planner(root, sub_tlist, tuple_fraction, sub_limit_tuples,
1153 &cheapest_path, &sorted_path, &dNumGroups);
1156 * Extract rowcount and width estimates for possible use in grouping
1157 * decisions. Beware here of the possibility that
1158 * cheapest_path->parent is NULL (ie, there is no FROM clause).
1160 if (cheapest_path->parent)
1162 path_rows = cheapest_path->parent->rows;
1163 path_width = cheapest_path->parent->width;
1167 path_rows = 1; /* assume non-set result */
1168 path_width = 100; /* arbitrary */
1171 if (parse->groupClause)
1174 * If grouping, decide whether to use sorted or hashed grouping.
1176 use_hashed_grouping =
1177 choose_hashed_grouping(root,
1178 tuple_fraction, limit_tuples,
1179 path_rows, path_width,
1180 cheapest_path, sorted_path,
1181 dNumGroups, &agg_costs);
1182 /* Also convert # groups to long int --- but 'ware overflow! */
1183 numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
1185 else if (parse->distinctClause && sorted_path &&
1186 !root->hasHavingQual && !parse->hasAggs && !activeWindows)
1189 * We'll reach the DISTINCT stage without any intermediate
1190 * processing, so figure out whether we will want to hash or not
1191 * so we can choose whether to use cheapest or sorted path.
1193 use_hashed_distinct =
1194 choose_hashed_distinct(root,
1195 tuple_fraction, limit_tuples,
1196 path_rows, path_width,
1197 cheapest_path->startup_cost,
1198 cheapest_path->total_cost,
1199 sorted_path->startup_cost,
1200 sorted_path->total_cost,
1201 sorted_path->pathkeys,
1203 tested_hashed_distinct = true;
1207 * Select the best path. If we are doing hashed grouping, we will
1208 * always read all the input tuples, so use the cheapest-total path.
1209 * Otherwise, trust query_planner's decision about which to use.
1211 if (use_hashed_grouping || use_hashed_distinct || !sorted_path)
1212 best_path = cheapest_path;
1214 best_path = sorted_path;
1217 * Check to see if it's possible to optimize MIN/MAX aggregates. If
1218 * so, we will forget all the work we did so far to choose a "regular"
1219 * path ... but we had to do it anyway to be able to tell which way is
1222 result_plan = optimize_minmax_aggregates(root,
1226 if (result_plan != NULL)
1229 * optimize_minmax_aggregates generated the full plan, with the
1230 * right tlist, and it has no sort order.
1232 current_pathkeys = NIL;
1237 * Normal case --- create a plan according to query_planner's
1240 bool need_sort_for_grouping = false;
1242 result_plan = create_plan(root, best_path);
1243 current_pathkeys = best_path->pathkeys;
1245 /* Detect if we'll need an explicit sort for grouping */
1246 if (parse->groupClause && !use_hashed_grouping &&
1247 !pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
1249 need_sort_for_grouping = true;
1252 * Always override create_plan's tlist, so that we don't
1253 * sort useless data from a "physical" tlist.
1255 need_tlist_eval = true;
1259 * create_plan returns a plan with just a "flat" tlist of
1260 * required Vars. Usually we need to insert the sub_tlist as the
1261 * tlist of the top plan node. However, we can skip that if we
1262 * determined that whatever create_plan chose to return will be
1265 if (need_tlist_eval)
1268 * If the top-level plan node is one that cannot do expression
1269 * evaluation, we must insert a Result node to project the
1272 if (!is_projection_capable_plan(result_plan))
1274 result_plan = (Plan *) make_result(root,
1282 * Otherwise, just replace the subplan's flat tlist with
1283 * the desired tlist.
1285 result_plan->targetlist = sub_tlist;
1289 * Also, account for the cost of evaluation of the sub_tlist.
1291 * Up to now, we have only been dealing with "flat" tlists,
1292 * containing just Vars. So their evaluation cost is zero
1293 * according to the model used by cost_qual_eval() (or if you
1294 * prefer, the cost is factored into cpu_tuple_cost). Thus we
1295 * can avoid accounting for tlist cost throughout
1296 * query_planner() and subroutines. But now we've inserted a
1297 * tlist that might contain actual operators, sub-selects, etc
1298 * --- so we'd better account for its cost.
1300 * Below this point, any tlist eval cost for added-on nodes
1301 * should be accounted for as we create those nodes.
1302 * Presently, of the node types we can add on, only Agg,
1303 * WindowAgg, and Group project new tlists (the rest just copy
1304 * their input tuples) --- so make_agg(), make_windowagg() and
1305 * make_group() are responsible for computing the added cost.
1307 cost_qual_eval(&tlist_cost, sub_tlist, root);
1308 result_plan->startup_cost += tlist_cost.startup;
1309 result_plan->total_cost += tlist_cost.startup +
1310 tlist_cost.per_tuple * result_plan->plan_rows;
1315 * Since we're using create_plan's tlist and not the one
1316 * make_subplanTargetList calculated, we have to refigure any
1317 * grouping-column indexes make_subplanTargetList computed.
1319 locate_grouping_columns(root, tlist, result_plan->targetlist,
1324 * Insert AGG or GROUP node if needed, plus an explicit sort step
1327 * HAVING clause, if any, becomes qual of the Agg or Group node.
1329 if (use_hashed_grouping)
1331 /* Hashed aggregate plan --- no sort needed */
1332 result_plan = (Plan *) make_agg(root,
1334 (List *) parse->havingQual,
1339 extract_grouping_ops(parse->groupClause),
1342 /* Hashed aggregation produces randomly-ordered results */
1343 current_pathkeys = NIL;
1345 else if (parse->hasAggs)
1347 /* Plain aggregate plan --- sort if needed */
1348 AggStrategy aggstrategy;
1350 if (parse->groupClause)
1352 if (need_sort_for_grouping)
1354 result_plan = (Plan *)
1355 make_sort_from_groupcols(root,
1359 current_pathkeys = root->group_pathkeys;
1361 aggstrategy = AGG_SORTED;
1364 * The AGG node will not change the sort ordering of its
1365 * groups, so current_pathkeys describes the result too.
1370 aggstrategy = AGG_PLAIN;
1371 /* Result will be only one row anyway; no sort order */
1372 current_pathkeys = NIL;
1375 result_plan = (Plan *) make_agg(root,
1377 (List *) parse->havingQual,
1382 extract_grouping_ops(parse->groupClause),
1386 else if (parse->groupClause)
1389 * GROUP BY without aggregation, so insert a group node (plus
1390 * the appropriate sort node, if necessary).
1392 * Add an explicit sort if we couldn't make the path come out
1393 * the way the GROUP node needs it.
1395 if (need_sort_for_grouping)
1397 result_plan = (Plan *)
1398 make_sort_from_groupcols(root,
1402 current_pathkeys = root->group_pathkeys;
1405 result_plan = (Plan *) make_group(root,
1407 (List *) parse->havingQual,
1410 extract_grouping_ops(parse->groupClause),
1413 /* The Group node won't change sort ordering */
1415 else if (root->hasHavingQual)
1418 * No aggregates, and no GROUP BY, but we have a HAVING qual.
1419 * This is a degenerate case in which we are supposed to emit
1420 * either 0 or 1 row depending on whether HAVING succeeds.
1421 * Furthermore, there cannot be any variables in either HAVING
1422 * or the targetlist, so we actually do not need the FROM
1423 * table at all! We can just throw away the plan-so-far and
1424 * generate a Result node. This is a sufficiently unusual
1425 * corner case that it's not worth contorting the structure of
1426 * this routine to avoid having to generate the plan in the
1429 result_plan = (Plan *) make_result(root,
1434 } /* end of non-minmax-aggregate case */
1437 * Since each window function could require a different sort order, we
1438 * stack up a WindowAgg node for each window, with sort steps between
1447 * If the top-level plan node is one that cannot do expression
1448 * evaluation, we must insert a Result node to project the desired
1449 * tlist. (In some cases this might not really be required, but
1450 * it's not worth trying to avoid it.) Note that on second and
1451 * subsequent passes through the following loop, the top-level
1452 * node will be a WindowAgg which we know can project; so we only
1453 * need to check once.
1455 if (!is_projection_capable_plan(result_plan))
1457 result_plan = (Plan *) make_result(root,
1464 * The "base" targetlist for all steps of the windowing process is
1465 * a flat tlist of all Vars and Aggs needed in the result. (In
1466 * some cases we wouldn't need to propagate all of these all the
1467 * way to the top, since they might only be needed as inputs to
1468 * WindowFuncs. It's probably not worth trying to optimize that
1469 * though.) We also need any volatile sort expressions, because
1470 * make_sort_from_pathkeys won't add those on its own, and anyway
1471 * we want them evaluated only once at the bottom of the stack. As
1472 * we climb up the stack, we add outputs for the WindowFuncs
1473 * computed at each level. Also, each input tlist has to present
1474 * all the columns needed to sort the data for the next WindowAgg
1475 * step. That's handled internally by make_sort_from_pathkeys,
1476 * but we need the copyObject steps here to ensure that each plan
1477 * node has a separately modifiable tlist.
1479 * Note: it's essential here to use PVC_INCLUDE_AGGREGATES so that
1480 * Vars mentioned only in aggregate expressions aren't pulled out
1481 * as separate targetlist entries. Otherwise we could be putting
1482 * ungrouped Vars directly into an Agg node's tlist, resulting in
1483 * undefined behavior.
1485 window_tlist = flatten_tlist(tlist,
1486 PVC_INCLUDE_AGGREGATES,
1487 PVC_INCLUDE_PLACEHOLDERS);
1488 window_tlist = add_volatile_sort_exprs(window_tlist, tlist,
1490 result_plan->targetlist = (List *) copyObject(window_tlist);
1492 foreach(l, activeWindows)
1494 WindowClause *wc = (WindowClause *) lfirst(l);
1495 List *window_pathkeys;
1497 AttrNumber *partColIdx;
1500 AttrNumber *ordColIdx;
1503 window_pathkeys = make_pathkeys_for_window(root,
1509 * This is a bit tricky: we build a sort node even if we don't
1510 * really have to sort. Even when no explicit sort is needed,
1511 * we need to have suitable resjunk items added to the input
1512 * plan's tlist for any partitioning or ordering columns that
1513 * aren't plain Vars. Furthermore, this way we can use
1514 * existing infrastructure to identify which input columns are
1515 * the interesting ones.
1517 if (window_pathkeys)
1521 sort_plan = make_sort_from_pathkeys(root,
1525 if (!pathkeys_contained_in(window_pathkeys,
1528 /* we do indeed need to sort */
1529 result_plan = (Plan *) sort_plan;
1530 current_pathkeys = window_pathkeys;
1532 /* In either case, extract the per-column information */
1533 get_column_info_for_window(root, wc, tlist,
1535 sort_plan->sortColIdx,
1545 /* empty window specification, nothing to sort */
1548 partOperators = NULL;
1551 ordOperators = NULL;
1556 /* Add the current WindowFuncs to the running tlist */
1557 window_tlist = add_to_flat_tlist(window_tlist,
1558 wflists->windowFuncs[wc->winref]);
1562 /* Install the original tlist in the topmost WindowAgg */
1563 window_tlist = tlist;
1566 /* ... and make the WindowAgg plan node */
1567 result_plan = (Plan *)
1568 make_windowagg(root,
1569 (List *) copyObject(window_tlist),
1570 wflists->windowFuncs[wc->winref],
1584 } /* end of if (setOperations) */
1587 * If there is a DISTINCT clause, add the necessary node(s).
1589 if (parse->distinctClause)
1591 double dNumDistinctRows;
1592 long numDistinctRows;
1595 * If there was grouping or aggregation, use the current number of
1596 * rows as the estimated number of DISTINCT rows (ie, assume the
1597 * result was already mostly unique). If not, use the number of
1598 * distinct-groups calculated by query_planner.
1600 if (parse->groupClause || root->hasHavingQual || parse->hasAggs)
1601 dNumDistinctRows = result_plan->plan_rows;
1603 dNumDistinctRows = dNumGroups;
1605 /* Also convert to long int --- but 'ware overflow! */
1606 numDistinctRows = (long) Min(dNumDistinctRows, (double) LONG_MAX);
1608 /* Choose implementation method if we didn't already */
1609 if (!tested_hashed_distinct)
1612 * At this point, either hashed or sorted grouping will have to
1613 * work from result_plan, so we pass that as both "cheapest" and
1616 use_hashed_distinct =
1617 choose_hashed_distinct(root,
1618 tuple_fraction, limit_tuples,
1619 result_plan->plan_rows,
1620 result_plan->plan_width,
1621 result_plan->startup_cost,
1622 result_plan->total_cost,
1623 result_plan->startup_cost,
1624 result_plan->total_cost,
1629 if (use_hashed_distinct)
1631 /* Hashed aggregate plan --- no sort needed */
1632 result_plan = (Plan *) make_agg(root,
1633 result_plan->targetlist,
1637 list_length(parse->distinctClause),
1638 extract_grouping_cols(parse->distinctClause,
1639 result_plan->targetlist),
1640 extract_grouping_ops(parse->distinctClause),
1643 /* Hashed aggregation produces randomly-ordered results */
1644 current_pathkeys = NIL;
1649 * Use a Unique node to implement DISTINCT. Add an explicit sort
1650 * if we couldn't make the path come out the way the Unique node
1651 * needs it. If we do have to sort, always sort by the more
1652 * rigorous of DISTINCT and ORDER BY, to avoid a second sort
1653 * below. However, for regular DISTINCT, don't sort now if we
1654 * don't have to --- sorting afterwards will likely be cheaper,
1655 * and also has the possibility of optimizing via LIMIT. But for
1656 * DISTINCT ON, we *must* force the final sort now, else it won't
1657 * have the desired behavior.
1659 List *needed_pathkeys;
1661 if (parse->hasDistinctOn &&
1662 list_length(root->distinct_pathkeys) <
1663 list_length(root->sort_pathkeys))
1664 needed_pathkeys = root->sort_pathkeys;
1666 needed_pathkeys = root->distinct_pathkeys;
1668 if (!pathkeys_contained_in(needed_pathkeys, current_pathkeys))
1670 if (list_length(root->distinct_pathkeys) >=
1671 list_length(root->sort_pathkeys))
1672 current_pathkeys = root->distinct_pathkeys;
1675 current_pathkeys = root->sort_pathkeys;
1676 /* Assert checks that parser didn't mess up... */
1677 Assert(pathkeys_contained_in(root->distinct_pathkeys,
1681 result_plan = (Plan *) make_sort_from_pathkeys(root,
1687 result_plan = (Plan *) make_unique(result_plan,
1688 parse->distinctClause);
1689 result_plan->plan_rows = dNumDistinctRows;
1690 /* The Unique node won't change sort ordering */
1695 * If ORDER BY was given and we were not able to make the plan come out in
1696 * the right order, add an explicit sort step.
1698 if (parse->sortClause)
1700 if (!pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
1702 result_plan = (Plan *) make_sort_from_pathkeys(root,
1704 root->sort_pathkeys,
1706 current_pathkeys = root->sort_pathkeys;
1711 * If there is a FOR UPDATE/SHARE clause, add the LockRows node. (Note: we
1712 * intentionally test parse->rowMarks not root->rowMarks here. If there
1713 * are only non-locking rowmarks, they should be handled by the
1714 * ModifyTable node instead.)
1716 if (parse->rowMarks)
1718 result_plan = (Plan *) make_lockrows(result_plan,
1720 SS_assign_special_param(root));
1723 * The result can no longer be assumed sorted, since locking might
1724 * cause the sort key columns to be replaced with new values.
1726 current_pathkeys = NIL;
1730 * Finally, if there is a LIMIT/OFFSET clause, add the LIMIT node.
1732 if (parse->limitCount || parse->limitOffset)
1734 result_plan = (Plan *) make_limit(result_plan,
1742 * Return the actual output ordering in query_pathkeys for possible use by
1743 * an outer query level.
1745 root->query_pathkeys = current_pathkeys;
1751 * Detect whether a plan node is a "dummy" plan created when a relation
1752 * is deemed not to need scanning due to constraint exclusion.
1754 * Currently, such dummy plans are Result nodes with constant FALSE
1758 is_dummy_plan(Plan *plan)
1760 if (IsA(plan, Result))
1762 List *rcqual = (List *) ((Result *) plan)->resconstantqual;
1764 if (list_length(rcqual) == 1)
1766 Const *constqual = (Const *) linitial(rcqual);
1768 if (constqual && IsA(constqual, Const))
1770 if (!constqual->constisnull &&
1771 !DatumGetBool(constqual->constvalue))
1780 * Create a bitmapset of the RT indexes of live base relations
1782 * Helper for preprocess_rowmarks ... at this point in the proceedings,
1783 * the only good way to distinguish baserels from appendrel children
1784 * is to see what is in the join tree.
1787 get_base_rel_indexes(Node *jtnode)
1793 if (IsA(jtnode, RangeTblRef))
1795 int varno = ((RangeTblRef *) jtnode)->rtindex;
1797 result = bms_make_singleton(varno);
1799 else if (IsA(jtnode, FromExpr))
1801 FromExpr *f = (FromExpr *) jtnode;
1805 foreach(l, f->fromlist)
1806 result = bms_join(result,
1807 get_base_rel_indexes(lfirst(l)));
1809 else if (IsA(jtnode, JoinExpr))
1811 JoinExpr *j = (JoinExpr *) jtnode;
1813 result = bms_join(get_base_rel_indexes(j->larg),
1814 get_base_rel_indexes(j->rarg));
1818 elog(ERROR, "unrecognized node type: %d",
1819 (int) nodeTag(jtnode));
1820 result = NULL; /* keep compiler quiet */
1826 * preprocess_rowmarks - set up PlanRowMarks if needed
1829 preprocess_rowmarks(PlannerInfo *root)
1831 Query *parse = root->parse;
1837 if (parse->rowMarks)
1840 * We've got trouble if FOR UPDATE/SHARE appears inside grouping,
1841 * since grouping renders a reference to individual tuple CTIDs
1842 * invalid. This is also checked at parse time, but that's
1843 * insufficient because of rule substitution, query pullup, etc.
1845 CheckSelectLocking(parse);
1850 * We only need rowmarks for UPDATE, DELETE, or FOR UPDATE/SHARE.
1852 if (parse->commandType != CMD_UPDATE &&
1853 parse->commandType != CMD_DELETE)
1858 * We need to have rowmarks for all base relations except the target. We
1859 * make a bitmapset of all base rels and then remove the items we don't
1860 * need or have FOR UPDATE/SHARE marks for.
1862 rels = get_base_rel_indexes((Node *) parse->jointree);
1863 if (parse->resultRelation)
1864 rels = bms_del_member(rels, parse->resultRelation);
1867 * Convert RowMarkClauses to PlanRowMark representation.
1870 foreach(l, parse->rowMarks)
1872 RowMarkClause *rc = (RowMarkClause *) lfirst(l);
1873 RangeTblEntry *rte = rt_fetch(rc->rti, parse->rtable);
1877 * Currently, it is syntactically impossible to have FOR UPDATE
1878 * applied to an update/delete target rel. If that ever becomes
1879 * possible, we should drop the target from the PlanRowMark list.
1881 Assert(rc->rti != parse->resultRelation);
1884 * Ignore RowMarkClauses for subqueries; they aren't real tables and
1885 * can't support true locking. Subqueries that got flattened into the
1886 * main query should be ignored completely. Any that didn't will get
1887 * ROW_MARK_COPY items in the next loop.
1889 if (rte->rtekind != RTE_RELATION)
1892 rels = bms_del_member(rels, rc->rti);
1894 newrc = makeNode(PlanRowMark);
1895 newrc->rti = newrc->prti = rc->rti;
1896 newrc->rowmarkId = ++(root->glob->lastRowMarkId);
1898 newrc->markType = ROW_MARK_EXCLUSIVE;
1900 newrc->markType = ROW_MARK_SHARE;
1901 newrc->noWait = rc->noWait;
1902 newrc->isParent = false;
1904 prowmarks = lappend(prowmarks, newrc);
1908 * Now, add rowmarks for any non-target, non-locked base relations.
1911 foreach(l, parse->rtable)
1913 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
1917 if (!bms_is_member(i, rels))
1920 newrc = makeNode(PlanRowMark);
1921 newrc->rti = newrc->prti = i;
1922 newrc->rowmarkId = ++(root->glob->lastRowMarkId);
1923 /* real tables support REFERENCE, anything else needs COPY */
1924 if (rte->rtekind == RTE_RELATION &&
1925 rte->relkind != RELKIND_FOREIGN_TABLE)
1926 newrc->markType = ROW_MARK_REFERENCE;
1928 newrc->markType = ROW_MARK_COPY;
1929 newrc->noWait = false; /* doesn't matter */
1930 newrc->isParent = false;
1932 prowmarks = lappend(prowmarks, newrc);
1935 root->rowMarks = prowmarks;
1939 * preprocess_limit - do pre-estimation for LIMIT and/or OFFSET clauses
1941 * We try to estimate the values of the LIMIT/OFFSET clauses, and pass the
1942 * results back in *count_est and *offset_est. These variables are set to
1943 * 0 if the corresponding clause is not present, and -1 if it's present
1944 * but we couldn't estimate the value for it. (The "0" convention is OK
1945 * for OFFSET but a little bit bogus for LIMIT: effectively we estimate
1946 * LIMIT 0 as though it were LIMIT 1. But this is in line with the planner's
1947 * usual practice of never estimating less than one row.) These values will
1948 * be passed to make_limit, which see if you change this code.
1950 * The return value is the suitably adjusted tuple_fraction to use for
1951 * planning the query. This adjustment is not overridable, since it reflects
1952 * plan actions that grouping_planner() will certainly take, not assumptions
1956 preprocess_limit(PlannerInfo *root, double tuple_fraction,
1957 int64 *offset_est, int64 *count_est)
1959 Query *parse = root->parse;
1961 double limit_fraction;
1963 /* Should not be called unless LIMIT or OFFSET */
1964 Assert(parse->limitCount || parse->limitOffset);
1967 * Try to obtain the clause values. We use estimate_expression_value
1968 * primarily because it can sometimes do something useful with Params.
1970 if (parse->limitCount)
1972 est = estimate_expression_value(root, parse->limitCount);
1973 if (est && IsA(est, Const))
1975 if (((Const *) est)->constisnull)
1977 /* NULL indicates LIMIT ALL, ie, no limit */
1978 *count_est = 0; /* treat as not present */
1982 *count_est = DatumGetInt64(((Const *) est)->constvalue);
1983 if (*count_est <= 0)
1984 *count_est = 1; /* force to at least 1 */
1988 *count_est = -1; /* can't estimate */
1991 *count_est = 0; /* not present */
1993 if (parse->limitOffset)
1995 est = estimate_expression_value(root, parse->limitOffset);
1996 if (est && IsA(est, Const))
1998 if (((Const *) est)->constisnull)
2000 /* Treat NULL as no offset; the executor will too */
2001 *offset_est = 0; /* treat as not present */
2005 *offset_est = DatumGetInt64(((Const *) est)->constvalue);
2006 if (*offset_est < 0)
2007 *offset_est = 0; /* less than 0 is same as 0 */
2011 *offset_est = -1; /* can't estimate */
2014 *offset_est = 0; /* not present */
2016 if (*count_est != 0)
2019 * A LIMIT clause limits the absolute number of tuples returned.
2020 * However, if it's not a constant LIMIT then we have to guess; for
2021 * lack of a better idea, assume 10% of the plan's result is wanted.
2023 if (*count_est < 0 || *offset_est < 0)
2025 /* LIMIT or OFFSET is an expression ... punt ... */
2026 limit_fraction = 0.10;
2030 /* LIMIT (plus OFFSET, if any) is max number of tuples needed */
2031 limit_fraction = (double) *count_est + (double) *offset_est;
2035 * If we have absolute limits from both caller and LIMIT, use the
2036 * smaller value; likewise if they are both fractional. If one is
2037 * fractional and the other absolute, we can't easily determine which
2038 * is smaller, but we use the heuristic that the absolute will usually
2041 if (tuple_fraction >= 1.0)
2043 if (limit_fraction >= 1.0)
2046 tuple_fraction = Min(tuple_fraction, limit_fraction);
2050 /* caller absolute, limit fractional; use caller's value */
2053 else if (tuple_fraction > 0.0)
2055 if (limit_fraction >= 1.0)
2057 /* caller fractional, limit absolute; use limit */
2058 tuple_fraction = limit_fraction;
2062 /* both fractional */
2063 tuple_fraction = Min(tuple_fraction, limit_fraction);
2068 /* no info from caller, just use limit */
2069 tuple_fraction = limit_fraction;
2072 else if (*offset_est != 0 && tuple_fraction > 0.0)
2075 * We have an OFFSET but no LIMIT. This acts entirely differently
2076 * from the LIMIT case: here, we need to increase rather than decrease
2077 * the caller's tuple_fraction, because the OFFSET acts to cause more
2078 * tuples to be fetched instead of fewer. This only matters if we got
2079 * a tuple_fraction > 0, however.
2081 * As above, use 10% if OFFSET is present but unestimatable.
2083 if (*offset_est < 0)
2084 limit_fraction = 0.10;
2086 limit_fraction = (double) *offset_est;
2089 * If we have absolute counts from both caller and OFFSET, add them
2090 * together; likewise if they are both fractional. If one is
2091 * fractional and the other absolute, we want to take the larger, and
2092 * we heuristically assume that's the fractional one.
2094 if (tuple_fraction >= 1.0)
2096 if (limit_fraction >= 1.0)
2098 /* both absolute, so add them together */
2099 tuple_fraction += limit_fraction;
2103 /* caller absolute, limit fractional; use limit */
2104 tuple_fraction = limit_fraction;
2109 if (limit_fraction >= 1.0)
2111 /* caller fractional, limit absolute; use caller's value */
2115 /* both fractional, so add them together */
2116 tuple_fraction += limit_fraction;
2117 if (tuple_fraction >= 1.0)
2118 tuple_fraction = 0.0; /* assume fetch all */
2123 return tuple_fraction;
2128 * preprocess_groupclause - do preparatory work on GROUP BY clause
2130 * The idea here is to adjust the ordering of the GROUP BY elements
2131 * (which in itself is semantically insignificant) to match ORDER BY,
2132 * thereby allowing a single sort operation to both implement the ORDER BY
2133 * requirement and set up for a Unique step that implements GROUP BY.
2135 * In principle it might be interesting to consider other orderings of the
2136 * GROUP BY elements, which could match the sort ordering of other
2137 * possible plans (eg an indexscan) and thereby reduce cost. We don't
2138 * bother with that, though. Hashed grouping will frequently win anyway.
2140 * Note: we need no comparable processing of the distinctClause because
2141 * the parser already enforced that that matches ORDER BY.
2144 preprocess_groupclause(PlannerInfo *root)
2146 Query *parse = root->parse;
2147 List *new_groupclause;
2152 /* If no ORDER BY, nothing useful to do here */
2153 if (parse->sortClause == NIL)
2157 * Scan the ORDER BY clause and construct a list of matching GROUP BY
2158 * items, but only as far as we can make a matching prefix.
2160 * This code assumes that the sortClause contains no duplicate items.
2162 new_groupclause = NIL;
2163 foreach(sl, parse->sortClause)
2165 SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
2167 foreach(gl, parse->groupClause)
2169 SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
2173 new_groupclause = lappend(new_groupclause, gc);
2178 break; /* no match, so stop scanning */
2181 /* Did we match all of the ORDER BY list, or just some of it? */
2182 partial_match = (sl != NULL);
2184 /* If no match at all, no point in reordering GROUP BY */
2185 if (new_groupclause == NIL)
2189 * Add any remaining GROUP BY items to the new list, but only if we were
2190 * able to make a complete match. In other words, we only rearrange the
2191 * GROUP BY list if the result is that one list is a prefix of the other
2192 * --- otherwise there's no possibility of a common sort. Also, give up
2193 * if there are any non-sortable GROUP BY items, since then there's no
2196 foreach(gl, parse->groupClause)
2198 SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
2200 if (list_member_ptr(new_groupclause, gc))
2201 continue; /* it matched an ORDER BY item */
2203 return; /* give up, no common sort possible */
2204 if (!OidIsValid(gc->sortop))
2205 return; /* give up, GROUP BY can't be sorted */
2206 new_groupclause = lappend(new_groupclause, gc);
2209 /* Success --- install the rearranged GROUP BY list */
2210 Assert(list_length(parse->groupClause) == list_length(new_groupclause));
2211 parse->groupClause = new_groupclause;
2215 * choose_hashed_grouping - should we use hashed grouping?
2217 * Returns TRUE to select hashing, FALSE to select sorting.
2220 choose_hashed_grouping(PlannerInfo *root,
2221 double tuple_fraction, double limit_tuples,
2222 double path_rows, int path_width,
2223 Path *cheapest_path, Path *sorted_path,
2224 double dNumGroups, AggClauseCosts *agg_costs)
2226 Query *parse = root->parse;
2227 int numGroupCols = list_length(parse->groupClause);
2231 List *target_pathkeys;
2232 List *current_pathkeys;
2237 * Executor doesn't support hashed aggregation with DISTINCT or ORDER BY
2238 * aggregates. (Doing so would imply storing *all* the input values in
2239 * the hash table, and/or running many sorts in parallel, either of which
2240 * seems like a certain loser.)
2242 can_hash = (agg_costs->numOrderedAggs == 0 &&
2243 grouping_is_hashable(parse->groupClause));
2244 can_sort = grouping_is_sortable(parse->groupClause);
2246 /* Quick out if only one choice is workable */
2247 if (!(can_hash && can_sort))
2255 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2256 errmsg("could not implement GROUP BY"),
2257 errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
2260 /* Prefer sorting when enable_hashagg is off */
2261 if (!enable_hashagg)
2265 * Don't do it if it doesn't look like the hashtable will fit into
2269 /* Estimate per-hash-entry space at tuple width... */
2270 hashentrysize = MAXALIGN(path_width) + MAXALIGN(sizeof(MinimalTupleData));
2271 /* plus space for pass-by-ref transition values... */
2272 hashentrysize += agg_costs->transitionSpace;
2273 /* plus the per-hash-entry overhead */
2274 hashentrysize += hash_agg_entry_size(agg_costs->numAggs);
2276 if (hashentrysize * dNumGroups > work_mem * 1024L)
2280 * When we have both GROUP BY and DISTINCT, use the more-rigorous of
2281 * DISTINCT and ORDER BY as the assumed required output sort order. This
2282 * is an oversimplification because the DISTINCT might get implemented via
2283 * hashing, but it's not clear that the case is common enough (or that our
2284 * estimates are good enough) to justify trying to solve it exactly.
2286 if (list_length(root->distinct_pathkeys) >
2287 list_length(root->sort_pathkeys))
2288 target_pathkeys = root->distinct_pathkeys;
2290 target_pathkeys = root->sort_pathkeys;
2293 * See if the estimated cost is no more than doing it the other way. While
2294 * avoiding the need for sorted input is usually a win, the fact that the
2295 * output won't be sorted may be a loss; so we need to do an actual cost
2298 * We need to consider cheapest_path + hashagg [+ final sort] versus
2299 * either cheapest_path [+ sort] + group or agg [+ final sort] or
2300 * presorted_path + group or agg [+ final sort] where brackets indicate a
2301 * step that may not be needed. We assume query_planner() will have
2302 * returned a presorted path only if it's a winner compared to
2303 * cheapest_path for this purpose.
2305 * These path variables are dummies that just hold cost fields; we don't
2306 * make actual Paths for these steps.
2308 cost_agg(&hashed_p, root, AGG_HASHED, agg_costs,
2309 numGroupCols, dNumGroups,
2310 cheapest_path->startup_cost, cheapest_path->total_cost,
2312 /* Result of hashed agg is always unsorted */
2313 if (target_pathkeys)
2314 cost_sort(&hashed_p, root, target_pathkeys, hashed_p.total_cost,
2315 dNumGroups, path_width,
2316 0.0, work_mem, limit_tuples);
2320 sorted_p.startup_cost = sorted_path->startup_cost;
2321 sorted_p.total_cost = sorted_path->total_cost;
2322 current_pathkeys = sorted_path->pathkeys;
2326 sorted_p.startup_cost = cheapest_path->startup_cost;
2327 sorted_p.total_cost = cheapest_path->total_cost;
2328 current_pathkeys = cheapest_path->pathkeys;
2330 if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
2332 cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
2333 path_rows, path_width,
2334 0.0, work_mem, -1.0);
2335 current_pathkeys = root->group_pathkeys;
2339 cost_agg(&sorted_p, root, AGG_SORTED, agg_costs,
2340 numGroupCols, dNumGroups,
2341 sorted_p.startup_cost, sorted_p.total_cost,
2344 cost_group(&sorted_p, root, numGroupCols, dNumGroups,
2345 sorted_p.startup_cost, sorted_p.total_cost,
2347 /* The Agg or Group node will preserve ordering */
2348 if (target_pathkeys &&
2349 !pathkeys_contained_in(target_pathkeys, current_pathkeys))
2350 cost_sort(&sorted_p, root, target_pathkeys, sorted_p.total_cost,
2351 dNumGroups, path_width,
2352 0.0, work_mem, limit_tuples);
2355 * Now make the decision using the top-level tuple fraction. First we
2356 * have to convert an absolute count (LIMIT) into fractional form.
2358 if (tuple_fraction >= 1.0)
2359 tuple_fraction /= dNumGroups;
2361 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
2362 tuple_fraction) < 0)
2364 /* Hashed is cheaper, so use it */
2371 * choose_hashed_distinct - should we use hashing for DISTINCT?
2373 * This is fairly similar to choose_hashed_grouping, but there are enough
2374 * differences that it doesn't seem worth trying to unify the two functions.
2375 * (One difference is that we sometimes apply this after forming a Plan,
2376 * so the input alternatives can't be represented as Paths --- instead we
2377 * pass in the costs as individual variables.)
2379 * But note that making the two choices independently is a bit bogus in
2380 * itself. If the two could be combined into a single choice operation
2381 * it'd probably be better, but that seems far too unwieldy to be practical,
2382 * especially considering that the combination of GROUP BY and DISTINCT
2383 * isn't very common in real queries. By separating them, we are giving
2384 * extra preference to using a sorting implementation when a common sort key
2385 * is available ... and that's not necessarily wrong anyway.
2387 * Returns TRUE to select hashing, FALSE to select sorting.
2390 choose_hashed_distinct(PlannerInfo *root,
2391 double tuple_fraction, double limit_tuples,
2392 double path_rows, int path_width,
2393 Cost cheapest_startup_cost, Cost cheapest_total_cost,
2394 Cost sorted_startup_cost, Cost sorted_total_cost,
2395 List *sorted_pathkeys,
2396 double dNumDistinctRows)
2398 Query *parse = root->parse;
2399 int numDistinctCols = list_length(parse->distinctClause);
2403 List *current_pathkeys;
2404 List *needed_pathkeys;
2409 * If we have a sortable DISTINCT ON clause, we always use sorting. This
2410 * enforces the expected behavior of DISTINCT ON.
2412 can_sort = grouping_is_sortable(parse->distinctClause);
2413 if (can_sort && parse->hasDistinctOn)
2416 can_hash = grouping_is_hashable(parse->distinctClause);
2418 /* Quick out if only one choice is workable */
2419 if (!(can_hash && can_sort))
2427 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2428 errmsg("could not implement DISTINCT"),
2429 errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
2432 /* Prefer sorting when enable_hashagg is off */
2433 if (!enable_hashagg)
2437 * Don't do it if it doesn't look like the hashtable will fit into
2440 hashentrysize = MAXALIGN(path_width) + MAXALIGN(sizeof(MinimalTupleData));
2442 if (hashentrysize * dNumDistinctRows > work_mem * 1024L)
2446 * See if the estimated cost is no more than doing it the other way. While
2447 * avoiding the need for sorted input is usually a win, the fact that the
2448 * output won't be sorted may be a loss; so we need to do an actual cost
2451 * We need to consider cheapest_path + hashagg [+ final sort] versus
2452 * sorted_path [+ sort] + group [+ final sort] where brackets indicate a
2453 * step that may not be needed.
2455 * These path variables are dummies that just hold cost fields; we don't
2456 * make actual Paths for these steps.
2458 cost_agg(&hashed_p, root, AGG_HASHED, NULL,
2459 numDistinctCols, dNumDistinctRows,
2460 cheapest_startup_cost, cheapest_total_cost,
2464 * Result of hashed agg is always unsorted, so if ORDER BY is present we
2465 * need to charge for the final sort.
2467 if (parse->sortClause)
2468 cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
2469 dNumDistinctRows, path_width,
2470 0.0, work_mem, limit_tuples);
2473 * Now for the GROUP case. See comments in grouping_planner about the
2474 * sorting choices here --- this code should match that code.
2476 sorted_p.startup_cost = sorted_startup_cost;
2477 sorted_p.total_cost = sorted_total_cost;
2478 current_pathkeys = sorted_pathkeys;
2479 if (parse->hasDistinctOn &&
2480 list_length(root->distinct_pathkeys) <
2481 list_length(root->sort_pathkeys))
2482 needed_pathkeys = root->sort_pathkeys;
2484 needed_pathkeys = root->distinct_pathkeys;
2485 if (!pathkeys_contained_in(needed_pathkeys, current_pathkeys))
2487 if (list_length(root->distinct_pathkeys) >=
2488 list_length(root->sort_pathkeys))
2489 current_pathkeys = root->distinct_pathkeys;
2491 current_pathkeys = root->sort_pathkeys;
2492 cost_sort(&sorted_p, root, current_pathkeys, sorted_p.total_cost,
2493 path_rows, path_width,
2494 0.0, work_mem, -1.0);
2496 cost_group(&sorted_p, root, numDistinctCols, dNumDistinctRows,
2497 sorted_p.startup_cost, sorted_p.total_cost,
2499 if (parse->sortClause &&
2500 !pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
2501 cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
2502 dNumDistinctRows, path_width,
2503 0.0, work_mem, limit_tuples);
2506 * Now make the decision using the top-level tuple fraction. First we
2507 * have to convert an absolute count (LIMIT) into fractional form.
2509 if (tuple_fraction >= 1.0)
2510 tuple_fraction /= dNumDistinctRows;
2512 if (compare_fractional_path_costs(&hashed_p, &sorted_p,
2513 tuple_fraction) < 0)
2515 /* Hashed is cheaper, so use it */
2522 * make_subplanTargetList
2523 * Generate appropriate target list when grouping is required.
2525 * When grouping_planner inserts grouping or aggregation plan nodes
2526 * above the scan/join plan constructed by query_planner+create_plan,
2527 * we typically want the scan/join plan to emit a different target list
2528 * than the outer plan nodes should have. This routine generates the
2529 * correct target list for the scan/join subplan.
2531 * The initial target list passed from the parser already contains entries
2532 * for all ORDER BY and GROUP BY expressions, but it will not have entries
2533 * for variables used only in HAVING clauses; so we need to add those
2534 * variables to the subplan target list. Also, we flatten all expressions
2535 * except GROUP BY items into their component variables; the other expressions
2536 * will be computed by the inserted nodes rather than by the subplan.
2537 * For example, given a query like
2538 * SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
2539 * we want to pass this targetlist to the subplan:
2541 * where the a+b target will be used by the Sort/Group steps, and the
2542 * other targets will be used for computing the final results.
2544 * If we are grouping or aggregating, *and* there are no non-Var grouping
2545 * expressions, then the returned tlist is effectively dummy; we do not
2546 * need to force it to be evaluated, because all the Vars it contains
2547 * should be present in the "flat" tlist generated by create_plan, though
2548 * possibly in a different order. In that case we'll use create_plan's tlist,
2549 * and the tlist made here is only needed as input to query_planner to tell
2550 * it which Vars are needed in the output of the scan/join plan.
2552 * 'tlist' is the query's target list.
2553 * 'groupColIdx' receives an array of column numbers for the GROUP BY
2554 * expressions (if there are any) in the returned target list.
2555 * 'need_tlist_eval' is set true if we really need to evaluate the
2556 * returned tlist as-is.
2558 * The result is the targetlist to be passed to query_planner.
2561 make_subplanTargetList(PlannerInfo *root,
2563 AttrNumber **groupColIdx,
2564 bool *need_tlist_eval)
2566 Query *parse = root->parse;
2568 List *non_group_cols;
2569 List *non_group_vars;
2572 *groupColIdx = NULL;
2575 * If we're not grouping or aggregating, there's nothing to do here;
2576 * query_planner should receive the unmodified target list.
2578 if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual &&
2579 !parse->hasWindowFuncs)
2581 *need_tlist_eval = true;
2586 * Otherwise, we must build a tlist containing all grouping columns,
2587 * plus any other Vars mentioned in the targetlist and HAVING qual.
2590 non_group_cols = NIL;
2591 *need_tlist_eval = false; /* only eval if not flat tlist */
2593 numCols = list_length(parse->groupClause);
2597 * If grouping, create sub_tlist entries for all GROUP BY columns, and
2598 * make an array showing where the group columns are in the sub_tlist.
2600 * Note: with this implementation, the array entries will always be
2601 * 1..N, but we don't want callers to assume that.
2603 AttrNumber *grpColIdx;
2606 grpColIdx = (AttrNumber *) palloc0(sizeof(AttrNumber) * numCols);
2607 *groupColIdx = grpColIdx;
2611 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2614 colno = get_grouping_column_index(parse, tle);
2618 * It's a grouping column, so add it to the result tlist and
2619 * remember its resno in grpColIdx[].
2621 TargetEntry *newtle;
2623 newtle = makeTargetEntry(tle->expr,
2624 list_length(sub_tlist) + 1,
2627 sub_tlist = lappend(sub_tlist, newtle);
2629 Assert(grpColIdx[colno] == 0); /* no dups expected */
2630 grpColIdx[colno] = newtle->resno;
2632 if (!(newtle->expr && IsA(newtle->expr, Var)))
2633 *need_tlist_eval = true; /* tlist contains non Vars */
2638 * Non-grouping column, so just remember the expression
2639 * for later call to pull_var_clause. There's no need for
2640 * pull_var_clause to examine the TargetEntry node itself.
2642 non_group_cols = lappend(non_group_cols, tle->expr);
2649 * With no grouping columns, just pass whole tlist to pull_var_clause.
2650 * Need (shallow) copy to avoid damaging input tlist below.
2652 non_group_cols = list_copy(tlist);
2656 * If there's a HAVING clause, we'll need the Vars it uses, too.
2658 if (parse->havingQual)
2659 non_group_cols = lappend(non_group_cols, parse->havingQual);
2662 * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
2663 * add them to the result tlist if not already present. (A Var used
2664 * directly as a GROUP BY item will be present already.) Note this
2665 * includes Vars used in resjunk items, so we are covering the needs of
2666 * ORDER BY and window specifications. Vars used within Aggrefs will be
2667 * pulled out here, too.
2669 non_group_vars = pull_var_clause((Node *) non_group_cols,
2670 PVC_RECURSE_AGGREGATES,
2671 PVC_INCLUDE_PLACEHOLDERS);
2672 sub_tlist = add_to_flat_tlist(sub_tlist, non_group_vars);
2674 /* clean up cruft */
2675 list_free(non_group_vars);
2676 list_free(non_group_cols);
2682 * get_grouping_column_index
2683 * Get the GROUP BY column position, if any, of a targetlist entry.
2685 * Returns the index (counting from 0) of the TLE in the GROUP BY list, or -1
2686 * if it's not a grouping column. Note: the result is unique because the
2687 * parser won't make multiple groupClause entries for the same TLE.
2690 get_grouping_column_index(Query *parse, TargetEntry *tle)
2693 Index ressortgroupref = tle->ressortgroupref;
2696 /* No need to search groupClause if TLE hasn't got a sortgroupref */
2697 if (ressortgroupref == 0)
2700 foreach(gl, parse->groupClause)
2702 SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
2704 if (grpcl->tleSortGroupRef == ressortgroupref)
2713 * locate_grouping_columns
2714 * Locate grouping columns in the tlist chosen by create_plan.
2716 * This is only needed if we don't use the sub_tlist chosen by
2717 * make_subplanTargetList. We have to forget the column indexes found
2718 * by that routine and re-locate the grouping exprs in the real sub_tlist.
2721 locate_grouping_columns(PlannerInfo *root,
2724 AttrNumber *groupColIdx)
2730 * No work unless grouping.
2732 if (!root->parse->groupClause)
2734 Assert(groupColIdx == NULL);
2737 Assert(groupColIdx != NULL);
2739 foreach(gl, root->parse->groupClause)
2741 SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
2742 Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
2743 TargetEntry *te = tlist_member(groupexpr, sub_tlist);
2746 elog(ERROR, "failed to locate grouping columns");
2747 groupColIdx[keyno++] = te->resno;
2752 * postprocess_setop_tlist
2753 * Fix up targetlist returned by plan_set_operations().
2755 * We need to transpose sort key info from the orig_tlist into new_tlist.
2756 * NOTE: this would not be good enough if we supported resjunk sort keys
2757 * for results of set operations --- then, we'd need to project a whole
2758 * new tlist to evaluate the resjunk columns. For now, just ereport if we
2759 * find any resjunk columns in orig_tlist.
2762 postprocess_setop_tlist(List *new_tlist, List *orig_tlist)
2765 ListCell *orig_tlist_item = list_head(orig_tlist);
2767 foreach(l, new_tlist)
2769 TargetEntry *new_tle = (TargetEntry *) lfirst(l);
2770 TargetEntry *orig_tle;
2772 /* ignore resjunk columns in setop result */
2773 if (new_tle->resjunk)
2776 Assert(orig_tlist_item != NULL);
2777 orig_tle = (TargetEntry *) lfirst(orig_tlist_item);
2778 orig_tlist_item = lnext(orig_tlist_item);
2779 if (orig_tle->resjunk) /* should not happen */
2780 elog(ERROR, "resjunk output columns are not implemented");
2781 Assert(new_tle->resno == orig_tle->resno);
2782 new_tle->ressortgroupref = orig_tle->ressortgroupref;
2784 if (orig_tlist_item != NULL)
2785 elog(ERROR, "resjunk output columns are not implemented");
2790 * select_active_windows
2791 * Create a list of the "active" window clauses (ie, those referenced
2792 * by non-deleted WindowFuncs) in the order they are to be executed.
2795 select_active_windows(PlannerInfo *root, WindowFuncLists *wflists)
2801 /* First, make a list of the active windows */
2803 foreach(lc, root->parse->windowClause)
2805 WindowClause *wc = (WindowClause *) lfirst(lc);
2807 /* It's only active if wflists shows some related WindowFuncs */
2808 Assert(wc->winref <= wflists->maxWinRef);
2809 if (wflists->windowFuncs[wc->winref] != NIL)
2810 actives = lappend(actives, wc);
2814 * Now, ensure that windows with identical partitioning/ordering clauses
2815 * are adjacent in the list. This is required by the SQL standard, which
2816 * says that only one sort is to be used for such windows, even if they
2817 * are otherwise distinct (eg, different names or framing clauses).
2819 * There is room to be much smarter here, for example detecting whether
2820 * one window's sort keys are a prefix of another's (so that sorting for
2821 * the latter would do for the former), or putting windows first that
2822 * match a sort order available for the underlying query. For the moment
2823 * we are content with meeting the spec.
2826 while (actives != NIL)
2828 WindowClause *wc = (WindowClause *) linitial(actives);
2832 /* Move wc from actives to result */
2833 actives = list_delete_first(actives);
2834 result = lappend(result, wc);
2836 /* Now move any matching windows from actives to result */
2838 for (lc = list_head(actives); lc; lc = next)
2840 WindowClause *wc2 = (WindowClause *) lfirst(lc);
2843 /* framing options are NOT to be compared here! */
2844 if (equal(wc->partitionClause, wc2->partitionClause) &&
2845 equal(wc->orderClause, wc2->orderClause))
2847 actives = list_delete_cell(actives, lc, prev);
2848 result = lappend(result, wc2);
2859 * add_volatile_sort_exprs
2860 * Identify any volatile sort/group expressions used by the active
2861 * windows, and add them to window_tlist if not already present.
2862 * Return the modified window_tlist.
2865 add_volatile_sort_exprs(List *window_tlist, List *tlist, List *activeWindows)
2867 Bitmapset *sgrefs = NULL;
2870 /* First, collect the sortgrouprefs of the windows into a bitmapset */
2871 foreach(lc, activeWindows)
2873 WindowClause *wc = (WindowClause *) lfirst(lc);
2876 foreach(lc2, wc->partitionClause)
2878 SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc2);
2880 sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
2882 foreach(lc2, wc->orderClause)
2884 SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc2);
2886 sgrefs = bms_add_member(sgrefs, sortcl->tleSortGroupRef);
2891 * Now scan the original tlist to find the referenced expressions. Any
2892 * that are volatile must be added to window_tlist.
2894 * Note: we know that the input window_tlist contains no items marked with
2895 * ressortgrouprefs, so we don't have to worry about collisions of the
2896 * reference numbers.
2900 TargetEntry *tle = (TargetEntry *) lfirst(lc);
2902 if (tle->ressortgroupref != 0 &&
2903 bms_is_member(tle->ressortgroupref, sgrefs) &&
2904 contain_volatile_functions((Node *) tle->expr))
2906 TargetEntry *newtle;
2908 newtle = makeTargetEntry(tle->expr,
2909 list_length(window_tlist) + 1,
2912 newtle->ressortgroupref = tle->ressortgroupref;
2913 window_tlist = lappend(window_tlist, newtle);
2917 return window_tlist;
2921 * make_pathkeys_for_window
2922 * Create a pathkeys list describing the required input ordering
2923 * for the given WindowClause.
2925 * The required ordering is first the PARTITION keys, then the ORDER keys.
2926 * In the future we might try to implement windowing using hashing, in which
2927 * case the ordering could be relaxed, but for now we always sort.
2930 make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc,
2931 List *tlist, bool canonicalize)
2933 List *window_pathkeys;
2934 List *window_sortclauses;
2936 /* Throw error if can't sort */
2937 if (!grouping_is_sortable(wc->partitionClause))
2939 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2940 errmsg("could not implement window PARTITION BY"),
2941 errdetail("Window partitioning columns must be of sortable datatypes.")));
2942 if (!grouping_is_sortable(wc->orderClause))
2944 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2945 errmsg("could not implement window ORDER BY"),
2946 errdetail("Window ordering columns must be of sortable datatypes.")));
2948 /* Okay, make the combined pathkeys */
2949 window_sortclauses = list_concat(list_copy(wc->partitionClause),
2950 list_copy(wc->orderClause));
2951 window_pathkeys = make_pathkeys_for_sortclauses(root,
2955 list_free(window_sortclauses);
2956 return window_pathkeys;
2960 * get_column_info_for_window
2961 * Get the partitioning/ordering column numbers and equality operators
2962 * for a WindowAgg node.
2964 * This depends on the behavior of make_pathkeys_for_window()!
2966 * We are given the target WindowClause and an array of the input column
2967 * numbers associated with the resulting pathkeys. In the easy case, there
2968 * are the same number of pathkey columns as partitioning + ordering columns
2969 * and we just have to copy some data around. However, it's possible that
2970 * some of the original partitioning + ordering columns were eliminated as
2971 * redundant during the transformation to pathkeys. (This can happen even
2972 * though the parser gets rid of obvious duplicates. A typical scenario is a
2973 * window specification "PARTITION BY x ORDER BY y" coupled with a clause
2974 * "WHERE x = y" that causes the two sort columns to be recognized as
2975 * redundant.) In that unusual case, we have to work a lot harder to
2976 * determine which keys are significant.
2978 * The method used here is a bit brute-force: add the sort columns to a list
2979 * one at a time and note when the resulting pathkey list gets longer. But
2980 * it's a sufficiently uncommon case that a faster way doesn't seem worth
2981 * the amount of code refactoring that'd be needed.
2985 get_column_info_for_window(PlannerInfo *root, WindowClause *wc, List *tlist,
2986 int numSortCols, AttrNumber *sortColIdx,
2988 AttrNumber **partColIdx,
2989 Oid **partOperators,
2991 AttrNumber **ordColIdx,
2994 int numPart = list_length(wc->partitionClause);
2995 int numOrder = list_length(wc->orderClause);
2997 if (numSortCols == numPart + numOrder)
3000 *partNumCols = numPart;
3001 *partColIdx = sortColIdx;
3002 *partOperators = extract_grouping_ops(wc->partitionClause);
3003 *ordNumCols = numOrder;
3004 *ordColIdx = sortColIdx + numPart;
3005 *ordOperators = extract_grouping_ops(wc->orderClause);
3014 /* first, allocate what's certainly enough space for the arrays */
3016 *partColIdx = (AttrNumber *) palloc(numPart * sizeof(AttrNumber));
3017 *partOperators = (Oid *) palloc(numPart * sizeof(Oid));
3019 *ordColIdx = (AttrNumber *) palloc(numOrder * sizeof(AttrNumber));
3020 *ordOperators = (Oid *) palloc(numOrder * sizeof(Oid));
3024 foreach(lc, wc->partitionClause)
3026 SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
3029 sortclauses = lappend(sortclauses, sgc);
3030 new_pathkeys = make_pathkeys_for_sortclauses(root,
3034 if (list_length(new_pathkeys) > list_length(pathkeys))
3036 /* this sort clause is actually significant */
3037 (*partColIdx)[*partNumCols] = sortColIdx[scidx++];
3038 (*partOperators)[*partNumCols] = sgc->eqop;
3040 pathkeys = new_pathkeys;
3043 foreach(lc, wc->orderClause)
3045 SortGroupClause *sgc = (SortGroupClause *) lfirst(lc);
3048 sortclauses = lappend(sortclauses, sgc);
3049 new_pathkeys = make_pathkeys_for_sortclauses(root,
3053 if (list_length(new_pathkeys) > list_length(pathkeys))
3055 /* this sort clause is actually significant */
3056 (*ordColIdx)[*ordNumCols] = sortColIdx[scidx++];
3057 (*ordOperators)[*ordNumCols] = sgc->eqop;
3059 pathkeys = new_pathkeys;
3062 /* complain if we didn't eat exactly the right number of sort cols */
3063 if (scidx != numSortCols)
3064 elog(ERROR, "failed to deconstruct sort operators into partitioning/ordering operators");
3070 * expression_planner
3071 * Perform planner's transformations on a standalone expression.
3073 * Various utility commands need to evaluate expressions that are not part
3074 * of a plannable query. They can do so using the executor's regular
3075 * expression-execution machinery, but first the expression has to be fed
3076 * through here to transform it from parser output to something executable.
3078 * Currently, we disallow sublinks in standalone expressions, so there's no
3079 * real "planning" involved here. (That might not always be true though.)
3080 * What we must do is run eval_const_expressions to ensure that any function
3081 * calls are converted to positional notation and function default arguments
3082 * get inserted. The fact that constant subexpressions get simplified is a
3083 * side-effect that is useful when the expression will get evaluated more than
3084 * once. Also, we must fix operator function IDs.
3086 * Note: this must not make any damaging changes to the passed-in expression
3087 * tree. (It would actually be okay to apply fix_opfuncids to it, but since
3088 * we first do an expression_tree_mutator-based walk, what is returned will
3089 * be a new node tree.)
3092 expression_planner(Expr *expr)
3097 * Convert named-argument function calls, insert default arguments and
3098 * simplify constant subexprs
3100 result = eval_const_expressions(NULL, (Node *) expr);
3102 /* Fill in opfuncid values if missing */
3103 fix_opfuncids(result);
3105 return (Expr *) result;
3110 * plan_cluster_use_sort
3111 * Use the planner to decide how CLUSTER should implement sorting
3113 * tableOid is the OID of a table to be clustered on its index indexOid
3114 * (which is already known to be a btree index). Decide whether it's
3115 * cheaper to do an indexscan or a seqscan-plus-sort to execute the CLUSTER.
3116 * Return TRUE to use sorting, FALSE to use an indexscan.
3118 * Note: caller had better already hold some type of lock on the table.
3121 plan_cluster_use_sort(Oid tableOid, Oid indexOid)
3125 PlannerGlobal *glob;
3128 IndexOptInfo *indexInfo;
3129 QualCost indexExprCost;
3130 Cost comparisonCost;
3132 Path seqScanAndSortPath;
3133 IndexPath *indexScanPath;
3136 /* Set up mostly-dummy planner state */
3137 query = makeNode(Query);
3138 query->commandType = CMD_SELECT;
3140 glob = makeNode(PlannerGlobal);
3142 root = makeNode(PlannerInfo);
3143 root->parse = query;
3145 root->query_level = 1;
3146 root->planner_cxt = CurrentMemoryContext;
3147 root->wt_param_id = -1;
3149 /* Build a minimal RTE for the rel */
3150 rte = makeNode(RangeTblEntry);
3151 rte->rtekind = RTE_RELATION;
3152 rte->relid = tableOid;
3153 rte->relkind = RELKIND_RELATION;
3155 rte->inFromCl = true;
3156 query->rtable = list_make1(rte);
3158 /* ... and insert it into PlannerInfo */
3159 root->simple_rel_array_size = 2;
3160 root->simple_rel_array = (RelOptInfo **)
3161 palloc0(root->simple_rel_array_size * sizeof(RelOptInfo *));
3162 root->simple_rte_array = (RangeTblEntry **)
3163 palloc0(root->simple_rel_array_size * sizeof(RangeTblEntry *));
3164 root->simple_rte_array[1] = rte;
3166 /* Build RelOptInfo */
3167 rel = build_simple_rel(root, 1, RELOPT_BASEREL);
3169 /* Locate IndexOptInfo for the target index */
3171 foreach(lc, rel->indexlist)
3173 indexInfo = (IndexOptInfo *) lfirst(lc);
3174 if (indexInfo->indexoid == indexOid)
3179 * It's possible that get_relation_info did not generate an IndexOptInfo
3180 * for the desired index; this could happen if it's not yet reached its
3181 * indcheckxmin usability horizon, or if it's a system index and we're
3182 * ignoring system indexes. In such cases we should tell CLUSTER to not
3183 * trust the index contents but use seqscan-and-sort.
3185 if (lc == NULL) /* not in the list? */
3186 return true; /* use sort */
3189 * Rather than doing all the pushups that would be needed to use
3190 * set_baserel_size_estimates, just do a quick hack for rows and width.
3192 rel->rows = rel->tuples;
3193 rel->width = get_relation_data_width(tableOid, NULL);
3195 root->total_table_pages = rel->pages;
3198 * Determine eval cost of the index expressions, if any. We need to
3199 * charge twice that amount for each tuple comparison that happens during
3200 * the sort, since tuplesort.c will have to re-evaluate the index
3201 * expressions each time. (XXX that's pretty inefficient...)
3203 cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
3204 comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
3206 /* Estimate the cost of seq scan + sort */
3207 seqScanPath = create_seqscan_path(root, rel);
3208 cost_sort(&seqScanAndSortPath, root, NIL,
3209 seqScanPath->total_cost, rel->tuples, rel->width,
3210 comparisonCost, maintenance_work_mem, -1.0);
3212 /* Estimate the cost of index scan */
3213 indexScanPath = create_index_path(root, indexInfo,
3215 ForwardScanDirection, NULL);
3217 return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);