* planner.c
* The query optimizer external interface.
*
- * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
- * $PostgreSQL: pgsql/src/backend/optimizer/plan/planner.c,v 1.262 2009/12/15 17:57:46 tgl Exp $
+ * src/backend/optimizer/plan/planner.c
*
*-------------------------------------------------------------------------
*/
#include <limits.h>
-#include "catalog/pg_operator.h"
#include "executor/executor.h"
#include "executor/nodeAgg.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
+#ifdef OPTIMIZER_DEBUG
+#include "nodes/print.h"
+#endif
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
+#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/planner.h"
#include "optimizer/prep.h"
#include "optimizer/subselect.h"
#include "optimizer/tlist.h"
-#include "optimizer/var.h"
-#ifdef OPTIMIZER_DEBUG
-#include "nodes/print.h"
-#endif
#include "parser/analyze.h"
-#include "parser/parse_expr.h"
-#include "parser/parse_oper.h"
#include "parser/parsetree.h"
-#include "utils/lsyscache.h"
-#include "utils/syscache.h"
+#include "rewrite/rewriteManip.h"
+#include "utils/rel.h"
/* GUC parameter */
static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
static Plan *inheritance_planner(PlannerInfo *root);
static Plan *grouping_planner(PlannerInfo *root, double tuple_fraction);
-static bool is_dummy_plan(Plan *plan);
static void preprocess_rowmarks(PlannerInfo *root);
static double preprocess_limit(PlannerInfo *root,
double tuple_fraction,
static void preprocess_groupclause(PlannerInfo *root);
static bool choose_hashed_grouping(PlannerInfo *root,
double tuple_fraction, double limit_tuples,
+ double path_rows, int path_width,
Path *cheapest_path, Path *sorted_path,
- double dNumGroups, AggClauseCounts *agg_counts);
+ double dNumGroups, AggClauseCosts *agg_costs);
static bool choose_hashed_distinct(PlannerInfo *root,
- Plan *input_plan, List *input_pathkeys,
double tuple_fraction, double limit_tuples,
+ double path_rows, int path_width,
+ Cost cheapest_startup_cost, Cost cheapest_total_cost,
+ Cost sorted_startup_cost, Cost sorted_total_cost,
+ List *sorted_pathkeys,
double dNumDistinctRows);
static List *make_subplanTargetList(PlannerInfo *root, List *tlist,
AttrNumber **groupColIdx, bool *need_tlist_eval);
+static int get_grouping_column_index(Query *parse, TargetEntry *tle);
static void locate_grouping_columns(PlannerInfo *root,
List *tlist,
List *sub_tlist,
PlannerInfo *root;
Plan *top_plan;
ListCell *lp,
- *lrt,
- *lrm;
+ *lr;
/* Cursor options may come from caller or from DECLARE CURSOR stmt */
if (parse->utilityStmt &&
glob->boundParams = boundParams;
glob->paramlist = NIL;
glob->subplans = NIL;
- glob->subrtables = NIL;
- glob->subrowmarks = NIL;
+ glob->subroots = NIL;
glob->rewindPlanIDs = NULL;
glob->finalrtable = NIL;
glob->finalrowmarks = NIL;
+ glob->resultRelations = NIL;
glob->relationOids = NIL;
glob->invalItems = NIL;
glob->lastPHId = 0;
+ glob->lastRowMarkId = 0;
glob->transientPlan = false;
/* Determine what fraction of the plan is likely to be scanned */
/* final cleanup of the plan */
Assert(glob->finalrtable == NIL);
Assert(glob->finalrowmarks == NIL);
- top_plan = set_plan_references(glob, top_plan,
- root->parse->rtable,
- root->rowMarks);
+ Assert(glob->resultRelations == NIL);
+ top_plan = set_plan_references(root, top_plan);
/* ... and the subplans (both regular subplans and initplans) */
- Assert(list_length(glob->subplans) == list_length(glob->subrtables));
- Assert(list_length(glob->subplans) == list_length(glob->subrowmarks));
- lrt = list_head(glob->subrtables);
- lrm = list_head(glob->subrowmarks);
- foreach(lp, glob->subplans)
+ Assert(list_length(glob->subplans) == list_length(glob->subroots));
+ forboth(lp, glob->subplans, lr, glob->subroots)
{
Plan *subplan = (Plan *) lfirst(lp);
- List *subrtable = (List *) lfirst(lrt);
- List *subrowmark = (List *) lfirst(lrm);
+ PlannerInfo *subroot = (PlannerInfo *) lfirst(lr);
- lfirst(lp) = set_plan_references(glob, subplan,
- subrtable, subrowmark);
- lrt = lnext(lrt);
- lrm = lnext(lrm);
+ lfirst(lp) = set_plan_references(subroot, subplan);
}
/* build the PlannedStmt result */
result = makeNode(PlannedStmt);
result->commandType = parse->commandType;
+ result->queryId = parse->queryId;
result->hasReturning = (parse->returningList != NIL);
+ result->hasModifyingCTE = parse->hasModifyingCTE;
result->canSetTag = parse->canSetTag;
result->transientPlan = glob->transientPlan;
result->planTree = top_plan;
result->rtable = glob->finalrtable;
- result->resultRelations = root->resultRelations;
+ result->resultRelations = glob->resultRelations;
result->utilityStmt = parse->utilityStmt;
- result->intoClause = parse->intoClause;
result->subplans = glob->subplans;
result->rewindPlanIDs = glob->rewindPlanIDs;
result->rowMarks = glob->finalrowmarks;
root->eq_classes = NIL;
root->append_rel_list = NIL;
root->rowMarks = NIL;
+ root->hasInheritedTarget = false;
root->hasRecursion = hasRecursion;
if (hasRecursion)
inline_set_returning_functions(root);
/*
- * Check to see if any subqueries in the rangetable can be merged into
- * this query.
+ * Check to see if any subqueries in the jointree can be merged into this
+ * query.
*/
parse->jointree = (FromExpr *)
pull_up_subqueries(root, (Node *) parse->jointree, NULL, NULL);
+ /*
+ * If this is a simple UNION ALL query, flatten it into an appendrel. We
+ * do this now because it requires applying pull_up_subqueries to the leaf
+ * queries of the UNION ALL, which weren't touched above because they
+ * weren't referenced by the jointree (they will be after we do this).
+ */
+ if (parse->setOperations)
+ flatten_simple_union_all(root);
+
/*
* Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
* avoid the expense of doing flatten_join_alias_vars(). Also check for
}
/*
- * Preprocess RowMark information. We need to do this after subquery
+ * Preprocess RowMark information. We need to do this after subquery
* pullup (so that all non-inherited RTEs are present) and before
* inheritance expansion (so that the info is available for
* expand_inherited_tables to examine and modify).
root->hasPseudoConstantQuals = false;
/*
- * Do expression preprocessing on targetlist and quals.
+ * Do expression preprocessing on targetlist and quals, as well as other
+ * random expressions in the querytree. Note that we do not need to
+ * handle sort/group expressions explicitly, because they are actually
+ * part of the targetlist.
*/
parse->targetList = (List *)
preprocess_expression(root, (Node *) parse->targetList,
parse->havingQual = preprocess_expression(root, parse->havingQual,
EXPRKIND_QUAL);
+ foreach(l, parse->windowClause)
+ {
+ WindowClause *wc = (WindowClause *) lfirst(l);
+
+ /* partitionClause/orderClause are sort/group expressions */
+ wc->startOffset = preprocess_expression(root, wc->startOffset,
+ EXPRKIND_LIMIT);
+ wc->endOffset = preprocess_expression(root, wc->endOffset,
+ EXPRKIND_LIMIT);
+ }
+
parse->limitOffset = preprocess_expression(root, parse->limitOffset,
EXPRKIND_LIMIT);
parse->limitCount = preprocess_expression(root, parse->limitCount,
/* If it's not SELECT, we need a ModifyTable node */
if (parse->commandType != CMD_SELECT)
{
- List *returningLists;
- List *rowMarks;
+ List *returningLists;
+ List *rowMarks;
/*
- * Deal with the RETURNING clause if any. It's convenient to pass
- * the returningList through setrefs.c now rather than at top
- * level (if we waited, handling inherited UPDATE/DELETE would be
- * much harder).
+ * Set up the RETURNING list-of-lists, if needed.
*/
if (parse->returningList)
- {
- List *rlist;
-
- Assert(parse->resultRelation);
- rlist = set_returning_clause_references(root->glob,
- parse->returningList,
- plan,
- parse->resultRelation);
- returningLists = list_make1(rlist);
- }
+ returningLists = list_make1(parse->returningList);
else
returningLists = NIL;
rowMarks = root->rowMarks;
plan = (Plan *) make_modifytable(parse->commandType,
- copyObject(root->resultRelations),
+ parse->canSetTag,
+ list_make1_int(parse->resultRelation),
list_make1(plan),
returningLists,
rowMarks,
* Simplify constant expressions.
*
* Note: an essential effect of this is to convert named-argument function
- * calls to positional notation and insert the current actual values
- * of any default arguments for functions. To ensure that happens, we
- * *must* process all expressions here. Previous PG versions sometimes
- * skipped const-simplification if it didn't seem worth the trouble, but
- * we can't do that anymore.
+ * calls to positional notation and insert the current actual values of
+ * any default arguments for functions. To ensure that happens, we *must*
+ * process all expressions here. Previous PG versions sometimes skipped
+ * const-simplification if it didn't seem worth the trouble, but we can't
+ * do that anymore.
*
* Note: this also flattens nested AND and OR expressions into N-argument
* form. All processing of a qual expression after this point must be
{
Query *parse = root->parse;
int parentRTindex = parse->resultRelation;
+ List *final_rtable = NIL;
+ int save_rel_array_size = 0;
+ RelOptInfo **save_rel_array = NULL;
List *subplans = NIL;
List *resultRelations = NIL;
List *returningLists = NIL;
- List *rtable = NIL;
List *rowMarks;
- List *tlist;
- PlannerInfo subroot;
- ListCell *l;
+ ListCell *lc;
- foreach(l, root->append_rel_list)
+ /*
+ * We generate a modified instance of the original Query for each target
+ * relation, plan that, and put all the plans into a list that will be
+ * controlled by a single ModifyTable node. All the instances share the
+ * same rangetable, but each instance must have its own set of subquery
+ * RTEs within the finished rangetable because (1) they are likely to get
+ * scribbled on during planning, and (2) it's not inconceivable that
+ * subqueries could get planned differently in different cases. We need
+ * not create duplicate copies of other RTE kinds, in particular not the
+ * target relations, because they don't have either of those issues. Not
+ * having to duplicate the target relations is important because doing so
+ * (1) would result in a rangetable of length O(N^2) for N targets, with
+ * at least O(N^3) work expended here; and (2) would greatly complicate
+ * management of the rowMarks list.
+ */
+ foreach(lc, root->append_rel_list)
{
- AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
+ AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc);
+ PlannerInfo subroot;
Plan *subplan;
+ Index rti;
/* append_rel_list contains all append rels; ignore others */
if (appinfo->parent_relid != parentRTindex)
continue;
/*
- * Generate modified query with this rel as target.
+ * We need a working copy of the PlannerInfo so that we can control
+ * propagation of information back to the main copy.
*/
memcpy(&subroot, root, sizeof(PlannerInfo));
+
+ /*
+ * Generate modified query with this rel as target. We first apply
+ * adjust_appendrel_attrs, which copies the Query and changes
+ * references to the parent RTE to refer to the current child RTE,
+ * then fool around with subquery RTEs.
+ */
subroot.parse = (Query *)
- adjust_appendrel_attrs((Node *) parse,
+ adjust_appendrel_attrs(root,
+ (Node *) parse,
appinfo);
- subroot.init_plans = NIL;
+
+ /*
+ * The rowMarks list might contain references to subquery RTEs, so
+ * make a copy that we can apply ChangeVarNodes to. (Fortunately, the
+ * executor doesn't need to see the modified copies --- we can just
+ * pass it the original rowMarks list.)
+ */
+ subroot.rowMarks = (List *) copyObject(root->rowMarks);
+
+ /*
+ * Add placeholders to the child Query's rangetable list to fill the
+ * RT indexes already reserved for subqueries in previous children.
+ * These won't be referenced, so there's no need to make them very
+ * valid-looking.
+ */
+ while (list_length(subroot.parse->rtable) < list_length(final_rtable))
+ subroot.parse->rtable = lappend(subroot.parse->rtable,
+ makeNode(RangeTblEntry));
+
+ /*
+ * If this isn't the first child Query, generate duplicates of all
+ * subquery RTEs, and adjust Var numbering to reference the
+ * duplicates. To simplify the loop logic, we scan the original rtable
+ * not the copy just made by adjust_appendrel_attrs; that should be OK
+ * since subquery RTEs couldn't contain any references to the target
+ * rel.
+ */
+ if (final_rtable != NIL)
+ {
+ ListCell *lr;
+
+ rti = 1;
+ foreach(lr, parse->rtable)
+ {
+ RangeTblEntry *rte = (RangeTblEntry *) lfirst(lr);
+
+ if (rte->rtekind == RTE_SUBQUERY)
+ {
+ Index newrti;
+
+ /*
+ * The RTE can't contain any references to its own RT
+ * index, so we can save a few cycles by applying
+ * ChangeVarNodes before we append the RTE to the
+ * rangetable.
+ */
+ newrti = list_length(subroot.parse->rtable) + 1;
+ ChangeVarNodes((Node *) subroot.parse, rti, newrti, 0);
+ ChangeVarNodes((Node *) subroot.rowMarks, rti, newrti, 0);
+ rte = copyObject(rte);
+ subroot.parse->rtable = lappend(subroot.parse->rtable,
+ rte);
+ }
+ rti++;
+ }
+ }
+
/* We needn't modify the child's append_rel_list */
/* There shouldn't be any OJ info to translate, as yet */
Assert(subroot.join_info_list == NIL);
/* and we haven't created PlaceHolderInfos, either */
Assert(subroot.placeholder_list == NIL);
+ /* hack to mark target relation as an inheritance partition */
+ subroot.hasInheritedTarget = true;
/* Generate plan */
subplan = grouping_planner(&subroot, 0.0 /* retrieve all tuples */ );
/*
* If this child rel was excluded by constraint exclusion, exclude it
- * from the plan.
+ * from the result plan.
*/
if (is_dummy_plan(subplan))
continue;
- /* Save rtable from first rel for use below */
- if (subplans == NIL)
- rtable = subroot.parse->rtable;
-
subplans = lappend(subplans, subplan);
+ /*
+ * If this is the first non-excluded child, its post-planning rtable
+ * becomes the initial contents of final_rtable; otherwise, append
+ * just its modified subquery RTEs to final_rtable.
+ */
+ if (final_rtable == NIL)
+ final_rtable = subroot.parse->rtable;
+ else
+ final_rtable = list_concat(final_rtable,
+ list_copy_tail(subroot.parse->rtable,
+ list_length(final_rtable)));
+
+ /*
+ * We need to collect all the RelOptInfos from all child plans into
+ * the main PlannerInfo, since setrefs.c will need them. We use the
+ * last child's simple_rel_array (previous ones are too short), so we
+ * have to propagate forward the RelOptInfos that were already built
+ * in previous children.
+ */
+ Assert(subroot.simple_rel_array_size >= save_rel_array_size);
+ for (rti = 1; rti < save_rel_array_size; rti++)
+ {
+ RelOptInfo *brel = save_rel_array[rti];
+
+ if (brel)
+ subroot.simple_rel_array[rti] = brel;
+ }
+ save_rel_array_size = subroot.simple_rel_array_size;
+ save_rel_array = subroot.simple_rel_array;
+
/* Make sure any initplans from this rel get into the outer list */
- root->init_plans = list_concat(root->init_plans, subroot.init_plans);
+ root->init_plans = subroot.init_plans;
- /* Build target-relations list for the executor */
+ /* Build list of target-relation RT indexes */
resultRelations = lappend_int(resultRelations, appinfo->child_relid);
/* Build list of per-relation RETURNING targetlists */
if (parse->returningList)
- {
- List *rlist;
-
- rlist = set_returning_clause_references(root->glob,
- subroot.parse->returningList,
- subplan,
- appinfo->child_relid);
- returningLists = lappend(returningLists, rlist);
- }
+ returningLists = lappend(returningLists,
+ subroot.parse->returningList);
}
- root->resultRelations = resultRelations;
-
/* Mark result as unordered (probably unnecessary) */
root->query_pathkeys = NIL;
/*
- * If we managed to exclude every child rel, return a dummy plan;
- * it doesn't even need a ModifyTable node.
+ * If we managed to exclude every child rel, return a dummy plan; it
+ * doesn't even need a ModifyTable node.
*/
if (subplans == NIL)
{
- root->resultRelations = list_make1_int(parentRTindex);
/* although dummy, it must have a valid tlist for executor */
+ List *tlist;
+
tlist = preprocess_targetlist(root, parse->targetList);
return (Plan *) make_result(root,
tlist,
}
/*
- * Planning might have modified the rangetable, due to changes of the
- * Query structures inside subquery RTEs. We have to ensure that this
- * gets propagated back to the master copy. But can't do this until we
- * are done planning, because all the calls to grouping_planner need
- * virgin sub-Queries to work from. (We are effectively assuming that
- * sub-Queries will get planned identically each time, or at least that
- * the impacts on their rangetables will be the same each time.)
- *
- * XXX should clean this up someday
+ * Put back the final adjusted rtable into the master copy of the Query.
*/
- parse->rtable = rtable;
+ parse->rtable = final_rtable;
+ root->simple_rel_array_size = save_rel_array_size;
+ root->simple_rel_array = save_rel_array;
/*
- * If there was a FOR UPDATE/SHARE clause, the LockRows node will
- * have dealt with fetching non-locked marked rows, else we need
- * to have ModifyTable do that.
+ * If there was a FOR UPDATE/SHARE clause, the LockRows node will have
+ * dealt with fetching non-locked marked rows, else we need to have
+ * ModifyTable do that.
*/
if (parse->rowMarks)
rowMarks = NIL;
/* And last, tack on a ModifyTable node to do the UPDATE/DELETE work */
return (Plan *) make_modifytable(parse->commandType,
- copyObject(root->resultRelations),
- subplans,
+ parse->canSetTag,
+ resultRelations,
+ subplans,
returningLists,
rowMarks,
SS_assign_special_param(root));
Plan *result_plan;
List *current_pathkeys;
double dNumGroups = 0;
+ bool use_hashed_distinct = false;
+ bool tested_hashed_distinct = false;
/* Tweak caller-supplied tuple_fraction if have LIMIT/OFFSET */
if (parse->limitCount || parse->limitOffset)
{
/* No set operations, do regular planning */
List *sub_tlist;
+ double sub_limit_tuples;
AttrNumber *groupColIdx = NULL;
bool need_tlist_eval = true;
- QualCost tlist_cost;
Path *cheapest_path;
Path *sorted_path;
Path *best_path;
long numGroups = 0;
- AggClauseCounts agg_counts;
+ AggClauseCosts agg_costs;
int numGroupCols;
+ double path_rows;
+ int path_width;
bool use_hashed_grouping = false;
WindowFuncLists *wflists = NULL;
List *activeWindows = NIL;
- MemSet(&agg_counts, 0, sizeof(AggClauseCounts));
+ MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
/* A recursive query should always have setOperations */
Assert(!root->hasRecursion);
sub_tlist = make_subplanTargetList(root, tlist,
&groupColIdx, &need_tlist_eval);
+ /*
+ * Do aggregate preprocessing, if the query has any aggs.
+ *
+ * Note: think not that we can turn off hasAggs if we find no aggs. It
+ * is possible for constant-expression simplification to remove all
+ * explicit references to aggs, but we still have to follow the
+ * aggregate semantics (eg, producing only one output row).
+ */
+ if (parse->hasAggs)
+ {
+ /*
+ * Collect statistics about aggregates for estimating costs. Note:
+ * we do not attempt to detect duplicate aggregates here; a
+ * somewhat-overestimated cost is okay for our present purposes.
+ */
+ count_agg_clauses(root, (Node *) tlist, &agg_costs);
+ count_agg_clauses(root, parse->havingQual, &agg_costs);
+
+ /*
+ * Preprocess MIN/MAX aggregates, if any. Note: be careful about
+ * adding logic between here and the optimize_minmax_aggregates
+ * call. Anything that is needed in MIN/MAX-optimizable cases
+ * will have to be duplicated in planagg.c.
+ */
+ preprocess_minmax_aggregates(root, tlist);
+ }
+
/*
* Calculate pathkeys that represent grouping/ordering requirements.
* Stash them in PlannerInfo so that query_planner can canonicalize
tlist,
false);
- /*
- * Will need actual number of aggregates for estimating costs.
- *
- * Note: we do not attempt to detect duplicate aggregates here; a
- * somewhat-overestimated count is okay for our present purposes.
- *
- * Note: think not that we can turn off hasAggs if we find no aggs. It
- * is possible for constant-expression simplification to remove all
- * explicit references to aggs, but we still have to follow the
- * aggregate semantics (eg, producing only one output row).
- */
- if (parse->hasAggs)
- {
- count_agg_clauses((Node *) tlist, &agg_counts);
- count_agg_clauses(parse->havingQual, &agg_counts);
- }
-
/*
* Figure out whether we want a sorted result from query_planner.
*
else
root->query_pathkeys = NIL;
+ /*
+ * Figure out whether there's a hard limit on the number of rows that
+ * query_planner's result subplan needs to return. Even if we know a
+ * hard limit overall, it doesn't apply if the query has any
+ * grouping/aggregation operations.
+ */
+ if (parse->groupClause ||
+ parse->distinctClause ||
+ parse->hasAggs ||
+ parse->hasWindowFuncs ||
+ root->hasHavingQual)
+ sub_limit_tuples = -1.0;
+ else
+ sub_limit_tuples = limit_tuples;
+
/*
* Generate the best unsorted and presorted paths for this Query (but
* note there may not be any presorted path). query_planner will also
* estimate the number of groups in the query, and canonicalize all
* the pathkeys.
*/
- query_planner(root, sub_tlist, tuple_fraction, limit_tuples,
+ query_planner(root, sub_tlist, tuple_fraction, sub_limit_tuples,
&cheapest_path, &sorted_path, &dNumGroups);
/*
- * If grouping, decide whether to use sorted or hashed grouping.
+ * Extract rowcount and width estimates for possible use in grouping
+ * decisions. Beware here of the possibility that
+ * cheapest_path->parent is NULL (ie, there is no FROM clause).
*/
- if (parse->groupClause)
+ if (cheapest_path->parent)
{
- bool can_hash;
- bool can_sort;
+ path_rows = cheapest_path->parent->rows;
+ path_width = cheapest_path->parent->width;
+ }
+ else
+ {
+ path_rows = 1; /* assume non-set result */
+ path_width = 100; /* arbitrary */
+ }
+ if (parse->groupClause)
+ {
/*
- * Executor doesn't support hashed aggregation with DISTINCT or
- * ORDER BY aggregates. (Doing so would imply storing *all* the
- * input values in the hash table, and/or running many sorts in
- * parallel, either of which seems like a certain loser.)
+ * If grouping, decide whether to use sorted or hashed grouping.
*/
- can_hash = (agg_counts.numOrderedAggs == 0 &&
- grouping_is_hashable(parse->groupClause));
- can_sort = grouping_is_sortable(parse->groupClause);
- if (can_hash && can_sort)
- {
- /* we have a meaningful choice to make ... */
- use_hashed_grouping =
- choose_hashed_grouping(root,
- tuple_fraction, limit_tuples,
- cheapest_path, sorted_path,
- dNumGroups, &agg_counts);
- }
- else if (can_hash)
- use_hashed_grouping = true;
- else if (can_sort)
- use_hashed_grouping = false;
- else
- ereport(ERROR,
- (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
- errmsg("could not implement GROUP BY"),
- errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
-
+ use_hashed_grouping =
+ choose_hashed_grouping(root,
+ tuple_fraction, limit_tuples,
+ path_rows, path_width,
+ cheapest_path, sorted_path,
+ dNumGroups, &agg_costs);
/* Also convert # groups to long int --- but 'ware overflow! */
numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
}
+ else if (parse->distinctClause && sorted_path &&
+ !root->hasHavingQual && !parse->hasAggs && !activeWindows)
+ {
+ /*
+ * We'll reach the DISTINCT stage without any intermediate
+ * processing, so figure out whether we will want to hash or not
+ * so we can choose whether to use cheapest or sorted path.
+ */
+ use_hashed_distinct =
+ choose_hashed_distinct(root,
+ tuple_fraction, limit_tuples,
+ path_rows, path_width,
+ cheapest_path->startup_cost,
+ cheapest_path->total_cost,
+ sorted_path->startup_cost,
+ sorted_path->total_cost,
+ sorted_path->pathkeys,
+ dNumGroups);
+ tested_hashed_distinct = true;
+ }
/*
* Select the best path. If we are doing hashed grouping, we will
* always read all the input tuples, so use the cheapest-total path.
* Otherwise, trust query_planner's decision about which to use.
*/
- if (use_hashed_grouping || !sorted_path)
+ if (use_hashed_grouping || use_hashed_distinct || !sorted_path)
best_path = cheapest_path;
else
best_path = sorted_path;
*/
result_plan = optimize_minmax_aggregates(root,
tlist,
+ &agg_costs,
best_path);
if (result_plan != NULL)
{
need_sort_for_grouping = true;
/*
- * Always override query_planner's tlist, so that we don't
- * sort useless data from a "physical" tlist.
+ * Always override create_plan's tlist, so that we don't sort
+ * useless data from a "physical" tlist.
*/
need_tlist_eval = true;
}
/*
- * create_plan() returns a plan with just a "flat" tlist of
- * required Vars. Usually we need to insert the sub_tlist as the
- * tlist of the top plan node. However, we can skip that if we
- * determined that whatever query_planner chose to return will be
- * good enough.
+ * create_plan returns a plan with just a "flat" tlist of required
+ * Vars. Usually we need to insert the sub_tlist as the tlist of
+ * the top plan node. However, we can skip that if we determined
+ * that whatever create_plan chose to return will be good enough.
*/
if (need_tlist_eval)
{
/*
* Also, account for the cost of evaluation of the sub_tlist.
- *
- * Up to now, we have only been dealing with "flat" tlists,
- * containing just Vars. So their evaluation cost is zero
- * according to the model used by cost_qual_eval() (or if you
- * prefer, the cost is factored into cpu_tuple_cost). Thus we
- * can avoid accounting for tlist cost throughout
- * query_planner() and subroutines. But now we've inserted a
- * tlist that might contain actual operators, sub-selects, etc
- * --- so we'd better account for its cost.
- *
- * Below this point, any tlist eval cost for added-on nodes
- * should be accounted for as we create those nodes.
- * Presently, of the node types we can add on, only Agg,
- * WindowAgg, and Group project new tlists (the rest just copy
- * their input tuples) --- so make_agg(), make_windowagg() and
- * make_group() are responsible for computing the added cost.
+ * See comments for add_tlist_costs_to_plan() for more info.
*/
- cost_qual_eval(&tlist_cost, sub_tlist, root);
- result_plan->startup_cost += tlist_cost.startup;
- result_plan->total_cost += tlist_cost.startup +
- tlist_cost.per_tuple * result_plan->plan_rows;
+ add_tlist_costs_to_plan(root, result_plan, sub_tlist);
}
else
{
/*
- * Since we're using query_planner's tlist and not the one
+ * Since we're using create_plan's tlist and not the one
* make_subplanTargetList calculated, we have to refigure any
* grouping-column indexes make_subplanTargetList computed.
*/
tlist,
(List *) parse->havingQual,
AGG_HASHED,
+ &agg_costs,
numGroupCols,
groupColIdx,
extract_grouping_ops(parse->groupClause),
numGroups,
- agg_counts.numAggs,
result_plan);
/* Hashed aggregation produces randomly-ordered results */
current_pathkeys = NIL;
tlist,
(List *) parse->havingQual,
aggstrategy,
+ &agg_costs,
numGroupCols,
groupColIdx,
extract_grouping_ops(parse->groupClause),
numGroups,
- agg_counts.numAggs,
result_plan);
}
else if (parse->groupClause)
* WindowFuncs. It's probably not worth trying to optimize that
* though.) We also need any volatile sort expressions, because
* make_sort_from_pathkeys won't add those on its own, and anyway
- * we want them evaluated only once at the bottom of the stack.
- * As we climb up the stack, we add outputs for the WindowFuncs
+ * we want them evaluated only once at the bottom of the stack. As
+ * we climb up the stack, we add outputs for the WindowFuncs
* computed at each level. Also, each input tlist has to present
* all the columns needed to sort the data for the next WindowAgg
* step. That's handled internally by make_sort_from_pathkeys,
* but we need the copyObject steps here to ensure that each plan
* node has a separately modifiable tlist.
+ *
+ * Note: it's essential here to use PVC_INCLUDE_AGGREGATES so that
+ * Vars mentioned only in aggregate expressions aren't pulled out
+ * as separate targetlist entries. Otherwise we could be putting
+ * ungrouped Vars directly into an Agg node's tlist, resulting in
+ * undefined behavior.
*/
- window_tlist = flatten_tlist(tlist);
- if (parse->hasAggs)
- window_tlist = add_to_flat_tlist(window_tlist,
- pull_agg_clause((Node *) tlist));
+ window_tlist = flatten_tlist(tlist,
+ PVC_INCLUDE_AGGREGATES,
+ PVC_INCLUDE_PLACEHOLDERS);
window_tlist = add_volatile_sort_exprs(window_tlist, tlist,
activeWindows);
result_plan->targetlist = (List *) copyObject(window_tlist);
result_plan = (Plan *)
make_windowagg(root,
(List *) copyObject(window_tlist),
- list_length(wflists->windowFuncs[wc->winref]),
+ wflists->windowFuncs[wc->winref],
wc->winref,
partNumCols,
partColIdx,
ordColIdx,
ordOperators,
wc->frameOptions,
+ wc->startOffset,
+ wc->endOffset,
result_plan);
}
}
{
double dNumDistinctRows;
long numDistinctRows;
- bool use_hashed_distinct;
- bool can_sort;
- bool can_hash;
/*
* If there was grouping or aggregation, use the current number of
/* Also convert to long int --- but 'ware overflow! */
numDistinctRows = (long) Min(dNumDistinctRows, (double) LONG_MAX);
- /*
- * If we have a sortable DISTINCT ON clause, we always use sorting.
- * This enforces the expected behavior of DISTINCT ON.
- */
- can_sort = grouping_is_sortable(parse->distinctClause);
- if (can_sort && parse->hasDistinctOn)
- use_hashed_distinct = false;
- else
+ /* Choose implementation method if we didn't already */
+ if (!tested_hashed_distinct)
{
- can_hash = grouping_is_hashable(parse->distinctClause);
- if (can_hash && can_sort)
- {
- /* we have a meaningful choice to make ... */
- use_hashed_distinct =
- choose_hashed_distinct(root,
- result_plan, current_pathkeys,
- tuple_fraction, limit_tuples,
- dNumDistinctRows);
- }
- else if (can_hash)
- use_hashed_distinct = true;
- else if (can_sort)
- use_hashed_distinct = false;
- else
- {
- ereport(ERROR,
- (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
- errmsg("could not implement DISTINCT"),
- errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
- use_hashed_distinct = false; /* keep compiler quiet */
- }
+ /*
+ * At this point, either hashed or sorted grouping will have to
+ * work from result_plan, so we pass that as both "cheapest" and
+ * "sorted".
+ */
+ use_hashed_distinct =
+ choose_hashed_distinct(root,
+ tuple_fraction, limit_tuples,
+ result_plan->plan_rows,
+ result_plan->plan_width,
+ result_plan->startup_cost,
+ result_plan->total_cost,
+ result_plan->startup_cost,
+ result_plan->total_cost,
+ current_pathkeys,
+ dNumDistinctRows);
}
if (use_hashed_distinct)
result_plan->targetlist,
NIL,
AGG_HASHED,
+ NULL,
list_length(parse->distinctClause),
extract_grouping_cols(parse->distinctClause,
result_plan->targetlist),
extract_grouping_ops(parse->distinctClause),
numDistinctRows,
- 0,
result_plan);
/* Hashed aggregation produces randomly-ordered results */
current_pathkeys = NIL;
}
/*
- * If there is a FOR UPDATE/SHARE clause, add the LockRows node.
- * (Note: we intentionally test parse->rowMarks not root->rowMarks here.
- * If there are only non-locking rowmarks, they should be handled by
- * the ModifyTable node instead.)
+ * If there is a FOR UPDATE/SHARE clause, add the LockRows node. (Note: we
+ * intentionally test parse->rowMarks not root->rowMarks here. If there
+ * are only non-locking rowmarks, they should be handled by the
+ * ModifyTable node instead.)
*/
if (parse->rowMarks)
{
result_plan = (Plan *) make_lockrows(result_plan,
root->rowMarks,
SS_assign_special_param(root));
+
/*
* The result can no longer be assumed sorted, since locking might
* cause the sort key columns to be replaced with new values.
count_est);
}
- /* Compute result-relations list if needed */
- if (parse->resultRelation)
- root->resultRelations = list_make1_int(parse->resultRelation);
- else
- root->resultRelations = NIL;
-
/*
* Return the actual output ordering in query_pathkeys for possible use by
* an outer query level.
return result_plan;
}
+/*
+ * add_tlist_costs_to_plan
+ *
+ * Estimate the execution costs associated with evaluating the targetlist
+ * expressions, and add them to the cost estimates for the Plan node.
+ *
+ * If the tlist contains set-returning functions, also inflate the Plan's cost
+ * and plan_rows estimates accordingly. (Hence, this must be called *after*
+ * any logic that uses plan_rows to, eg, estimate qual evaluation costs.)
+ *
+ * Note: during initial stages of planning, we mostly consider plan nodes with
+ * "flat" tlists, containing just Vars. So their evaluation cost is zero
+ * according to the model used by cost_qual_eval() (or if you prefer, the cost
+ * is factored into cpu_tuple_cost). Thus we can avoid accounting for tlist
+ * cost throughout query_planner() and subroutines. But once we apply a
+ * tlist that might contain actual operators, sub-selects, etc, we'd better
+ * account for its cost. Any set-returning functions in the tlist must also
+ * affect the estimated rowcount.
+ *
+ * Once grouping_planner() has applied a general tlist to the topmost
+ * scan/join plan node, any tlist eval cost for added-on nodes should be
+ * accounted for as we create those nodes. Presently, of the node types we
+ * can add on later, only Agg, WindowAgg, and Group project new tlists (the
+ * rest just copy their input tuples) --- so make_agg(), make_windowagg() and
+ * make_group() are responsible for calling this function to account for their
+ * tlist costs.
+ */
+void
+add_tlist_costs_to_plan(PlannerInfo *root, Plan *plan, List *tlist)
+{
+ QualCost tlist_cost;
+ double tlist_rows;
+
+ cost_qual_eval(&tlist_cost, tlist, root);
+ plan->startup_cost += tlist_cost.startup;
+ plan->total_cost += tlist_cost.startup +
+ tlist_cost.per_tuple * plan->plan_rows;
+
+ tlist_rows = tlist_returns_set_rows(tlist);
+ if (tlist_rows > 1)
+ {
+ /*
+ * We assume that execution costs of the tlist proper were all
+ * accounted for by cost_qual_eval. However, it still seems
+ * appropriate to charge something more for the executor's general
+ * costs of processing the added tuples. The cost is probably less
+ * than cpu_tuple_cost, though, so we arbitrarily use half of that.
+ */
+ plan->total_cost += plan->plan_rows * (tlist_rows - 1) *
+ cpu_tuple_cost / 2;
+
+ plan->plan_rows *= tlist_rows;
+ }
+}
+
/*
* Detect whether a plan node is a "dummy" plan created when a relation
* is deemed not to need scanning due to constraint exclusion.
*
* Currently, such dummy plans are Result nodes with constant FALSE
- * filter quals.
+ * filter quals (see set_dummy_rel_pathlist and create_append_plan).
+ *
+ * XXX this probably ought to be somewhere else, but not clear where.
*/
-static bool
+bool
is_dummy_plan(Plan *plan)
{
if (IsA(plan, Result))
}
/*
- * We need to have rowmarks for all base relations except the target.
- * We make a bitmapset of all base rels and then remove the items we
- * don't need or have FOR UPDATE/SHARE marks for.
+ * We need to have rowmarks for all base relations except the target. We
+ * make a bitmapset of all base rels and then remove the items we don't
+ * need or have FOR UPDATE/SHARE marks for.
*/
rels = get_base_rel_indexes((Node *) parse->jointree);
if (parse->resultRelation)
/*
* Currently, it is syntactically impossible to have FOR UPDATE
- * applied to an update/delete target rel. If that ever becomes
+ * applied to an update/delete target rel. If that ever becomes
* possible, we should drop the target from the PlanRowMark list.
*/
Assert(rc->rti != parse->resultRelation);
/*
- * Ignore RowMarkClauses for subqueries; they aren't real tables
- * and can't support true locking. Subqueries that got flattened
- * into the main query should be ignored completely. Any that didn't
- * will get ROW_MARK_COPY items in the next loop.
+ * Ignore RowMarkClauses for subqueries; they aren't real tables and
+ * can't support true locking. Subqueries that got flattened into the
+ * main query should be ignored completely. Any that didn't will get
+ * ROW_MARK_COPY items in the next loop.
*/
if (rte->rtekind != RTE_RELATION)
continue;
newrc = makeNode(PlanRowMark);
newrc->rti = newrc->prti = rc->rti;
+ newrc->rowmarkId = ++(root->glob->lastRowMarkId);
if (rc->forUpdate)
newrc->markType = ROW_MARK_EXCLUSIVE;
else
newrc->markType = ROW_MARK_SHARE;
newrc->noWait = rc->noWait;
newrc->isParent = false;
- /* attnos will be assigned in preprocess_targetlist */
- newrc->ctidAttNo = InvalidAttrNumber;
- newrc->toidAttNo = InvalidAttrNumber;
- newrc->wholeAttNo = InvalidAttrNumber;
prowmarks = lappend(prowmarks, newrc);
}
newrc = makeNode(PlanRowMark);
newrc->rti = newrc->prti = i;
+ newrc->rowmarkId = ++(root->glob->lastRowMarkId);
/* real tables support REFERENCE, anything else needs COPY */
- if (rte->rtekind == RTE_RELATION)
+ if (rte->rtekind == RTE_RELATION &&
+ rte->relkind != RELKIND_FOREIGN_TABLE)
newrc->markType = ROW_MARK_REFERENCE;
else
newrc->markType = ROW_MARK_COPY;
- newrc->noWait = false; /* doesn't matter */
+ newrc->noWait = false; /* doesn't matter */
newrc->isParent = false;
- /* attnos will be assigned in preprocess_targetlist */
- newrc->ctidAttNo = InvalidAttrNumber;
- newrc->toidAttNo = InvalidAttrNumber;
- newrc->wholeAttNo = InvalidAttrNumber;
prowmarks = lappend(prowmarks, newrc);
}
/*
* choose_hashed_grouping - should we use hashed grouping?
*
- * Note: this is only applied when both alternatives are actually feasible.
+ * Returns TRUE to select hashing, FALSE to select sorting.
*/
static bool
choose_hashed_grouping(PlannerInfo *root,
double tuple_fraction, double limit_tuples,
+ double path_rows, int path_width,
Path *cheapest_path, Path *sorted_path,
- double dNumGroups, AggClauseCounts *agg_counts)
+ double dNumGroups, AggClauseCosts *agg_costs)
{
- int numGroupCols = list_length(root->parse->groupClause);
- double cheapest_path_rows;
- int cheapest_path_width;
+ Query *parse = root->parse;
+ int numGroupCols = list_length(parse->groupClause);
+ bool can_hash;
+ bool can_sort;
Size hashentrysize;
List *target_pathkeys;
List *current_pathkeys;
Path hashed_p;
Path sorted_p;
+ /*
+ * Executor doesn't support hashed aggregation with DISTINCT or ORDER BY
+ * aggregates. (Doing so would imply storing *all* the input values in
+ * the hash table, and/or running many sorts in parallel, either of which
+ * seems like a certain loser.)
+ */
+ can_hash = (agg_costs->numOrderedAggs == 0 &&
+ grouping_is_hashable(parse->groupClause));
+ can_sort = grouping_is_sortable(parse->groupClause);
+
+ /* Quick out if only one choice is workable */
+ if (!(can_hash && can_sort))
+ {
+ if (can_hash)
+ return true;
+ else if (can_sort)
+ return false;
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("could not implement GROUP BY"),
+ errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
+ }
+
/* Prefer sorting when enable_hashagg is off */
if (!enable_hashagg)
return false;
/*
* Don't do it if it doesn't look like the hashtable will fit into
* work_mem.
- *
- * Beware here of the possibility that cheapest_path->parent is NULL. This
- * could happen if user does something silly like SELECT 'foo' GROUP BY 1;
*/
- if (cheapest_path->parent)
- {
- cheapest_path_rows = cheapest_path->parent->rows;
- cheapest_path_width = cheapest_path->parent->width;
- }
- else
- {
- cheapest_path_rows = 1; /* assume non-set result */
- cheapest_path_width = 100; /* arbitrary */
- }
/* Estimate per-hash-entry space at tuple width... */
- hashentrysize = MAXALIGN(cheapest_path_width) + MAXALIGN(sizeof(MinimalTupleData));
+ hashentrysize = MAXALIGN(path_width) + MAXALIGN(sizeof(MinimalTupleData));
/* plus space for pass-by-ref transition values... */
- hashentrysize += agg_counts->transitionSpace;
+ hashentrysize += agg_costs->transitionSpace;
/* plus the per-hash-entry overhead */
- hashentrysize += hash_agg_entry_size(agg_counts->numAggs);
+ hashentrysize += hash_agg_entry_size(agg_costs->numAggs);
if (hashentrysize * dNumGroups > work_mem * 1024L)
return false;
* These path variables are dummies that just hold cost fields; we don't
* make actual Paths for these steps.
*/
- cost_agg(&hashed_p, root, AGG_HASHED, agg_counts->numAggs,
+ cost_agg(&hashed_p, root, AGG_HASHED, agg_costs,
numGroupCols, dNumGroups,
cheapest_path->startup_cost, cheapest_path->total_cost,
- cheapest_path_rows);
+ path_rows);
/* Result of hashed agg is always unsorted */
if (target_pathkeys)
cost_sort(&hashed_p, root, target_pathkeys, hashed_p.total_cost,
- dNumGroups, cheapest_path_width, limit_tuples);
+ dNumGroups, path_width,
+ 0.0, work_mem, limit_tuples);
if (sorted_path)
{
if (!pathkeys_contained_in(root->group_pathkeys, current_pathkeys))
{
cost_sort(&sorted_p, root, root->group_pathkeys, sorted_p.total_cost,
- cheapest_path_rows, cheapest_path_width, -1.0);
+ path_rows, path_width,
+ 0.0, work_mem, -1.0);
current_pathkeys = root->group_pathkeys;
}
- if (root->parse->hasAggs)
- cost_agg(&sorted_p, root, AGG_SORTED, agg_counts->numAggs,
+ if (parse->hasAggs)
+ cost_agg(&sorted_p, root, AGG_SORTED, agg_costs,
numGroupCols, dNumGroups,
sorted_p.startup_cost, sorted_p.total_cost,
- cheapest_path_rows);
+ path_rows);
else
cost_group(&sorted_p, root, numGroupCols, dNumGroups,
sorted_p.startup_cost, sorted_p.total_cost,
- cheapest_path_rows);
+ path_rows);
/* The Agg or Group node will preserve ordering */
if (target_pathkeys &&
!pathkeys_contained_in(target_pathkeys, current_pathkeys))
cost_sort(&sorted_p, root, target_pathkeys, sorted_p.total_cost,
- dNumGroups, cheapest_path_width, limit_tuples);
+ dNumGroups, path_width,
+ 0.0, work_mem, limit_tuples);
/*
* Now make the decision using the top-level tuple fraction. First we
*
* This is fairly similar to choose_hashed_grouping, but there are enough
* differences that it doesn't seem worth trying to unify the two functions.
+ * (One difference is that we sometimes apply this after forming a Plan,
+ * so the input alternatives can't be represented as Paths --- instead we
+ * pass in the costs as individual variables.)
*
* But note that making the two choices independently is a bit bogus in
* itself. If the two could be combined into a single choice operation
* extra preference to using a sorting implementation when a common sort key
* is available ... and that's not necessarily wrong anyway.
*
- * Note: this is only applied when both alternatives are actually feasible.
+ * Returns TRUE to select hashing, FALSE to select sorting.
*/
static bool
choose_hashed_distinct(PlannerInfo *root,
- Plan *input_plan, List *input_pathkeys,
double tuple_fraction, double limit_tuples,
+ double path_rows, int path_width,
+ Cost cheapest_startup_cost, Cost cheapest_total_cost,
+ Cost sorted_startup_cost, Cost sorted_total_cost,
+ List *sorted_pathkeys,
double dNumDistinctRows)
{
- int numDistinctCols = list_length(root->parse->distinctClause);
+ Query *parse = root->parse;
+ int numDistinctCols = list_length(parse->distinctClause);
+ bool can_sort;
+ bool can_hash;
Size hashentrysize;
List *current_pathkeys;
List *needed_pathkeys;
Path hashed_p;
Path sorted_p;
+ /*
+ * If we have a sortable DISTINCT ON clause, we always use sorting. This
+ * enforces the expected behavior of DISTINCT ON.
+ */
+ can_sort = grouping_is_sortable(parse->distinctClause);
+ if (can_sort && parse->hasDistinctOn)
+ return false;
+
+ can_hash = grouping_is_hashable(parse->distinctClause);
+
+ /* Quick out if only one choice is workable */
+ if (!(can_hash && can_sort))
+ {
+ if (can_hash)
+ return true;
+ else if (can_sort)
+ return false;
+ else
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("could not implement DISTINCT"),
+ errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
+ }
+
/* Prefer sorting when enable_hashagg is off */
if (!enable_hashagg)
return false;
* Don't do it if it doesn't look like the hashtable will fit into
* work_mem.
*/
- hashentrysize = MAXALIGN(input_plan->plan_width) + MAXALIGN(sizeof(MinimalTupleData));
+ hashentrysize = MAXALIGN(path_width) + MAXALIGN(sizeof(MinimalTupleData));
if (hashentrysize * dNumDistinctRows > work_mem * 1024L)
return false;
* output won't be sorted may be a loss; so we need to do an actual cost
* comparison.
*
- * We need to consider input_plan + hashagg [+ final sort] versus
- * input_plan [+ sort] + group [+ final sort] where brackets indicate a
+ * We need to consider cheapest_path + hashagg [+ final sort] versus
+ * sorted_path [+ sort] + group [+ final sort] where brackets indicate a
* step that may not be needed.
*
* These path variables are dummies that just hold cost fields; we don't
* make actual Paths for these steps.
*/
- cost_agg(&hashed_p, root, AGG_HASHED, 0,
+ cost_agg(&hashed_p, root, AGG_HASHED, NULL,
numDistinctCols, dNumDistinctRows,
- input_plan->startup_cost, input_plan->total_cost,
- input_plan->plan_rows);
+ cheapest_startup_cost, cheapest_total_cost,
+ path_rows);
/*
* Result of hashed agg is always unsorted, so if ORDER BY is present we
* need to charge for the final sort.
*/
- if (root->parse->sortClause)
+ if (parse->sortClause)
cost_sort(&hashed_p, root, root->sort_pathkeys, hashed_p.total_cost,
- dNumDistinctRows, input_plan->plan_width, limit_tuples);
+ dNumDistinctRows, path_width,
+ 0.0, work_mem, limit_tuples);
/*
* Now for the GROUP case. See comments in grouping_planner about the
* sorting choices here --- this code should match that code.
*/
- sorted_p.startup_cost = input_plan->startup_cost;
- sorted_p.total_cost = input_plan->total_cost;
- current_pathkeys = input_pathkeys;
- if (root->parse->hasDistinctOn &&
+ sorted_p.startup_cost = sorted_startup_cost;
+ sorted_p.total_cost = sorted_total_cost;
+ current_pathkeys = sorted_pathkeys;
+ if (parse->hasDistinctOn &&
list_length(root->distinct_pathkeys) <
list_length(root->sort_pathkeys))
needed_pathkeys = root->sort_pathkeys;
else
current_pathkeys = root->sort_pathkeys;
cost_sort(&sorted_p, root, current_pathkeys, sorted_p.total_cost,
- input_plan->plan_rows, input_plan->plan_width, -1.0);
+ path_rows, path_width,
+ 0.0, work_mem, -1.0);
}
cost_group(&sorted_p, root, numDistinctCols, dNumDistinctRows,
sorted_p.startup_cost, sorted_p.total_cost,
- input_plan->plan_rows);
- if (root->parse->sortClause &&
+ path_rows);
+ if (parse->sortClause &&
!pathkeys_contained_in(root->sort_pathkeys, current_pathkeys))
cost_sort(&sorted_p, root, root->sort_pathkeys, sorted_p.total_cost,
- dNumDistinctRows, input_plan->plan_width, limit_tuples);
+ dNumDistinctRows, path_width,
+ 0.0, work_mem, limit_tuples);
/*
* Now make the decision using the top-level tuple fraction. First we
return false;
}
-/*---------------
+/*
* make_subplanTargetList
* Generate appropriate target list when grouping is required.
*
- * When grouping_planner inserts Aggregate, Group, or Result plan nodes
- * above the result of query_planner, we typically want to pass a different
- * target list to query_planner than the outer plan nodes should have.
- * This routine generates the correct target list for the subplan.
+ * When grouping_planner inserts grouping or aggregation plan nodes
+ * above the scan/join plan constructed by query_planner+create_plan,
+ * we typically want the scan/join plan to emit a different target list
+ * than the outer plan nodes should have. This routine generates the
+ * correct target list for the scan/join subplan.
*
* The initial target list passed from the parser already contains entries
* for all ORDER BY and GROUP BY expressions, but it will not have entries
* For example, given a query like
* SELECT a+b,SUM(c+d) FROM table GROUP BY a+b;
* we want to pass this targetlist to the subplan:
- * a,b,c,d,a+b
+ * a+b,c,d
* where the a+b target will be used by the Sort/Group steps, and the
- * other targets will be used for computing the final results. (In the
- * above example we could theoretically suppress the a and b targets and
- * pass down only c,d,a+b, but it's not really worth the trouble to
- * eliminate simple var references from the subplan. We will avoid doing
- * the extra computation to recompute a+b at the outer level; see
- * fix_upper_expr() in setrefs.c.)
+ * other targets will be used for computing the final results.
*
* If we are grouping or aggregating, *and* there are no non-Var grouping
* expressions, then the returned tlist is effectively dummy; we do not
* need to force it to be evaluated, because all the Vars it contains
- * should be present in the output of query_planner anyway.
+ * should be present in the "flat" tlist generated by create_plan, though
+ * possibly in a different order. In that case we'll use create_plan's tlist,
+ * and the tlist made here is only needed as input to query_planner to tell
+ * it which Vars are needed in the output of the scan/join plan.
*
* 'tlist' is the query's target list.
* 'groupColIdx' receives an array of column numbers for the GROUP BY
- * expressions (if there are any) in the subplan's target list.
+ * expressions (if there are any) in the returned target list.
* 'need_tlist_eval' is set true if we really need to evaluate the
- * result tlist.
+ * returned tlist as-is.
*
- * The result is the targetlist to be passed to the subplan.
- *---------------
+ * The result is the targetlist to be passed to query_planner.
*/
static List *
make_subplanTargetList(PlannerInfo *root,
{
Query *parse = root->parse;
List *sub_tlist;
- List *extravars;
+ List *non_group_cols;
+ List *non_group_vars;
int numCols;
*groupColIdx = NULL;
}
/*
- * Otherwise, start with a "flattened" tlist (having just the vars
- * mentioned in the targetlist and HAVING qual --- but not upper-level
- * Vars; they will be replaced by Params later on). Note this includes
- * vars used in resjunk items, so we are covering the needs of ORDER BY
- * and window specifications.
+ * Otherwise, we must build a tlist containing all grouping columns, plus
+ * any other Vars mentioned in the targetlist and HAVING qual.
*/
- sub_tlist = flatten_tlist(tlist);
- extravars = pull_var_clause(parse->havingQual, PVC_INCLUDE_PLACEHOLDERS);
- sub_tlist = add_to_flat_tlist(sub_tlist, extravars);
- list_free(extravars);
+ sub_tlist = NIL;
+ non_group_cols = NIL;
*need_tlist_eval = false; /* only eval if not flat tlist */
- /*
- * If grouping, create sub_tlist entries for all GROUP BY expressions
- * (GROUP BY items that are simple Vars should be in the list already),
- * and make an array showing where the group columns are in the sub_tlist.
- */
numCols = list_length(parse->groupClause);
if (numCols > 0)
{
- int keyno = 0;
+ /*
+ * If grouping, create sub_tlist entries for all GROUP BY columns, and
+ * make an array showing where the group columns are in the sub_tlist.
+ *
+ * Note: with this implementation, the array entries will always be
+ * 1..N, but we don't want callers to assume that.
+ */
AttrNumber *grpColIdx;
- ListCell *gl;
+ ListCell *tl;
- grpColIdx = (AttrNumber *) palloc(sizeof(AttrNumber) * numCols);
+ grpColIdx = (AttrNumber *) palloc0(sizeof(AttrNumber) * numCols);
*groupColIdx = grpColIdx;
- foreach(gl, parse->groupClause)
+ foreach(tl, tlist)
{
- SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
- Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
- TargetEntry *te;
+ TargetEntry *tle = (TargetEntry *) lfirst(tl);
+ int colno;
- /*
- * Find or make a matching sub_tlist entry. If the groupexpr
- * isn't a Var, no point in searching. (Note that the parser
- * won't make multiple groupClause entries for the same TLE.)
- */
- if (groupexpr && IsA(groupexpr, Var))
- te = tlist_member(groupexpr, sub_tlist);
- else
- te = NULL;
+ colno = get_grouping_column_index(parse, tle);
+ if (colno >= 0)
+ {
+ /*
+ * It's a grouping column, so add it to the result tlist and
+ * remember its resno in grpColIdx[].
+ */
+ TargetEntry *newtle;
- if (!te)
+ newtle = makeTargetEntry(tle->expr,
+ list_length(sub_tlist) + 1,
+ NULL,
+ false);
+ sub_tlist = lappend(sub_tlist, newtle);
+
+ Assert(grpColIdx[colno] == 0); /* no dups expected */
+ grpColIdx[colno] = newtle->resno;
+
+ if (!(newtle->expr && IsA(newtle->expr, Var)))
+ *need_tlist_eval = true; /* tlist contains non Vars */
+ }
+ else
{
- te = makeTargetEntry((Expr *) groupexpr,
- list_length(sub_tlist) + 1,
- NULL,
- false);
- sub_tlist = lappend(sub_tlist, te);
- *need_tlist_eval = true; /* it's not flat anymore */
+ /*
+ * Non-grouping column, so just remember the expression for
+ * later call to pull_var_clause. There's no need for
+ * pull_var_clause to examine the TargetEntry node itself.
+ */
+ non_group_cols = lappend(non_group_cols, tle->expr);
}
-
- /* and save its resno */
- grpColIdx[keyno++] = te->resno;
}
}
+ else
+ {
+ /*
+ * With no grouping columns, just pass whole tlist to pull_var_clause.
+ * Need (shallow) copy to avoid damaging input tlist below.
+ */
+ non_group_cols = list_copy(tlist);
+ }
+
+ /*
+ * If there's a HAVING clause, we'll need the Vars it uses, too.
+ */
+ if (parse->havingQual)
+ non_group_cols = lappend(non_group_cols, parse->havingQual);
+
+ /*
+ * Pull out all the Vars mentioned in non-group cols (plus HAVING), and
+ * add them to the result tlist if not already present. (A Var used
+ * directly as a GROUP BY item will be present already.) Note this
+ * includes Vars used in resjunk items, so we are covering the needs of
+ * ORDER BY and window specifications. Vars used within Aggrefs will be
+ * pulled out here, too.
+ */
+ non_group_vars = pull_var_clause((Node *) non_group_cols,
+ PVC_RECURSE_AGGREGATES,
+ PVC_INCLUDE_PLACEHOLDERS);
+ sub_tlist = add_to_flat_tlist(sub_tlist, non_group_vars);
+
+ /* clean up cruft */
+ list_free(non_group_vars);
+ list_free(non_group_cols);
return sub_tlist;
}
+/*
+ * get_grouping_column_index
+ * Get the GROUP BY column position, if any, of a targetlist entry.
+ *
+ * Returns the index (counting from 0) of the TLE in the GROUP BY list, or -1
+ * if it's not a grouping column. Note: the result is unique because the
+ * parser won't make multiple groupClause entries for the same TLE.
+ */
+static int
+get_grouping_column_index(Query *parse, TargetEntry *tle)
+{
+ int colno = 0;
+ Index ressortgroupref = tle->ressortgroupref;
+ ListCell *gl;
+
+ /* No need to search groupClause if TLE hasn't got a sortgroupref */
+ if (ressortgroupref == 0)
+ return -1;
+
+ foreach(gl, parse->groupClause)
+ {
+ SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
+
+ if (grpcl->tleSortGroupRef == ressortgroupref)
+ return colno;
+ colno++;
+ }
+
+ return -1;
+}
+
/*
* locate_grouping_columns
- * Locate grouping columns in the tlist chosen by query_planner.
+ * Locate grouping columns in the tlist chosen by create_plan.
*
* This is only needed if we don't use the sub_tlist chosen by
* make_subplanTargetList. We have to forget the column indexes found
return (Expr *) result;
}
+
+
+/*
+ * plan_cluster_use_sort
+ * Use the planner to decide how CLUSTER should implement sorting
+ *
+ * tableOid is the OID of a table to be clustered on its index indexOid
+ * (which is already known to be a btree index). Decide whether it's
+ * cheaper to do an indexscan or a seqscan-plus-sort to execute the CLUSTER.
+ * Return TRUE to use sorting, FALSE to use an indexscan.
+ *
+ * Note: caller had better already hold some type of lock on the table.
+ */
+bool
+plan_cluster_use_sort(Oid tableOid, Oid indexOid)
+{
+ PlannerInfo *root;
+ Query *query;
+ PlannerGlobal *glob;
+ RangeTblEntry *rte;
+ RelOptInfo *rel;
+ IndexOptInfo *indexInfo;
+ QualCost indexExprCost;
+ Cost comparisonCost;
+ Path *seqScanPath;
+ Path seqScanAndSortPath;
+ IndexPath *indexScanPath;
+ ListCell *lc;
+
+ /* Set up mostly-dummy planner state */
+ query = makeNode(Query);
+ query->commandType = CMD_SELECT;
+
+ glob = makeNode(PlannerGlobal);
+
+ root = makeNode(PlannerInfo);
+ root->parse = query;
+ root->glob = glob;
+ root->query_level = 1;
+ root->planner_cxt = CurrentMemoryContext;
+ root->wt_param_id = -1;
+
+ /* Build a minimal RTE for the rel */
+ rte = makeNode(RangeTblEntry);
+ rte->rtekind = RTE_RELATION;
+ rte->relid = tableOid;
+ rte->relkind = RELKIND_RELATION;
+ rte->inh = false;
+ rte->inFromCl = true;
+ query->rtable = list_make1(rte);
+
+ /* Set up RTE/RelOptInfo arrays */
+ setup_simple_rel_arrays(root);
+
+ /* Build RelOptInfo */
+ rel = build_simple_rel(root, 1, RELOPT_BASEREL);
+
+ /* Locate IndexOptInfo for the target index */
+ indexInfo = NULL;
+ foreach(lc, rel->indexlist)
+ {
+ indexInfo = (IndexOptInfo *) lfirst(lc);
+ if (indexInfo->indexoid == indexOid)
+ break;
+ }
+
+ /*
+ * It's possible that get_relation_info did not generate an IndexOptInfo
+ * for the desired index; this could happen if it's not yet reached its
+ * indcheckxmin usability horizon, or if it's a system index and we're
+ * ignoring system indexes. In such cases we should tell CLUSTER to not
+ * trust the index contents but use seqscan-and-sort.
+ */
+ if (lc == NULL) /* not in the list? */
+ return true; /* use sort */
+
+ /*
+ * Rather than doing all the pushups that would be needed to use
+ * set_baserel_size_estimates, just do a quick hack for rows and width.
+ */
+ rel->rows = rel->tuples;
+ rel->width = get_relation_data_width(tableOid, NULL);
+
+ root->total_table_pages = rel->pages;
+
+ /*
+ * Determine eval cost of the index expressions, if any. We need to
+ * charge twice that amount for each tuple comparison that happens during
+ * the sort, since tuplesort.c will have to re-evaluate the index
+ * expressions each time. (XXX that's pretty inefficient...)
+ */
+ cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
+ comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
+
+ /* Estimate the cost of seq scan + sort */
+ seqScanPath = create_seqscan_path(root, rel, NULL);
+ cost_sort(&seqScanAndSortPath, root, NIL,
+ seqScanPath->total_cost, rel->tuples, rel->width,
+ comparisonCost, maintenance_work_mem, -1.0);
+
+ /* Estimate the cost of index scan */
+ indexScanPath = create_index_path(root, indexInfo,
+ NIL, NIL, NIL, NIL, NIL,
+ ForwardScanDirection, false,
+ NULL, 1.0);
+
+ return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
+}