PostgreSQL Source Code  git master
costsize.c File Reference
#include "postgres.h"
#include <limits.h>
#include <math.h>
#include "access/amapi.h"
#include "access/htup_details.h"
#include "access/tsmapi.h"
#include "executor/executor.h"
#include "executor/nodeAgg.h"
#include "executor/nodeHash.h"
#include "executor/nodeMemoize.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/placeholder.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "parser/parsetree.h"
#include "utils/lsyscache.h"
#include "utils/selfuncs.h"
#include "utils/spccache.h"
#include "utils/tuplesort.h"
Include dependency graph for costsize.c:

Go to the source code of this file.

Data Structures

struct  cost_qual_eval_context
 

Macros

#define LOG2(x)   (log(x) / 0.693147180559945)
 
#define APPEND_CPU_COST_MULTIPLIER   0.5
 
#define MAXIMUM_ROWCOUNT   1e100
 

Functions

static Listextract_nonindex_conditions (List *qual_clauses, List *indexclauses)
 
static MergeScanSelCachecached_scansel (PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
 
static void cost_rescan (PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
 
static bool cost_qual_eval_walker (Node *node, cost_qual_eval_context *context)
 
static void get_restriction_qual_cost (PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
 
static bool has_indexed_join_quals (NestPath *path)
 
static double approx_tuple_count (PlannerInfo *root, JoinPath *path, List *quals)
 
static double calc_joinrel_size_estimate (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, double outer_rows, double inner_rows, SpecialJoinInfo *sjinfo, List *restrictlist)
 
static Selectivity get_foreign_key_join_selectivity (PlannerInfo *root, Relids outer_relids, Relids inner_relids, SpecialJoinInfo *sjinfo, List **restrictlist)
 
static Cost append_nonpartial_cost (List *subpaths, int numpaths, int parallel_workers)
 
static void set_rel_width (PlannerInfo *root, RelOptInfo *rel)
 
static double relation_byte_size (double tuples, int width)
 
static double page_size (double tuples, int width)
 
static double get_parallel_divisor (Path *path)
 
double clamp_row_est (double nrows)
 
long clamp_cardinality_to_long (Cardinality x)
 
void cost_seqscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_samplescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_gather (GatherPath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, double *rows)
 
void cost_gather_merge (GatherMergePath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, Cost input_startup_cost, Cost input_total_cost, double *rows)
 
void cost_index (IndexPath *path, PlannerInfo *root, double loop_count, bool partial_path)
 
double index_pages_fetched (double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
 
static double get_indexpath_pages (Path *bitmapqual)
 
void cost_bitmap_heap_scan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, Path *bitmapqual, double loop_count)
 
void cost_bitmap_tree_node (Path *path, Cost *cost, Selectivity *selec)
 
void cost_bitmap_and_node (BitmapAndPath *path, PlannerInfo *root)
 
void cost_bitmap_or_node (BitmapOrPath *path, PlannerInfo *root)
 
void cost_tidscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
 
void cost_tidrangescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidrangequals, ParamPathInfo *param_info)
 
void cost_subqueryscan (SubqueryScanPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, bool trivial_pathtarget)
 
void cost_functionscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_tablefuncscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_valuesscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_ctescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_namedtuplestorescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_resultscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_recursive_union (Path *runion, Path *nrterm, Path *rterm)
 
static void cost_tuplesort (Cost *startup_cost, Cost *run_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_incremental_sort (Path *path, PlannerInfo *root, List *pathkeys, int presorted_keys, Cost input_startup_cost, Cost input_total_cost, double input_tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_sort (Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_append (AppendPath *apath)
 
void cost_merge_append (Path *path, PlannerInfo *root, List *pathkeys, int n_streams, Cost input_startup_cost, Cost input_total_cost, double tuples)
 
void cost_material (Path *path, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
 
static void cost_memoize_rescan (PlannerInfo *root, MemoizePath *mpath, Cost *rescan_startup_cost, Cost *rescan_total_cost)
 
void cost_agg (Path *path, PlannerInfo *root, AggStrategy aggstrategy, const AggClauseCosts *aggcosts, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples, double input_width)
 
void cost_windowagg (Path *path, PlannerInfo *root, List *windowFuncs, int numPartCols, int numOrderCols, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_group (Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void initial_cost_nestloop (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, Path *outer_path, Path *inner_path, JoinPathExtraData *extra)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, JoinPathExtraData *extra)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, JoinPathExtraData *extra, bool parallel_hash)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void cost_subplan (PlannerInfo *root, SubPlan *subplan, Plan *plan)
 
void cost_qual_eval (QualCost *cost, List *quals, PlannerInfo *root)
 
void cost_qual_eval_node (QualCost *cost, Node *qual, PlannerInfo *root)
 
void compute_semi_anti_join_factors (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, SpecialJoinInfo *sjinfo, List *restrictlist, SemiAntiJoinFactors *semifactors)
 
void set_baserel_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
double get_parameterized_baserel_size (PlannerInfo *root, RelOptInfo *rel, List *param_clauses)
 
void set_joinrel_size_estimates (PlannerInfo *root, RelOptInfo *rel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo, List *restrictlist)
 
double get_parameterized_joinrel_size (PlannerInfo *root, RelOptInfo *rel, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, List *restrict_clauses)
 
void set_subquery_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_function_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_tablefunc_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_values_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_cte_size_estimates (PlannerInfo *root, RelOptInfo *rel, double cte_rows)
 
void set_namedtuplestore_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_result_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_foreign_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
PathTargetset_pathtarget_cost_width (PlannerInfo *root, PathTarget *target)
 
double compute_bitmap_pages (PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
 

Variables

double seq_page_cost = DEFAULT_SEQ_PAGE_COST
 
double random_page_cost = DEFAULT_RANDOM_PAGE_COST
 
double cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST
 
double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST
 
double cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST
 
double parallel_tuple_cost = DEFAULT_PARALLEL_TUPLE_COST
 
double parallel_setup_cost = DEFAULT_PARALLEL_SETUP_COST
 
double recursive_worktable_factor = DEFAULT_RECURSIVE_WORKTABLE_FACTOR
 
int effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE
 
Cost disable_cost = 1.0e10
 
int max_parallel_workers_per_gather = 2
 
bool enable_seqscan = true
 
bool enable_indexscan = true
 
bool enable_indexonlyscan = true
 
bool enable_bitmapscan = true
 
bool enable_tidscan = true
 
bool enable_sort = true
 
bool enable_incremental_sort = true
 
bool enable_hashagg = true
 
bool enable_nestloop = true
 
bool enable_material = true
 
bool enable_memoize = true
 
bool enable_mergejoin = true
 
bool enable_hashjoin = true
 
bool enable_gathermerge = true
 
bool enable_partitionwise_join = false
 
bool enable_partitionwise_aggregate = false
 
bool enable_parallel_append = true
 
bool enable_parallel_hash = true
 
bool enable_partition_pruning = true
 
bool enable_async_append = true
 

Macro Definition Documentation

◆ APPEND_CPU_COST_MULTIPLIER

#define APPEND_CPU_COST_MULTIPLIER   0.5

Definition at line 110 of file costsize.c.

◆ LOG2

#define LOG2 (   x)    (log(x) / 0.693147180559945)

Definition at line 103 of file costsize.c.

◆ MAXIMUM_ROWCOUNT

#define MAXIMUM_ROWCOUNT   1e100

Definition at line 118 of file costsize.c.

Function Documentation

◆ append_nonpartial_cost()

static Cost append_nonpartial_cost ( List subpaths,
int  numpaths,
int  parallel_workers 
)
static

Definition at line 2127 of file costsize.c.

2128 {
2129  Cost *costarr;
2130  int arrlen;
2131  ListCell *l;
2132  ListCell *cell;
2133  int path_index;
2134  int min_index;
2135  int max_index;
2136 
2137  if (numpaths == 0)
2138  return 0;
2139 
2140  /*
2141  * Array length is number of workers or number of relevant paths,
2142  * whichever is less.
2143  */
2144  arrlen = Min(parallel_workers, numpaths);
2145  costarr = (Cost *) palloc(sizeof(Cost) * arrlen);
2146 
2147  /* The first few paths will each be claimed by a different worker. */
2148  path_index = 0;
2149  foreach(cell, subpaths)
2150  {
2151  Path *subpath = (Path *) lfirst(cell);
2152 
2153  if (path_index == arrlen)
2154  break;
2155  costarr[path_index++] = subpath->total_cost;
2156  }
2157 
2158  /*
2159  * Since subpaths are sorted by decreasing cost, the last one will have
2160  * the minimum cost.
2161  */
2162  min_index = arrlen - 1;
2163 
2164  /*
2165  * For each of the remaining subpaths, add its cost to the array element
2166  * with minimum cost.
2167  */
2168  for_each_cell(l, subpaths, cell)
2169  {
2170  Path *subpath = (Path *) lfirst(l);
2171 
2172  /* Consider only the non-partial paths */
2173  if (path_index++ == numpaths)
2174  break;
2175 
2176  costarr[min_index] += subpath->total_cost;
2177 
2178  /* Update the new min cost array index */
2179  min_index = 0;
2180  for (int i = 0; i < arrlen; i++)
2181  {
2182  if (costarr[i] < costarr[min_index])
2183  min_index = i;
2184  }
2185  }
2186 
2187  /* Return the highest cost from the array */
2188  max_index = 0;
2189  for (int i = 0; i < arrlen; i++)
2190  {
2191  if (costarr[i] > costarr[max_index])
2192  max_index = i;
2193  }
2194 
2195  return costarr[max_index];
2196 }
#define Min(x, y)
Definition: c.h:937
int i
Definition: isn.c:73
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
void * palloc(Size size)
Definition: mcxt.c:1199
double Cost
Definition: nodes.h:251
#define lfirst(lc)
Definition: pg_list.h:170
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:436

References for_each_cell, i, lfirst, Min, palloc(), and subpath().

Referenced by cost_append().

◆ approx_tuple_count()

static double approx_tuple_count ( PlannerInfo root,
JoinPath path,
List quals 
)
static

Definition at line 4932 of file costsize.c.

4933 {
4934  double tuples;
4935  double outer_tuples = path->outerjoinpath->rows;
4936  double inner_tuples = path->innerjoinpath->rows;
4937  SpecialJoinInfo sjinfo;
4938  Selectivity selec = 1.0;
4939  ListCell *l;
4940 
4941  /*
4942  * Make up a SpecialJoinInfo for JOIN_INNER semantics.
4943  */
4944  sjinfo.type = T_SpecialJoinInfo;
4945  sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
4946  sjinfo.min_righthand = path->innerjoinpath->parent->relids;
4947  sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
4948  sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
4949  sjinfo.jointype = JOIN_INNER;
4950  /* we don't bother trying to make the remaining fields valid */
4951  sjinfo.lhs_strict = false;
4952  sjinfo.delay_upper_joins = false;
4953  sjinfo.semi_can_btree = false;
4954  sjinfo.semi_can_hash = false;
4955  sjinfo.semi_operators = NIL;
4956  sjinfo.semi_rhs_exprs = NIL;
4957 
4958  /* Get the approximate selectivity */
4959  foreach(l, quals)
4960  {
4961  Node *qual = (Node *) lfirst(l);
4962 
4963  /* Note that clause_selectivity will be able to cache its result */
4964  selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
4965  }
4966 
4967  /* Apply it to the input relation sizes */
4968  tuples = selec * outer_tuples * inner_tuples;
4969 
4970  return clamp_row_est(tuples);
4971 }
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:690
double clamp_row_est(double nrows)
Definition: costsize.c:201
double Selectivity
Definition: nodes.h:250
@ JOIN_INNER
Definition: nodes.h:293
#define NIL
Definition: pg_list.h:66
Path * outerjoinpath
Definition: pathnodes.h:1948
Path * innerjoinpath
Definition: pathnodes.h:1949
Definition: nodes.h:118
Cardinality rows
Definition: pathnodes.h:1544
Relids syn_lefthand
Definition: pathnodes.h:2702
Relids min_righthand
Definition: pathnodes.h:2701
List * semi_rhs_exprs
Definition: pathnodes.h:2711
JoinType jointype
Definition: pathnodes.h:2704
Relids min_lefthand
Definition: pathnodes.h:2700
Relids syn_righthand
Definition: pathnodes.h:2703
List * semi_operators
Definition: pathnodes.h:2710
bool delay_upper_joins
Definition: pathnodes.h:2706

References clamp_row_est(), clause_selectivity(), SpecialJoinInfo::delay_upper_joins, JoinPath::innerjoinpath, JOIN_INNER, SpecialJoinInfo::jointype, lfirst, SpecialJoinInfo::lhs_strict, SpecialJoinInfo::min_lefthand, SpecialJoinInfo::min_righthand, NIL, JoinPath::outerjoinpath, Path::rows, SpecialJoinInfo::semi_can_btree, SpecialJoinInfo::semi_can_hash, SpecialJoinInfo::semi_operators, SpecialJoinInfo::semi_rhs_exprs, SpecialJoinInfo::syn_lefthand, and SpecialJoinInfo::syn_righthand.

Referenced by final_cost_hashjoin(), and final_cost_mergejoin().

◆ cached_scansel()

static MergeScanSelCache * cached_scansel ( PlannerInfo root,
RestrictInfo rinfo,
PathKey pathkey 
)
static

Definition at line 3722 of file costsize.c.

3723 {
3724  MergeScanSelCache *cache;
3725  ListCell *lc;
3726  Selectivity leftstartsel,
3727  leftendsel,
3728  rightstartsel,
3729  rightendsel;
3730  MemoryContext oldcontext;
3731 
3732  /* Do we have this result already? */
3733  foreach(lc, rinfo->scansel_cache)
3734  {
3735  cache = (MergeScanSelCache *) lfirst(lc);
3736  if (cache->opfamily == pathkey->pk_opfamily &&
3737  cache->collation == pathkey->pk_eclass->ec_collation &&
3738  cache->strategy == pathkey->pk_strategy &&
3739  cache->nulls_first == pathkey->pk_nulls_first)
3740  return cache;
3741  }
3742 
3743  /* Nope, do the computation */
3744  mergejoinscansel(root,
3745  (Node *) rinfo->clause,
3746  pathkey->pk_opfamily,
3747  pathkey->pk_strategy,
3748  pathkey->pk_nulls_first,
3749  &leftstartsel,
3750  &leftendsel,
3751  &rightstartsel,
3752  &rightendsel);
3753 
3754  /* Cache the result in suitably long-lived workspace */
3755  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
3756 
3757  cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
3758  cache->opfamily = pathkey->pk_opfamily;
3759  cache->collation = pathkey->pk_eclass->ec_collation;
3760  cache->strategy = pathkey->pk_strategy;
3761  cache->nulls_first = pathkey->pk_nulls_first;
3762  cache->leftstartsel = leftstartsel;
3763  cache->leftendsel = leftendsel;
3764  cache->rightstartsel = rightstartsel;
3765  cache->rightendsel = rightendsel;
3766 
3767  rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
3768 
3769  MemoryContextSwitchTo(oldcontext);
3770 
3771  return cache;
3772 }
List * lappend(List *list, void *datum)
Definition: list.c:338
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
void mergejoinscansel(PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
Definition: selfuncs.c:2921
Selectivity leftstartsel
Definition: pathnodes.h:2585
Selectivity leftendsel
Definition: pathnodes.h:2586
Selectivity rightendsel
Definition: pathnodes.h:2588
Selectivity rightstartsel
Definition: pathnodes.h:2587
bool pk_nulls_first
Definition: pathnodes.h:1379
int pk_strategy
Definition: pathnodes.h:1378
Oid pk_opfamily
Definition: pathnodes.h:1377
Expr * clause
Definition: pathnodes.h:2432

References RestrictInfo::clause, MergeScanSelCache::collation, lappend(), MergeScanSelCache::leftendsel, MergeScanSelCache::leftstartsel, lfirst, MemoryContextSwitchTo(), mergejoinscansel(), MergeScanSelCache::nulls_first, MergeScanSelCache::opfamily, palloc(), PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, MergeScanSelCache::rightendsel, MergeScanSelCache::rightstartsel, and MergeScanSelCache::strategy.

Referenced by initial_cost_mergejoin().

◆ calc_joinrel_size_estimate()

static double calc_joinrel_size_estimate ( PlannerInfo root,
RelOptInfo joinrel,
RelOptInfo outer_rel,
RelOptInfo inner_rel,
double  outer_rows,
double  inner_rows,
SpecialJoinInfo sjinfo,
List restrictlist 
)
static

Definition at line 5140 of file costsize.c.

5148 {
5149  JoinType jointype = sjinfo->jointype;
5150  Selectivity fkselec;
5151  Selectivity jselec;
5152  Selectivity pselec;
5153  double nrows;
5154 
5155  /*
5156  * Compute joinclause selectivity. Note that we are only considering
5157  * clauses that become restriction clauses at this join level; we are not
5158  * double-counting them because they were not considered in estimating the
5159  * sizes of the component rels.
5160  *
5161  * First, see whether any of the joinclauses can be matched to known FK
5162  * constraints. If so, drop those clauses from the restrictlist, and
5163  * instead estimate their selectivity using FK semantics. (We do this
5164  * without regard to whether said clauses are local or "pushed down".
5165  * Probably, an FK-matching clause could never be seen as pushed down at
5166  * an outer join, since it would be strict and hence would be grounds for
5167  * join strength reduction.) fkselec gets the net selectivity for
5168  * FK-matching clauses, or 1.0 if there are none.
5169  */
5170  fkselec = get_foreign_key_join_selectivity(root,
5171  outer_rel->relids,
5172  inner_rel->relids,
5173  sjinfo,
5174  &restrictlist);
5175 
5176  /*
5177  * For an outer join, we have to distinguish the selectivity of the join's
5178  * own clauses (JOIN/ON conditions) from any clauses that were "pushed
5179  * down". For inner joins we just count them all as joinclauses.
5180  */
5181  if (IS_OUTER_JOIN(jointype))
5182  {
5183  List *joinquals = NIL;
5184  List *pushedquals = NIL;
5185  ListCell *l;
5186 
5187  /* Grovel through the clauses to separate into two lists */
5188  foreach(l, restrictlist)
5189  {
5190  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5191 
5192  if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5193  pushedquals = lappend(pushedquals, rinfo);
5194  else
5195  joinquals = lappend(joinquals, rinfo);
5196  }
5197 
5198  /* Get the separate selectivities */
5199  jselec = clauselist_selectivity(root,
5200  joinquals,
5201  0,
5202  jointype,
5203  sjinfo);
5204  pselec = clauselist_selectivity(root,
5205  pushedquals,
5206  0,
5207  jointype,
5208  sjinfo);
5209 
5210  /* Avoid leaking a lot of ListCells */
5211  list_free(joinquals);
5212  list_free(pushedquals);
5213  }
5214  else
5215  {
5216  jselec = clauselist_selectivity(root,
5217  restrictlist,
5218  0,
5219  jointype,
5220  sjinfo);
5221  pselec = 0.0; /* not used, keep compiler quiet */
5222  }
5223 
5224  /*
5225  * Basically, we multiply size of Cartesian product by selectivity.
5226  *
5227  * If we are doing an outer join, take that into account: the joinqual
5228  * selectivity has to be clamped using the knowledge that the output must
5229  * be at least as large as the non-nullable input. However, any
5230  * pushed-down quals are applied after the outer join, so their
5231  * selectivity applies fully.
5232  *
5233  * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
5234  * of LHS rows that have matches, and we apply that straightforwardly.
5235  */
5236  switch (jointype)
5237  {
5238  case JOIN_INNER:
5239  nrows = outer_rows * inner_rows * fkselec * jselec;
5240  /* pselec not used */
5241  break;
5242  case JOIN_LEFT:
5243  nrows = outer_rows * inner_rows * fkselec * jselec;
5244  if (nrows < outer_rows)
5245  nrows = outer_rows;
5246  nrows *= pselec;
5247  break;
5248  case JOIN_FULL:
5249  nrows = outer_rows * inner_rows * fkselec * jselec;
5250  if (nrows < outer_rows)
5251  nrows = outer_rows;
5252  if (nrows < inner_rows)
5253  nrows = inner_rows;
5254  nrows *= pselec;
5255  break;
5256  case JOIN_SEMI:
5257  nrows = outer_rows * fkselec * jselec;
5258  /* pselec not used */
5259  break;
5260  case JOIN_ANTI:
5261  nrows = outer_rows * (1.0 - fkselec * jselec);
5262  nrows *= pselec;
5263  break;
5264  default:
5265  /* other values not expected here */
5266  elog(ERROR, "unrecognized join type: %d", (int) jointype);
5267  nrows = 0; /* keep compiler quiet */
5268  break;
5269  }
5270 
5271  return clamp_row_est(nrows);
5272 }
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
static Selectivity get_foreign_key_join_selectivity(PlannerInfo *root, Relids outer_relids, Relids inner_relids, SpecialJoinInfo *sjinfo, List **restrictlist)
Definition: costsize.c:5290
#define ERROR
Definition: elog.h:35
void list_free(List *list)
Definition: list.c:1545
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:336
JoinType
Definition: nodes.h:288
@ JOIN_SEMI
Definition: nodes.h:307
@ JOIN_FULL
Definition: nodes.h:295
@ JOIN_LEFT
Definition: nodes.h:294
@ JOIN_ANTI
Definition: nodes.h:308
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2566
#define lfirst_node(type, lc)
Definition: pg_list.h:174
Definition: pg_list.h:52
Relids relids
Definition: pathnodes.h:821

References clamp_row_est(), clauselist_selectivity(), elog(), ERROR, get_foreign_key_join_selectivity(), IS_OUTER_JOIN, JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_SEMI, SpecialJoinInfo::jointype, lappend(), lfirst_node, list_free(), NIL, RelOptInfo::relids, and RINFO_IS_PUSHED_DOWN.

Referenced by get_parameterized_joinrel_size(), and set_joinrel_size_estimates().

◆ clamp_cardinality_to_long()

long clamp_cardinality_to_long ( Cardinality  x)

Definition at line 224 of file costsize.c.

225 {
226  /*
227  * Just for paranoia's sake, ensure we do something sane with negative or
228  * NaN values.
229  */
230  if (isnan(x))
231  return LONG_MAX;
232  if (x <= 0)
233  return 0;
234 
235  /*
236  * If "long" is 64 bits, then LONG_MAX cannot be represented exactly as a
237  * double. Casting it to double and back may well result in overflow due
238  * to rounding, so avoid doing that. We trust that any double value that
239  * compares strictly less than "(double) LONG_MAX" will cast to a
240  * representable "long" value.
241  */
242  return (x < (double) LONG_MAX) ? (long) x : LONG_MAX;
243 }
int x
Definition: isn.c:71

References x.

Referenced by buildSubPlanHash(), create_recursiveunion_plan(), create_setop_plan(), and make_agg().

◆ clamp_row_est()

double clamp_row_est ( double  nrows)

Definition at line 201 of file costsize.c.

202 {
203  /*
204  * Avoid infinite and NaN row estimates. Costs derived from such values
205  * are going to be useless. Also force the estimate to be at least one
206  * row, to make explain output look better and to avoid possible
207  * divide-by-zero when interpolating costs. Make it an integer, too.
208  */
209  if (nrows > MAXIMUM_ROWCOUNT || isnan(nrows))
210  nrows = MAXIMUM_ROWCOUNT;
211  else if (nrows <= 1.0)
212  nrows = 1.0;
213  else
214  nrows = rint(nrows);
215 
216  return nrows;
217 }
#define MAXIMUM_ROWCOUNT
Definition: costsize.c:118

References MAXIMUM_ROWCOUNT.

Referenced by adjust_limit_rows_costs(), approx_tuple_count(), bernoulli_samplescangetsamplesize(), calc_joinrel_size_estimate(), compute_bitmap_pages(), cost_agg(), cost_append(), cost_bitmap_heap_scan(), cost_group(), cost_index(), cost_seqscan(), cost_subplan(), cost_subqueryscan(), create_bitmap_subplan(), estimate_hash_bucket_stats(), estimate_num_groups(), estimate_path_cost_size(), estimate_size(), expression_returns_set_rows(), final_cost_hashjoin(), final_cost_mergejoin(), final_cost_nestloop(), get_parameterized_baserel_size(), get_variable_numdistinct(), initial_cost_mergejoin(), set_baserel_size_estimates(), set_cte_size_estimates(), set_foreign_size(), system_rows_samplescangetsamplesize(), system_samplescangetsamplesize(), and system_time_samplescangetsamplesize().

◆ compute_bitmap_pages()

double compute_bitmap_pages ( PlannerInfo root,
RelOptInfo baserel,
Path bitmapqual,
int  loop_count,
Cost cost,
double *  tuple 
)

Definition at line 6139 of file costsize.c.

6141 {
6142  Cost indexTotalCost;
6143  Selectivity indexSelectivity;
6144  double T;
6145  double pages_fetched;
6146  double tuples_fetched;
6147  double heap_pages;
6148  long maxentries;
6149 
6150  /*
6151  * Fetch total cost of obtaining the bitmap, as well as its total
6152  * selectivity.
6153  */
6154  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6155 
6156  /*
6157  * Estimate number of main-table pages fetched.
6158  */
6159  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6160 
6161  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
6162 
6163  /*
6164  * For a single scan, the number of heap pages that need to be fetched is
6165  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
6166  * re-reads needed).
6167  */
6168  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
6169 
6170  /*
6171  * Calculate the number of pages fetched from the heap. Then based on
6172  * current work_mem estimate get the estimated maxentries in the bitmap.
6173  * (Note that we always do this calculation based on the number of pages
6174  * that would be fetched in a single iteration, even if loop_count > 1.
6175  * That's correct, because only that number of entries will be stored in
6176  * the bitmap at one time.)
6177  */
6178  heap_pages = Min(pages_fetched, baserel->pages);
6179  maxentries = tbm_calculate_entries(work_mem * 1024L);
6180 
6181  if (loop_count > 1)
6182  {
6183  /*
6184  * For repeated bitmap scans, scale up the number of tuples fetched in
6185  * the Mackert and Lohman formula by the number of scans, so that we
6186  * estimate the number of pages fetched by all the scans. Then
6187  * pro-rate for one scan.
6188  */
6189  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6190  baserel->pages,
6191  get_indexpath_pages(bitmapqual),
6192  root);
6193  pages_fetched /= loop_count;
6194  }
6195 
6196  if (pages_fetched >= T)
6197  pages_fetched = T;
6198  else
6199  pages_fetched = ceil(pages_fetched);
6200 
6201  if (maxentries < heap_pages)
6202  {
6203  double exact_pages;
6204  double lossy_pages;
6205 
6206  /*
6207  * Crude approximation of the number of lossy pages. Because of the
6208  * way tbm_lossify() is coded, the number of lossy pages increases
6209  * very sharply as soon as we run short of memory; this formula has
6210  * that property and seems to perform adequately in testing, but it's
6211  * possible we could do better somehow.
6212  */
6213  lossy_pages = Max(0, heap_pages - maxentries / 2);
6214  exact_pages = heap_pages - lossy_pages;
6215 
6216  /*
6217  * If there are lossy pages then recompute the number of tuples
6218  * processed by the bitmap heap node. We assume here that the chance
6219  * of a given tuple coming from an exact page is the same as the
6220  * chance that a given page is exact. This might not be true, but
6221  * it's not clear how we can do any better.
6222  */
6223  if (lossy_pages > 0)
6224  tuples_fetched =
6225  clamp_row_est(indexSelectivity *
6226  (exact_pages / heap_pages) * baserel->tuples +
6227  (lossy_pages / heap_pages) * baserel->tuples);
6228  }
6229 
6230  if (cost)
6231  *cost = indexTotalCost;
6232  if (tuple)
6233  *tuple = tuples_fetched;
6234 
6235  return pages_fetched;
6236 }
#define Max(x, y)
Definition: c.h:931
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:868
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1084
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:933
int work_mem
Definition: globals.c:125
static const uint32 T[65]
Definition: md5.c:119
Cardinality tuples
Definition: pathnodes.h:891
BlockNumber pages
Definition: pathnodes.h:890
long tbm_calculate_entries(double maxbytes)
Definition: tidbitmap.c:1545

References clamp_row_est(), cost_bitmap_tree_node(), get_indexpath_pages(), index_pages_fetched(), Max, Min, RelOptInfo::pages, T, tbm_calculate_entries(), RelOptInfo::tuples, and work_mem.

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

◆ compute_semi_anti_join_factors()

void compute_semi_anti_join_factors ( PlannerInfo root,
RelOptInfo joinrel,
RelOptInfo outerrel,
RelOptInfo innerrel,
JoinType  jointype,
SpecialJoinInfo sjinfo,
List restrictlist,
SemiAntiJoinFactors semifactors 
)

Definition at line 4730 of file costsize.c.

4738 {
4739  Selectivity jselec;
4740  Selectivity nselec;
4741  Selectivity avgmatch;
4742  SpecialJoinInfo norm_sjinfo;
4743  List *joinquals;
4744  ListCell *l;
4745 
4746  /*
4747  * In an ANTI join, we must ignore clauses that are "pushed down", since
4748  * those won't affect the match logic. In a SEMI join, we do not
4749  * distinguish joinquals from "pushed down" quals, so just use the whole
4750  * restrictinfo list. For other outer join types, we should consider only
4751  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
4752  */
4753  if (IS_OUTER_JOIN(jointype))
4754  {
4755  joinquals = NIL;
4756  foreach(l, restrictlist)
4757  {
4758  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4759 
4760  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
4761  joinquals = lappend(joinquals, rinfo);
4762  }
4763  }
4764  else
4765  joinquals = restrictlist;
4766 
4767  /*
4768  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
4769  */
4770  jselec = clauselist_selectivity(root,
4771  joinquals,
4772  0,
4773  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
4774  sjinfo);
4775 
4776  /*
4777  * Also get the normal inner-join selectivity of the join clauses.
4778  */
4779  norm_sjinfo.type = T_SpecialJoinInfo;
4780  norm_sjinfo.min_lefthand = outerrel->relids;
4781  norm_sjinfo.min_righthand = innerrel->relids;
4782  norm_sjinfo.syn_lefthand = outerrel->relids;
4783  norm_sjinfo.syn_righthand = innerrel->relids;
4784  norm_sjinfo.jointype = JOIN_INNER;
4785  /* we don't bother trying to make the remaining fields valid */
4786  norm_sjinfo.lhs_strict = false;
4787  norm_sjinfo.delay_upper_joins = false;
4788  norm_sjinfo.semi_can_btree = false;
4789  norm_sjinfo.semi_can_hash = false;
4790  norm_sjinfo.semi_operators = NIL;
4791  norm_sjinfo.semi_rhs_exprs = NIL;
4792 
4793  nselec = clauselist_selectivity(root,
4794  joinquals,
4795  0,
4796  JOIN_INNER,
4797  &norm_sjinfo);
4798 
4799  /* Avoid leaking a lot of ListCells */
4800  if (IS_OUTER_JOIN(jointype))
4801  list_free(joinquals);
4802 
4803  /*
4804  * jselec can be interpreted as the fraction of outer-rel rows that have
4805  * any matches (this is true for both SEMI and ANTI cases). And nselec is
4806  * the fraction of the Cartesian product that matches. So, the average
4807  * number of matches for each outer-rel row that has at least one match is
4808  * nselec * inner_rows / jselec.
4809  *
4810  * Note: it is correct to use the inner rel's "rows" count here, even
4811  * though we might later be considering a parameterized inner path with
4812  * fewer rows. This is because we have included all the join clauses in
4813  * the selectivity estimate.
4814  */
4815  if (jselec > 0) /* protect against zero divide */
4816  {
4817  avgmatch = nselec * innerrel->rows / jselec;
4818  /* Clamp to sane range */
4819  avgmatch = Max(1.0, avgmatch);
4820  }
4821  else
4822  avgmatch = 1.0;
4823 
4824  semifactors->outer_match_frac = jselec;
4825  semifactors->match_count = avgmatch;
4826 }
Cardinality rows
Definition: pathnodes.h:827
Selectivity outer_match_frac
Definition: pathnodes.h:2996
Selectivity match_count
Definition: pathnodes.h:2997

References clauselist_selectivity(), SpecialJoinInfo::delay_upper_joins, IS_OUTER_JOIN, JOIN_ANTI, JOIN_INNER, JOIN_SEMI, SpecialJoinInfo::jointype, lappend(), lfirst_node, SpecialJoinInfo::lhs_strict, list_free(), SemiAntiJoinFactors::match_count, Max, SpecialJoinInfo::min_lefthand, SpecialJoinInfo::min_righthand, NIL, SemiAntiJoinFactors::outer_match_frac, RelOptInfo::relids, RINFO_IS_PUSHED_DOWN, RelOptInfo::rows, SpecialJoinInfo::semi_can_btree, SpecialJoinInfo::semi_can_hash, SpecialJoinInfo::semi_operators, SpecialJoinInfo::semi_rhs_exprs, SpecialJoinInfo::syn_lefthand, and SpecialJoinInfo::syn_righthand.

Referenced by add_paths_to_joinrel().

◆ cost_agg()

void cost_agg ( Path path,
PlannerInfo root,
AggStrategy  aggstrategy,
const AggClauseCosts aggcosts,
int  numGroupCols,
double  numGroups,
List quals,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples,
double  input_width 
)

Definition at line 2620 of file costsize.c.

2626 {
2627  double output_tuples;
2628  Cost startup_cost;
2629  Cost total_cost;
2630  AggClauseCosts dummy_aggcosts;
2631 
2632  /* Use all-zero per-aggregate costs if NULL is passed */
2633  if (aggcosts == NULL)
2634  {
2635  Assert(aggstrategy == AGG_HASHED);
2636  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
2637  aggcosts = &dummy_aggcosts;
2638  }
2639 
2640  /*
2641  * The transCost.per_tuple component of aggcosts should be charged once
2642  * per input tuple, corresponding to the costs of evaluating the aggregate
2643  * transfns and their input expressions. The finalCost.per_tuple component
2644  * is charged once per output tuple, corresponding to the costs of
2645  * evaluating the finalfns. Startup costs are of course charged but once.
2646  *
2647  * If we are grouping, we charge an additional cpu_operator_cost per
2648  * grouping column per input tuple for grouping comparisons.
2649  *
2650  * We will produce a single output tuple if not grouping, and a tuple per
2651  * group otherwise. We charge cpu_tuple_cost for each output tuple.
2652  *
2653  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2654  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2655  * input path is already sorted appropriately, AGG_SORTED should be
2656  * preferred (since it has no risk of memory overflow). This will happen
2657  * as long as the computed total costs are indeed exactly equal --- but if
2658  * there's roundoff error we might do the wrong thing. So be sure that
2659  * the computations below form the same intermediate values in the same
2660  * order.
2661  */
2662  if (aggstrategy == AGG_PLAIN)
2663  {
2664  startup_cost = input_total_cost;
2665  startup_cost += aggcosts->transCost.startup;
2666  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2667  startup_cost += aggcosts->finalCost.startup;
2668  startup_cost += aggcosts->finalCost.per_tuple;
2669  /* we aren't grouping */
2670  total_cost = startup_cost + cpu_tuple_cost;
2671  output_tuples = 1;
2672  }
2673  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2674  {
2675  /* Here we are able to deliver output on-the-fly */
2676  startup_cost = input_startup_cost;
2677  total_cost = input_total_cost;
2678  if (aggstrategy == AGG_MIXED && !enable_hashagg)
2679  {
2680  startup_cost += disable_cost;
2681  total_cost += disable_cost;
2682  }
2683  /* calcs phrased this way to match HASHED case, see note above */
2684  total_cost += aggcosts->transCost.startup;
2685  total_cost += aggcosts->transCost.per_tuple * input_tuples;
2686  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2687  total_cost += aggcosts->finalCost.startup;
2688  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2689  total_cost += cpu_tuple_cost * numGroups;
2690  output_tuples = numGroups;
2691  }
2692  else
2693  {
2694  /* must be AGG_HASHED */
2695  startup_cost = input_total_cost;
2696  if (!enable_hashagg)
2697  startup_cost += disable_cost;
2698  startup_cost += aggcosts->transCost.startup;
2699  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2700  /* cost of computing hash value */
2701  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2702  startup_cost += aggcosts->finalCost.startup;
2703 
2704  total_cost = startup_cost;
2705  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2706  /* cost of retrieving from hash table */
2707  total_cost += cpu_tuple_cost * numGroups;
2708  output_tuples = numGroups;
2709  }
2710 
2711  /*
2712  * Add the disk costs of hash aggregation that spills to disk.
2713  *
2714  * Groups that go into the hash table stay in memory until finalized, so
2715  * spilling and reprocessing tuples doesn't incur additional invocations
2716  * of transCost or finalCost. Furthermore, the computed hash value is
2717  * stored with the spilled tuples, so we don't incur extra invocations of
2718  * the hash function.
2719  *
2720  * Hash Agg begins returning tuples after the first batch is complete.
2721  * Accrue writes (spilled tuples) to startup_cost and to total_cost;
2722  * accrue reads only to total_cost.
2723  */
2724  if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
2725  {
2726  double pages;
2727  double pages_written = 0.0;
2728  double pages_read = 0.0;
2729  double spill_cost;
2730  double hashentrysize;
2731  double nbatches;
2732  Size mem_limit;
2733  uint64 ngroups_limit;
2734  int num_partitions;
2735  int depth;
2736 
2737  /*
2738  * Estimate number of batches based on the computed limits. If less
2739  * than or equal to one, all groups are expected to fit in memory;
2740  * otherwise we expect to spill.
2741  */
2742  hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
2743  input_width,
2744  aggcosts->transitionSpace);
2745  hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
2746  &ngroups_limit, &num_partitions);
2747 
2748  nbatches = Max((numGroups * hashentrysize) / mem_limit,
2749  numGroups / ngroups_limit);
2750 
2751  nbatches = Max(ceil(nbatches), 1.0);
2752  num_partitions = Max(num_partitions, 2);
2753 
2754  /*
2755  * The number of partitions can change at different levels of
2756  * recursion; but for the purposes of this calculation assume it stays
2757  * constant.
2758  */
2759  depth = ceil(log(nbatches) / log(num_partitions));
2760 
2761  /*
2762  * Estimate number of pages read and written. For each level of
2763  * recursion, a tuple must be written and then later read.
2764  */
2765  pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
2766  pages_written = pages_read = pages * depth;
2767 
2768  /*
2769  * HashAgg has somewhat worse IO behavior than Sort on typical
2770  * hardware/OS combinations. Account for this with a generic penalty.
2771  */
2772  pages_read *= 2.0;
2773  pages_written *= 2.0;
2774 
2775  startup_cost += pages_written * random_page_cost;
2776  total_cost += pages_written * random_page_cost;
2777  total_cost += pages_read * seq_page_cost;
2778 
2779  /* account for CPU cost of spilling a tuple and reading it back */
2780  spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
2781  startup_cost += spill_cost;
2782  total_cost += spill_cost;
2783  }
2784 
2785  /*
2786  * If there are quals (HAVING quals), account for their cost and
2787  * selectivity.
2788  */
2789  if (quals)
2790  {
2791  QualCost qual_cost;
2792 
2793  cost_qual_eval(&qual_cost, quals, root);
2794  startup_cost += qual_cost.startup;
2795  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2796 
2797  output_tuples = clamp_row_est(output_tuples *
2799  quals,
2800  0,
2801  JOIN_INNER,
2802  NULL));
2803  }
2804 
2805  path->rows = output_tuples;
2806  path->startup_cost = startup_cost;
2807  path->total_cost = total_cost;
2808 }
#define MemSet(start, val, len)
Definition: c.h:953
size_t Size
Definition: c.h:541
double random_page_cost
Definition: costsize.c:121
double cpu_operator_cost
Definition: costsize.c:124
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:6085
double cpu_tuple_cost
Definition: costsize.c:122
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4368
double seq_page_cost
Definition: costsize.c:120
bool enable_hashagg
Definition: costsize.c:142
Cost disable_cost
Definition: costsize.c:131
Assert(fmt[strlen(fmt) - 1] !='\n')
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1686
void hash_agg_set_limits(double hashentrysize, double input_groups, int used_bits, Size *mem_limit, uint64 *ngroups_limit, int *num_partitions)
Definition: nodeAgg.c:1790
@ AGG_SORTED
Definition: nodes.h:352
@ AGG_HASHED
Definition: nodes.h:353
@ AGG_MIXED
Definition: nodes.h:354
@ AGG_PLAIN
Definition: nodes.h:351
static int list_length(const List *l)
Definition: pg_list.h:150
QualCost finalCost
Definition: pathnodes.h:61
Size transitionSpace
Definition: pathnodes.h:62
QualCost transCost
Definition: pathnodes.h:60
Cost startup_cost
Definition: pathnodes.h:1545
Cost total_cost
Definition: pathnodes.h:1546
List * aggtransinfos
Definition: pathnodes.h:471
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47

References AGG_HASHED, AGG_MIXED, AGG_PLAIN, AGG_SORTED, PlannerInfo::aggtransinfos, Assert(), clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, disable_cost, enable_hashagg, AggClauseCosts::finalCost, hash_agg_entry_size(), hash_agg_set_limits(), JOIN_INNER, list_length(), Max, MemSet, QualCost::per_tuple, random_page_cost, relation_byte_size(), Path::rows, seq_page_cost, QualCost::startup, Path::startup_cost, Path::total_cost, AggClauseCosts::transCost, and AggClauseCosts::transitionSpace.

Referenced by choose_hashed_setop(), create_agg_path(), create_groupingsets_path(), and create_unique_path().

◆ cost_append()

void cost_append ( AppendPath apath)

Definition at line 2203 of file costsize.c.

2204 {
2205  ListCell *l;
2206 
2207  apath->path.startup_cost = 0;
2208  apath->path.total_cost = 0;
2209  apath->path.rows = 0;
2210 
2211  if (apath->subpaths == NIL)
2212  return;
2213 
2214  if (!apath->path.parallel_aware)
2215  {
2216  List *pathkeys = apath->path.pathkeys;
2217 
2218  if (pathkeys == NIL)
2219  {
2220  Path *firstsubpath = (Path *) linitial(apath->subpaths);
2221 
2222  /*
2223  * For an unordered, non-parallel-aware Append we take the startup
2224  * cost as the startup cost of the first subpath.
2225  */
2226  apath->path.startup_cost = firstsubpath->startup_cost;
2227 
2228  /* Compute rows and costs as sums of subplan rows and costs. */
2229  foreach(l, apath->subpaths)
2230  {
2231  Path *subpath = (Path *) lfirst(l);
2232 
2233  apath->path.rows += subpath->rows;
2234  apath->path.total_cost += subpath->total_cost;
2235  }
2236  }
2237  else
2238  {
2239  /*
2240  * For an ordered, non-parallel-aware Append we take the startup
2241  * cost as the sum of the subpath startup costs. This ensures
2242  * that we don't underestimate the startup cost when a query's
2243  * LIMIT is such that several of the children have to be run to
2244  * satisfy it. This might be overkill --- another plausible hack
2245  * would be to take the Append's startup cost as the maximum of
2246  * the child startup costs. But we don't want to risk believing
2247  * that an ORDER BY LIMIT query can be satisfied at small cost
2248  * when the first child has small startup cost but later ones
2249  * don't. (If we had the ability to deal with nonlinear cost
2250  * interpolation for partial retrievals, we would not need to be
2251  * so conservative about this.)
2252  *
2253  * This case is also different from the above in that we have to
2254  * account for possibly injecting sorts into subpaths that aren't
2255  * natively ordered.
2256  */
2257  foreach(l, apath->subpaths)
2258  {
2259  Path *subpath = (Path *) lfirst(l);
2260  Path sort_path; /* dummy for result of cost_sort */
2261 
2262  if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
2263  {
2264  /*
2265  * We'll need to insert a Sort node, so include costs for
2266  * that. We can use the parent's LIMIT if any, since we
2267  * certainly won't pull more than that many tuples from
2268  * any child.
2269  */
2270  cost_sort(&sort_path,
2271  NULL, /* doesn't currently need root */
2272  pathkeys,
2273  subpath->total_cost,
2274  subpath->rows,
2275  subpath->pathtarget->width,
2276  0.0,
2277  work_mem,
2278  apath->limit_tuples);
2279  subpath = &sort_path;
2280  }
2281 
2282  apath->path.rows += subpath->rows;
2283  apath->path.startup_cost += subpath->startup_cost;
2284  apath->path.total_cost += subpath->total_cost;
2285  }
2286  }
2287  }
2288  else /* parallel-aware */
2289  {
2290  int i = 0;
2291  double parallel_divisor = get_parallel_divisor(&apath->path);
2292 
2293  /* Parallel-aware Append never produces ordered output. */
2294  Assert(apath->path.pathkeys == NIL);
2295 
2296  /* Calculate startup cost. */
2297  foreach(l, apath->subpaths)
2298  {
2299  Path *subpath = (Path *) lfirst(l);
2300 
2301  /*
2302  * Append will start returning tuples when the child node having
2303  * lowest startup cost is done setting up. We consider only the
2304  * first few subplans that immediately get a worker assigned.
2305  */
2306  if (i == 0)
2307  apath->path.startup_cost = subpath->startup_cost;
2308  else if (i < apath->path.parallel_workers)
2309  apath->path.startup_cost = Min(apath->path.startup_cost,
2310  subpath->startup_cost);
2311 
2312  /*
2313  * Apply parallel divisor to subpaths. Scale the number of rows
2314  * for each partial subpath based on the ratio of the parallel
2315  * divisor originally used for the subpath to the one we adopted.
2316  * Also add the cost of partial paths to the total cost, but
2317  * ignore non-partial paths for now.
2318  */
2319  if (i < apath->first_partial_path)
2320  apath->path.rows += subpath->rows / parallel_divisor;
2321  else
2322  {
2323  double subpath_parallel_divisor;
2324 
2325  subpath_parallel_divisor = get_parallel_divisor(subpath);
2326  apath->path.rows += subpath->rows * (subpath_parallel_divisor /
2327  parallel_divisor);
2328  apath->path.total_cost += subpath->total_cost;
2329  }
2330 
2331  apath->path.rows = clamp_row_est(apath->path.rows);
2332 
2333  i++;
2334  }
2335 
2336  /* Add cost for non-partial subpaths. */
2337  apath->path.total_cost +=
2339  apath->first_partial_path,
2340  apath->path.parallel_workers);
2341  }
2342 
2343  /*
2344  * Although Append does not do any selection or projection, it's not free;
2345  * add a small per-tuple overhead.
2346  */
2347  apath->path.total_cost +=
2349 }
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:110
static Cost append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
Definition: costsize.c:2127
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6106
void cost_sort(Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:2096
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:346
#define linitial(l)
Definition: pg_list.h:176
int first_partial_path
Definition: pathnodes.h:1808
Cardinality limit_tuples
Definition: pathnodes.h:1809
List * subpaths
Definition: pathnodes.h:1806
List * pathkeys
Definition: pathnodes.h:1549
int parallel_workers
Definition: pathnodes.h:1541
bool parallel_aware
Definition: pathnodes.h:1537

References APPEND_CPU_COST_MULTIPLIER, append_nonpartial_cost(), Assert(), clamp_row_est(), cost_sort(), cpu_tuple_cost, AppendPath::first_partial_path, get_parallel_divisor(), i, lfirst, AppendPath::limit_tuples, linitial, Min, NIL, Path::parallel_aware, Path::parallel_workers, AppendPath::path, Path::pathkeys, pathkeys_contained_in(), Path::rows, Path::startup_cost, subpath(), AppendPath::subpaths, Path::total_cost, and work_mem.

Referenced by create_append_path().

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1127 of file costsize.c.

1128 {
1129  Cost totalCost;
1130  Selectivity selec;
1131  ListCell *l;
1132 
1133  /*
1134  * We estimate AND selectivity on the assumption that the inputs are
1135  * independent. This is probably often wrong, but we don't have the info
1136  * to do better.
1137  *
1138  * The runtime cost of the BitmapAnd itself is estimated at 100x
1139  * cpu_operator_cost for each tbm_intersect needed. Probably too small,
1140  * definitely too simplistic?
1141  */
1142  totalCost = 0.0;
1143  selec = 1.0;
1144  foreach(l, path->bitmapquals)
1145  {
1146  Path *subpath = (Path *) lfirst(l);
1147  Cost subCost;
1148  Selectivity subselec;
1149 
1150  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1151 
1152  selec *= subselec;
1153 
1154  totalCost += subCost;
1155  if (l != list_head(path->bitmapquals))
1156  totalCost += 100.0 * cpu_operator_cost;
1157  }
1158  path->bitmapselectivity = selec;
1159  path->path.rows = 0; /* per above, not used */
1160  path->path.startup_cost = totalCost;
1161  path->path.total_cost = totalCost;
1162 }
static ListCell * list_head(const List *l)
Definition: pg_list.h:126
Selectivity bitmapselectivity
Definition: pathnodes.h:1685
List * bitmapquals
Definition: pathnodes.h:1684

References BitmapAndPath::bitmapquals, BitmapAndPath::bitmapselectivity, cost_bitmap_tree_node(), cpu_operator_cost, lfirst, list_head(), BitmapAndPath::path, Path::rows, Path::startup_cost, subpath(), and Path::total_cost.

Referenced by create_bitmap_and_path().

◆ cost_bitmap_heap_scan()

void cost_bitmap_heap_scan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info,
Path bitmapqual,
double  loop_count 
)

Definition at line 983 of file costsize.c.

986 {
987  Cost startup_cost = 0;
988  Cost run_cost = 0;
989  Cost indexTotalCost;
990  QualCost qpqual_cost;
991  Cost cpu_per_tuple;
992  Cost cost_per_page;
993  Cost cpu_run_cost;
994  double tuples_fetched;
995  double pages_fetched;
996  double spc_seq_page_cost,
997  spc_random_page_cost;
998  double T;
999 
1000  /* Should only be applied to base relations */
1001  Assert(IsA(baserel, RelOptInfo));
1002  Assert(baserel->relid > 0);
1003  Assert(baserel->rtekind == RTE_RELATION);
1004 
1005  /* Mark the path with the correct row estimate */
1006  if (param_info)
1007  path->rows = param_info->ppi_rows;
1008  else
1009  path->rows = baserel->rows;
1010 
1011  if (!enable_bitmapscan)
1012  startup_cost += disable_cost;
1013 
1014  pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
1015  loop_count, &indexTotalCost,
1016  &tuples_fetched);
1017 
1018  startup_cost += indexTotalCost;
1019  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
1020 
1021  /* Fetch estimated page costs for tablespace containing table. */
1023  &spc_random_page_cost,
1024  &spc_seq_page_cost);
1025 
1026  /*
1027  * For small numbers of pages we should charge spc_random_page_cost
1028  * apiece, while if nearly all the table's pages are being read, it's more
1029  * appropriate to charge spc_seq_page_cost apiece. The effect is
1030  * nonlinear, too. For lack of a better idea, interpolate like this to
1031  * determine the cost per page.
1032  */
1033  if (pages_fetched >= 2.0)
1034  cost_per_page = spc_random_page_cost -
1035  (spc_random_page_cost - spc_seq_page_cost)
1036  * sqrt(pages_fetched / T);
1037  else
1038  cost_per_page = spc_random_page_cost;
1039 
1040  run_cost += pages_fetched * cost_per_page;
1041 
1042  /*
1043  * Estimate CPU costs per tuple.
1044  *
1045  * Often the indexquals don't need to be rechecked at each tuple ... but
1046  * not always, especially not if there are enough tuples involved that the
1047  * bitmaps become lossy. For the moment, just assume they will be
1048  * rechecked always. This means we charge the full freight for all the
1049  * scan clauses.
1050  */
1051  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1052 
1053  startup_cost += qpqual_cost.startup;
1054  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1055  cpu_run_cost = cpu_per_tuple * tuples_fetched;
1056 
1057  /* Adjust costing for parallelism, if used. */
1058  if (path->parallel_workers > 0)
1059  {
1060  double parallel_divisor = get_parallel_divisor(path);
1061 
1062  /* The CPU cost is divided among all the workers. */
1063  cpu_run_cost /= parallel_divisor;
1064 
1065  path->rows = clamp_row_est(path->rows / parallel_divisor);
1066  }
1067 
1068 
1069  run_cost += cpu_run_cost;
1070 
1071  /* tlist eval costs are paid per output row, not per tuple scanned */
1072  startup_cost += path->pathtarget->cost.startup;
1073  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1074 
1075  path->startup_cost = startup_cost;
1076  path->total_cost = startup_cost + run_cost;
1077 }
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4688
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
Definition: costsize.c:6139
bool enable_bitmapscan
Definition: costsize.c:138
#define IsA(nodeptr, _type_)
Definition: nodes.h:168
@ RTE_RELATION
Definition: parsenodes.h:1011
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:181
Cardinality ppi_rows
Definition: pathnodes.h:1465
Index relid
Definition: pathnodes.h:868
Oid reltablespace
Definition: pathnodes.h:870
RTEKind rtekind
Definition: pathnodes.h:872

References Assert(), clamp_row_est(), compute_bitmap_pages(), cpu_tuple_cost, disable_cost, enable_bitmapscan, get_parallel_divisor(), get_restriction_qual_cost(), get_tablespace_page_costs(), IsA, RelOptInfo::pages, Path::parallel_workers, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, T, and Path::total_cost.

Referenced by bitmap_scan_cost_est(), and create_bitmap_heap_path().

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1171 of file costsize.c.

1172 {
1173  Cost totalCost;
1174  Selectivity selec;
1175  ListCell *l;
1176 
1177  /*
1178  * We estimate OR selectivity on the assumption that the inputs are
1179  * non-overlapping, since that's often the case in "x IN (list)" type
1180  * situations. Of course, we clamp to 1.0 at the end.
1181  *
1182  * The runtime cost of the BitmapOr itself is estimated at 100x
1183  * cpu_operator_cost for each tbm_union needed. Probably too small,
1184  * definitely too simplistic? We are aware that the tbm_unions are
1185  * optimized out when the inputs are BitmapIndexScans.
1186  */
1187  totalCost = 0.0;
1188  selec = 0.0;
1189  foreach(l, path->bitmapquals)
1190  {
1191  Path *subpath = (Path *) lfirst(l);
1192  Cost subCost;
1193  Selectivity subselec;
1194 
1195  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1196 
1197  selec += subselec;
1198 
1199  totalCost += subCost;
1200  if (l != list_head(path->bitmapquals) &&
1201  !IsA(subpath, IndexPath))
1202  totalCost += 100.0 * cpu_operator_cost;
1203  }
1204  path->bitmapselectivity = Min(selec, 1.0);
1205  path->path.rows = 0; /* per above, not used */
1206  path->path.startup_cost = totalCost;
1207  path->path.total_cost = totalCost;
1208 }
Selectivity bitmapselectivity
Definition: pathnodes.h:1698
List * bitmapquals
Definition: pathnodes.h:1697

References BitmapOrPath::bitmapquals, BitmapOrPath::bitmapselectivity, cost_bitmap_tree_node(), cpu_operator_cost, IsA, lfirst, list_head(), Min, BitmapOrPath::path, Path::rows, Path::startup_cost, subpath(), and Path::total_cost.

Referenced by create_bitmap_or_path().

◆ cost_bitmap_tree_node()

void cost_bitmap_tree_node ( Path path,
Cost cost,
Selectivity selec 
)

Definition at line 1084 of file costsize.c.

1085 {
1086  if (IsA(path, IndexPath))
1087  {
1088  *cost = ((IndexPath *) path)->indextotalcost;
1089  *selec = ((IndexPath *) path)->indexselectivity;
1090 
1091  /*
1092  * Charge a small amount per retrieved tuple to reflect the costs of
1093  * manipulating the bitmap. This is mostly to make sure that a bitmap
1094  * scan doesn't look to be the same cost as an indexscan to retrieve a
1095  * single tuple.
1096  */
1097  *cost += 0.1 * cpu_operator_cost * path->rows;
1098  }
1099  else if (IsA(path, BitmapAndPath))
1100  {
1101  *cost = path->total_cost;
1102  *selec = ((BitmapAndPath *) path)->bitmapselectivity;
1103  }
1104  else if (IsA(path, BitmapOrPath))
1105  {
1106  *cost = path->total_cost;
1107  *selec = ((BitmapOrPath *) path)->bitmapselectivity;
1108  }
1109  else
1110  {
1111  elog(ERROR, "unrecognized node type: %d", nodeTag(path));
1112  *cost = *selec = 0; /* keep compiler quiet */
1113  }
1114 }
#define nodeTag(nodeptr)
Definition: nodes.h:122

References cpu_operator_cost, elog(), ERROR, IsA, nodeTag, Path::rows, and Path::total_cost.

Referenced by choose_bitmap_and(), compute_bitmap_pages(), cost_bitmap_and_node(), cost_bitmap_or_node(), and path_usage_comparator().

◆ cost_ctescan()

void cost_ctescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1668 of file costsize.c.

1670 {
1671  Cost startup_cost = 0;
1672  Cost run_cost = 0;
1673  QualCost qpqual_cost;
1674  Cost cpu_per_tuple;
1675 
1676  /* Should only be applied to base relations that are CTEs */
1677  Assert(baserel->relid > 0);
1678  Assert(baserel->rtekind == RTE_CTE);
1679 
1680  /* Mark the path with the correct row estimate */
1681  if (param_info)
1682  path->rows = param_info->ppi_rows;
1683  else
1684  path->rows = baserel->rows;
1685 
1686  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1687  cpu_per_tuple = cpu_tuple_cost;
1688 
1689  /* Add scanning CPU costs */
1690  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1691 
1692  startup_cost += qpqual_cost.startup;
1693  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1694  run_cost += cpu_per_tuple * baserel->tuples;
1695 
1696  /* tlist eval costs are paid per output row, not per tuple scanned */
1697  startup_cost += path->pathtarget->cost.startup;
1698  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1699 
1700  path->startup_cost = startup_cost;
1701  path->total_cost = startup_cost + run_cost;
1702 }
@ RTE_CTE
Definition: parsenodes.h:1017

References Assert(), cpu_tuple_cost, get_restriction_qual_cost(), QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::rows, Path::rows, RTE_CTE, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_ctescan_path(), and create_worktablescan_path().

◆ cost_functionscan()

void cost_functionscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1501 of file costsize.c.

1503 {
1504  Cost startup_cost = 0;
1505  Cost run_cost = 0;
1506  QualCost qpqual_cost;
1507  Cost cpu_per_tuple;
1508  RangeTblEntry *rte;
1509  QualCost exprcost;
1510 
1511  /* Should only be applied to base relations that are functions */
1512  Assert(baserel->relid > 0);
1513  rte = planner_rt_fetch(baserel->relid, root);
1514  Assert(rte->rtekind == RTE_FUNCTION);
1515 
1516  /* Mark the path with the correct row estimate */
1517  if (param_info)
1518  path->rows = param_info->ppi_rows;
1519  else
1520  path->rows = baserel->rows;
1521 
1522  /*
1523  * Estimate costs of executing the function expression(s).
1524  *
1525  * Currently, nodeFunctionscan.c always executes the functions to
1526  * completion before returning any rows, and caches the results in a
1527  * tuplestore. So the function eval cost is all startup cost, and per-row
1528  * costs are minimal.
1529  *
1530  * XXX in principle we ought to charge tuplestore spill costs if the
1531  * number of rows is large. However, given how phony our rowcount
1532  * estimates for functions tend to be, there's not a lot of point in that
1533  * refinement right now.
1534  */
1535  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1536 
1537  startup_cost += exprcost.startup + exprcost.per_tuple;
1538 
1539  /* Add scanning CPU costs */
1540  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1541 
1542  startup_cost += qpqual_cost.startup;
1543  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1544  run_cost += cpu_per_tuple * baserel->tuples;
1545 
1546  /* tlist eval costs are paid per output row, not per tuple scanned */
1547  startup_cost += path->pathtarget->cost.startup;
1548  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1549 
1550  path->startup_cost = startup_cost;
1551  path->total_cost = startup_cost + run_cost;
1552 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4394
@ RTE_FUNCTION
Definition: parsenodes.h:1014
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:520
List * functions
Definition: parsenodes.h:1124
RTEKind rtekind
Definition: parsenodes.h:1030

References Assert(), cost_qual_eval_node(), cpu_tuple_cost, RangeTblEntry::functions, get_restriction_qual_cost(), QualCost::per_tuple, planner_rt_fetch, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::rows, Path::rows, RTE_FUNCTION, RangeTblEntry::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_functionscan_path().

◆ cost_gather()

void cost_gather ( GatherPath path,
PlannerInfo root,
RelOptInfo rel,
ParamPathInfo param_info,
double *  rows 
)

Definition at line 406 of file costsize.c.

409 {
410  Cost startup_cost = 0;
411  Cost run_cost = 0;
412 
413  /* Mark the path with the correct row estimate */
414  if (rows)
415  path->path.rows = *rows;
416  else if (param_info)
417  path->path.rows = param_info->ppi_rows;
418  else
419  path->path.rows = rel->rows;
420 
421  startup_cost = path->subpath->startup_cost;
422 
423  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
424 
425  /* Parallel setup and communication cost. */
426  startup_cost += parallel_setup_cost;
427  run_cost += parallel_tuple_cost * path->path.rows;
428 
429  path->path.startup_cost = startup_cost;
430  path->path.total_cost = (startup_cost + run_cost);
431 }
double parallel_setup_cost
Definition: costsize.c:126
double parallel_tuple_cost
Definition: costsize.c:125
Path * subpath
Definition: pathnodes.h:1916

References parallel_setup_cost, parallel_tuple_cost, GatherPath::path, ParamPathInfo::ppi_rows, RelOptInfo::rows, Path::rows, Path::startup_cost, GatherPath::subpath, and Path::total_cost.

Referenced by create_gather_path().

◆ cost_gather_merge()

void cost_gather_merge ( GatherMergePath path,
PlannerInfo root,
RelOptInfo rel,
ParamPathInfo param_info,
Cost  input_startup_cost,
Cost  input_total_cost,
double *  rows 
)

Definition at line 444 of file costsize.c.

448 {
449  Cost startup_cost = 0;
450  Cost run_cost = 0;
451  Cost comparison_cost;
452  double N;
453  double logN;
454 
455  /* Mark the path with the correct row estimate */
456  if (rows)
457  path->path.rows = *rows;
458  else if (param_info)
459  path->path.rows = param_info->ppi_rows;
460  else
461  path->path.rows = rel->rows;
462 
463  if (!enable_gathermerge)
464  startup_cost += disable_cost;
465 
466  /*
467  * Add one to the number of workers to account for the leader. This might
468  * be overgenerous since the leader will do less work than other workers
469  * in typical cases, but we'll go with it for now.
470  */
471  Assert(path->num_workers > 0);
472  N = (double) path->num_workers + 1;
473  logN = LOG2(N);
474 
475  /* Assumed cost per tuple comparison */
476  comparison_cost = 2.0 * cpu_operator_cost;
477 
478  /* Heap creation cost */
479  startup_cost += comparison_cost * N * logN;
480 
481  /* Per-tuple heap maintenance cost */
482  run_cost += path->path.rows * comparison_cost * logN;
483 
484  /* small cost for heap management, like cost_merge_append */
485  run_cost += cpu_operator_cost * path->path.rows;
486 
487  /*
488  * Parallel setup and communication cost. Since Gather Merge, unlike
489  * Gather, requires us to block until a tuple is available from every
490  * worker, we bump the IPC cost up a little bit as compared with Gather.
491  * For lack of a better idea, charge an extra 5%.
492  */
493  startup_cost += parallel_setup_cost;
494  run_cost += parallel_tuple_cost * path->path.rows * 1.05;
495 
496  path->path.startup_cost = startup_cost + input_startup_cost;
497  path->path.total_cost = (startup_cost + run_cost + input_total_cost);
498 }
#define LOG2(x)
Definition: costsize.c:103
bool enable_gathermerge
Definition: costsize.c:148

References Assert(), cpu_operator_cost, disable_cost, enable_gathermerge, LOG2, GatherMergePath::num_workers, parallel_setup_cost, parallel_tuple_cost, GatherMergePath::path, ParamPathInfo::ppi_rows, RelOptInfo::rows, Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by create_gather_merge_path().

◆ cost_group()

void cost_group ( Path path,
PlannerInfo root,
int  numGroupCols,
double  numGroups,
List quals,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples 
)

Definition at line 2892 of file costsize.c.

2897 {
2898  double output_tuples;
2899  Cost startup_cost;
2900  Cost total_cost;
2901 
2902  output_tuples = numGroups;
2903  startup_cost = input_startup_cost;
2904  total_cost = input_total_cost;
2905 
2906  /*
2907  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2908  * all columns get compared at most of the tuples.
2909  */
2910  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2911 
2912  /*
2913  * If there are quals (HAVING quals), account for their cost and
2914  * selectivity.
2915  */
2916  if (quals)
2917  {
2918  QualCost qual_cost;
2919 
2920  cost_qual_eval(&qual_cost, quals, root);
2921  startup_cost += qual_cost.startup;
2922  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2923 
2924  output_tuples = clamp_row_est(output_tuples *
2926  quals,
2927  0,
2928  JOIN_INNER,
2929  NULL));
2930  }
2931 
2932  path->rows = output_tuples;
2933  path->startup_cost = startup_cost;
2934  path->total_cost = total_cost;
2935 }

References clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_operator_cost, JOIN_INNER, QualCost::per_tuple, Path::rows, QualCost::startup, Path::startup_cost, and Path::total_cost.

Referenced by choose_hashed_setop(), and create_group_path().

◆ cost_incremental_sort()

void cost_incremental_sort ( Path path,
PlannerInfo root,
List pathkeys,
int  presorted_keys,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples,
int  width,
Cost  comparison_cost,
int  sort_mem,
double  limit_tuples 
)

Definition at line 1956 of file costsize.c.

1961 {
1962  Cost startup_cost = 0,
1963  run_cost = 0,
1964  input_run_cost = input_total_cost - input_startup_cost;
1965  double group_tuples,
1966  input_groups;
1967  Cost group_startup_cost,
1968  group_run_cost,
1969  group_input_run_cost;
1970  List *presortedExprs = NIL;
1971  ListCell *l;
1972  int i = 0;
1973  bool unknown_varno = false;
1974 
1975  Assert(presorted_keys != 0);
1976 
1977  /*
1978  * We want to be sure the cost of a sort is never estimated as zero, even
1979  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1980  */
1981  if (input_tuples < 2.0)
1982  input_tuples = 2.0;
1983 
1984  /* Default estimate of number of groups, capped to one group per row. */
1985  input_groups = Min(input_tuples, DEFAULT_NUM_DISTINCT);
1986 
1987  /*
1988  * Extract presorted keys as list of expressions.
1989  *
1990  * We need to be careful about Vars containing "varno 0" which might have
1991  * been introduced by generate_append_tlist, which would confuse
1992  * estimate_num_groups (in fact it'd fail for such expressions). See
1993  * recurse_set_operations which has to deal with the same issue.
1994  *
1995  * Unlike recurse_set_operations we can't access the original target list
1996  * here, and even if we could it's not very clear how useful would that be
1997  * for a set operation combining multiple tables. So we simply detect if
1998  * there are any expressions with "varno 0" and use the default
1999  * DEFAULT_NUM_DISTINCT in that case.
2000  *
2001  * We might also use either 1.0 (a single group) or input_tuples (each row
2002  * being a separate group), pretty much the worst and best case for
2003  * incremental sort. But those are extreme cases and using something in
2004  * between seems reasonable. Furthermore, generate_append_tlist is used
2005  * for set operations, which are likely to produce mostly unique output
2006  * anyway - from that standpoint the DEFAULT_NUM_DISTINCT is defensive
2007  * while maintaining lower startup cost.
2008  */
2009  foreach(l, pathkeys)
2010  {
2011  PathKey *key = (PathKey *) lfirst(l);
2012  EquivalenceMember *member = (EquivalenceMember *)
2013  linitial(key->pk_eclass->ec_members);
2014 
2015  /*
2016  * Check if the expression contains Var with "varno 0" so that we
2017  * don't call estimate_num_groups in that case.
2018  */
2019  if (bms_is_member(0, pull_varnos(root, (Node *) member->em_expr)))
2020  {
2021  unknown_varno = true;
2022  break;
2023  }
2024 
2025  /* expression not containing any Vars with "varno 0" */
2026  presortedExprs = lappend(presortedExprs, member->em_expr);
2027 
2028  i++;
2029  if (i >= presorted_keys)
2030  break;
2031  }
2032 
2033  /* Estimate number of groups with equal presorted keys. */
2034  if (!unknown_varno)
2035  input_groups = estimate_num_groups(root, presortedExprs, input_tuples,
2036  NULL, NULL);
2037 
2038  group_tuples = input_tuples / input_groups;
2039  group_input_run_cost = input_run_cost / input_groups;
2040 
2041  /*
2042  * Estimate average cost of sorting of one group where presorted keys are
2043  * equal. Incremental sort is sensitive to distribution of tuples to the
2044  * groups, where we're relying on quite rough assumptions. Thus, we're
2045  * pessimistic about incremental sort performance and increase its average
2046  * group size by half.
2047  */
2048  cost_tuplesort(&group_startup_cost, &group_run_cost,
2049  1.5 * group_tuples, width, comparison_cost, sort_mem,
2050  limit_tuples);
2051 
2052  /*
2053  * Startup cost of incremental sort is the startup cost of its first group
2054  * plus the cost of its input.
2055  */
2056  startup_cost += group_startup_cost
2057  + input_startup_cost + group_input_run_cost;
2058 
2059  /*
2060  * After we started producing tuples from the first group, the cost of
2061  * producing all the tuples is given by the cost to finish processing this
2062  * group, plus the total cost to process the remaining groups, plus the
2063  * remaining cost of input.
2064  */
2065  run_cost += group_run_cost
2066  + (group_run_cost + group_startup_cost) * (input_groups - 1)
2067  + group_input_run_cost * (input_groups - 1);
2068 
2069  /*
2070  * Incremental sort adds some overhead by itself. Firstly, it has to
2071  * detect the sort groups. This is roughly equal to one extra copy and
2072  * comparison per tuple. Secondly, it has to reset the tuplesort context
2073  * for every group.
2074  */
2075  run_cost += (cpu_tuple_cost + comparison_cost) * input_tuples;
2076  run_cost += 2.0 * cpu_tuple_cost * input_groups;
2077 
2078  path->rows = input_tuples;
2079  path->startup_cost = startup_cost;
2080  path->total_cost = startup_cost + run_cost;
2081 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:428
static void cost_tuplesort(Cost *startup_cost, Cost *run_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:1854
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition: selfuncs.c:3385
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:52
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:100

References Assert(), bms_is_member(), cost_tuplesort(), cpu_tuple_cost, DEFAULT_NUM_DISTINCT, EquivalenceMember::em_expr, estimate_num_groups(), i, sort-test::key, lappend(), lfirst, linitial, Min, NIL, pull_varnos(), Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by create_incremental_sort_path().

◆ cost_index()

void cost_index ( IndexPath path,
PlannerInfo root,
double  loop_count,
bool  partial_path 
)

Definition at line 519 of file costsize.c.

521 {
522  IndexOptInfo *index = path->indexinfo;
523  RelOptInfo *baserel = index->rel;
524  bool indexonly = (path->path.pathtype == T_IndexOnlyScan);
525  amcostestimate_function amcostestimate;
526  List *qpquals;
527  Cost startup_cost = 0;
528  Cost run_cost = 0;
529  Cost cpu_run_cost = 0;
530  Cost indexStartupCost;
531  Cost indexTotalCost;
532  Selectivity indexSelectivity;
533  double indexCorrelation,
534  csquared;
535  double spc_seq_page_cost,
536  spc_random_page_cost;
537  Cost min_IO_cost,
538  max_IO_cost;
539  QualCost qpqual_cost;
540  Cost cpu_per_tuple;
541  double tuples_fetched;
542  double pages_fetched;
543  double rand_heap_pages;
544  double index_pages;
545 
546  /* Should only be applied to base relations */
547  Assert(IsA(baserel, RelOptInfo) &&
549  Assert(baserel->relid > 0);
550  Assert(baserel->rtekind == RTE_RELATION);
551 
552  /*
553  * Mark the path with the correct row estimate, and identify which quals
554  * will need to be enforced as qpquals. We need not check any quals that
555  * are implied by the index's predicate, so we can use indrestrictinfo not
556  * baserestrictinfo as the list of relevant restriction clauses for the
557  * rel.
558  */
559  if (path->path.param_info)
560  {
561  path->path.rows = path->path.param_info->ppi_rows;
562  /* qpquals come from the rel's restriction clauses and ppi_clauses */
564  path->indexclauses),
565  extract_nonindex_conditions(path->path.param_info->ppi_clauses,
566  path->indexclauses));
567  }
568  else
569  {
570  path->path.rows = baserel->rows;
571  /* qpquals come from just the rel's restriction clauses */
573  path->indexclauses);
574  }
575 
576  if (!enable_indexscan)
577  startup_cost += disable_cost;
578  /* we don't need to check enable_indexonlyscan; indxpath.c does that */
579 
580  /*
581  * Call index-access-method-specific code to estimate the processing cost
582  * for scanning the index, as well as the selectivity of the index (ie,
583  * the fraction of main-table tuples we will have to retrieve) and its
584  * correlation to the main-table tuple order. We need a cast here because
585  * pathnodes.h uses a weak function type to avoid including amapi.h.
586  */
587  amcostestimate = (amcostestimate_function) index->amcostestimate;
588  amcostestimate(root, path, loop_count,
589  &indexStartupCost, &indexTotalCost,
590  &indexSelectivity, &indexCorrelation,
591  &index_pages);
592 
593  /*
594  * Save amcostestimate's results for possible use in bitmap scan planning.
595  * We don't bother to save indexStartupCost or indexCorrelation, because a
596  * bitmap scan doesn't care about either.
597  */
598  path->indextotalcost = indexTotalCost;
599  path->indexselectivity = indexSelectivity;
600 
601  /* all costs for touching index itself included here */
602  startup_cost += indexStartupCost;
603  run_cost += indexTotalCost - indexStartupCost;
604 
605  /* estimate number of main-table tuples fetched */
606  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
607 
608  /* fetch estimated page costs for tablespace containing table */
610  &spc_random_page_cost,
611  &spc_seq_page_cost);
612 
613  /*----------
614  * Estimate number of main-table pages fetched, and compute I/O cost.
615  *
616  * When the index ordering is uncorrelated with the table ordering,
617  * we use an approximation proposed by Mackert and Lohman (see
618  * index_pages_fetched() for details) to compute the number of pages
619  * fetched, and then charge spc_random_page_cost per page fetched.
620  *
621  * When the index ordering is exactly correlated with the table ordering
622  * (just after a CLUSTER, for example), the number of pages fetched should
623  * be exactly selectivity * table_size. What's more, all but the first
624  * will be sequential fetches, not the random fetches that occur in the
625  * uncorrelated case. So if the number of pages is more than 1, we
626  * ought to charge
627  * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
628  * For partially-correlated indexes, we ought to charge somewhere between
629  * these two estimates. We currently interpolate linearly between the
630  * estimates based on the correlation squared (XXX is that appropriate?).
631  *
632  * If it's an index-only scan, then we will not need to fetch any heap
633  * pages for which the visibility map shows all tuples are visible.
634  * Hence, reduce the estimated number of heap fetches accordingly.
635  * We use the measured fraction of the entire heap that is all-visible,
636  * which might not be particularly relevant to the subset of the heap
637  * that this query will fetch; but it's not clear how to do better.
638  *----------
639  */
640  if (loop_count > 1)
641  {
642  /*
643  * For repeated indexscans, the appropriate estimate for the
644  * uncorrelated case is to scale up the number of tuples fetched in
645  * the Mackert and Lohman formula by the number of scans, so that we
646  * estimate the number of pages fetched by all the scans; then
647  * pro-rate the costs for one scan. In this case we assume all the
648  * fetches are random accesses.
649  */
650  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
651  baserel->pages,
652  (double) index->pages,
653  root);
654 
655  if (indexonly)
656  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
657 
658  rand_heap_pages = pages_fetched;
659 
660  max_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
661 
662  /*
663  * In the perfectly correlated case, the number of pages touched by
664  * each scan is selectivity * table_size, and we can use the Mackert
665  * and Lohman formula at the page level to estimate how much work is
666  * saved by caching across scans. We still assume all the fetches are
667  * random, though, which is an overestimate that's hard to correct for
668  * without double-counting the cache effects. (But in most cases
669  * where such a plan is actually interesting, only one page would get
670  * fetched per scan anyway, so it shouldn't matter much.)
671  */
672  pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
673 
674  pages_fetched = index_pages_fetched(pages_fetched * loop_count,
675  baserel->pages,
676  (double) index->pages,
677  root);
678 
679  if (indexonly)
680  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
681 
682  min_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
683  }
684  else
685  {
686  /*
687  * Normal case: apply the Mackert and Lohman formula, and then
688  * interpolate between that and the correlation-derived result.
689  */
690  pages_fetched = index_pages_fetched(tuples_fetched,
691  baserel->pages,
692  (double) index->pages,
693  root);
694 
695  if (indexonly)
696  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
697 
698  rand_heap_pages = pages_fetched;
699 
700  /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
701  max_IO_cost = pages_fetched * spc_random_page_cost;
702 
703  /* min_IO_cost is for the perfectly correlated case (csquared=1) */
704  pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
705 
706  if (indexonly)
707  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
708 
709  if (pages_fetched > 0)
710  {
711  min_IO_cost = spc_random_page_cost;
712  if (pages_fetched > 1)
713  min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
714  }
715  else
716  min_IO_cost = 0;
717  }
718 
719  if (partial_path)
720  {
721  /*
722  * For index only scans compute workers based on number of index pages
723  * fetched; the number of heap pages we fetch might be so small as to
724  * effectively rule out parallelism, which we don't want to do.
725  */
726  if (indexonly)
727  rand_heap_pages = -1;
728 
729  /*
730  * Estimate the number of parallel workers required to scan index. Use
731  * the number of heap pages computed considering heap fetches won't be
732  * sequential as for parallel scans the pages are accessed in random
733  * order.
734  */
736  rand_heap_pages,
737  index_pages,
739 
740  /*
741  * Fall out if workers can't be assigned for parallel scan, because in
742  * such a case this path will be rejected. So there is no benefit in
743  * doing extra computation.
744  */
745  if (path->path.parallel_workers <= 0)
746  return;
747 
748  path->path.parallel_aware = true;
749  }
750 
751  /*
752  * Now interpolate based on estimated index order correlation to get total
753  * disk I/O cost for main table accesses.
754  */
755  csquared = indexCorrelation * indexCorrelation;
756 
757  run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
758 
759  /*
760  * Estimate CPU costs per tuple.
761  *
762  * What we want here is cpu_tuple_cost plus the evaluation costs of any
763  * qual clauses that we have to evaluate as qpquals.
764  */
765  cost_qual_eval(&qpqual_cost, qpquals, root);
766 
767  startup_cost += qpqual_cost.startup;
768  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
769 
770  cpu_run_cost += cpu_per_tuple * tuples_fetched;
771 
772  /* tlist eval costs are paid per output row, not per tuple scanned */
773  startup_cost += path->path.pathtarget->cost.startup;
774  cpu_run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
775 
776  /* Adjust costing for parallelism, if used. */
777  if (path->path.parallel_workers > 0)
778  {
779  double parallel_divisor = get_parallel_divisor(&path->path);
780 
781  path->path.rows = clamp_row_est(path->path.rows / parallel_divisor);
782 
783  /* The CPU cost is divided among all the workers. */
784  cpu_run_cost /= parallel_divisor;
785  }
786 
787  run_cost += cpu_run_cost;
788 
789  path->path.startup_cost = startup_cost;
790  path->path.total_cost = startup_cost + run_cost;
791 }
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:4155
void(* amcostestimate_function)(struct PlannerInfo *root, struct IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
Definition: amapi.h:130
int max_parallel_workers_per_gather
Definition: costsize.c:133
static List * extract_nonindex_conditions(List *qual_clauses, List *indexclauses)
Definition: costsize.c:810
bool enable_indexscan
Definition: costsize.c:136
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
List * indrestrictinfo
Definition: pathnodes.h:1126
List * indexclauses
Definition: pathnodes.h:1598
Path path
Definition: pathnodes.h:1596
Selectivity indexselectivity
Definition: pathnodes.h:1603
Cost indextotalcost
Definition: pathnodes.h:1602
IndexOptInfo * indexinfo
Definition: pathnodes.h:1597
NodeTag pathtype
Definition: pathnodes.h:1510
double allvisfrac
Definition: pathnodes.h:892
Definition: type.h:95

References RelOptInfo::allvisfrac, Assert(), clamp_row_est(), compute_parallel_worker(), cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_indexscan, extract_nonindex_conditions(), get_parallel_divisor(), get_tablespace_page_costs(), index_pages_fetched(), IndexPath::indexclauses, IndexPath::indexinfo, IndexPath::indexselectivity, IndexPath::indextotalcost, IndexOptInfo::indrestrictinfo, IsA, list_concat(), max_parallel_workers_per_gather, RelOptInfo::pages, Path::parallel_aware, Path::parallel_workers, IndexPath::path, Path::pathtype, QualCost::per_tuple, RelOptInfo::relid, RelOptInfo::reltablespace, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_index_path(), and reparameterize_path().

◆ cost_material()

void cost_material ( Path path,
Cost  input_startup_cost,
Cost  input_total_cost,
double  tuples,
int  width 
)

Definition at line 2425 of file costsize.c.

2428 {
2429  Cost startup_cost = input_startup_cost;
2430  Cost run_cost = input_total_cost - input_startup_cost;
2431  double nbytes = relation_byte_size(tuples, width);
2432  long work_mem_bytes = work_mem * 1024L;
2433 
2434  path->rows = tuples;
2435 
2436  /*
2437  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2438  * reflect bookkeeping overhead. (This rate must be more than what
2439  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2440  * if it is exactly the same then there will be a cost tie between
2441  * nestloop with A outer, materialized B inner and nestloop with B outer,
2442  * materialized A inner. The extra cost ensures we'll prefer
2443  * materializing the smaller rel.) Note that this is normally a good deal
2444  * less than cpu_tuple_cost; which is OK because a Material plan node
2445  * doesn't do qual-checking or projection, so it's got less overhead than
2446  * most plan nodes.
2447  */
2448  run_cost += 2 * cpu_operator_cost * tuples;
2449 
2450  /*
2451  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2452  * This cost is assumed to be evenly spread through the plan run phase,
2453  * which isn't exactly accurate but our cost model doesn't allow for
2454  * nonuniform costs within the run phase.
2455  */
2456  if (nbytes > work_mem_bytes)
2457  {
2458  double npages = ceil(nbytes / BLCKSZ);
2459 
2460  run_cost += seq_page_cost * npages;
2461  }
2462 
2463  path->startup_cost = startup_cost;
2464  path->total_cost = startup_cost + run_cost;
2465 }

References cpu_operator_cost, relation_byte_size(), Path::rows, seq_page_cost, Path::startup_cost, Path::total_cost, and work_mem.

Referenced by create_material_path(), and materialize_finished_plan().

◆ cost_memoize_rescan()

static void cost_memoize_rescan ( PlannerInfo root,
MemoizePath mpath,
Cost rescan_startup_cost,
Cost rescan_total_cost 
)
static

Definition at line 2481 of file costsize.c.

2483 {
2484  EstimationInfo estinfo;
2485  Cost input_startup_cost = mpath->subpath->startup_cost;
2486  Cost input_total_cost = mpath->subpath->total_cost;
2487  double tuples = mpath->subpath->rows;
2488  double calls = mpath->calls;
2489  int width = mpath->subpath->pathtarget->width;
2490 
2491  double hash_mem_bytes;
2492  double est_entry_bytes;
2493  double est_cache_entries;
2494  double ndistinct;
2495  double evict_ratio;
2496  double hit_ratio;
2497  Cost startup_cost;
2498  Cost total_cost;
2499 
2500  /* available cache space */
2501  hash_mem_bytes = get_hash_memory_limit();
2502 
2503  /*
2504  * Set the number of bytes each cache entry should consume in the cache.
2505  * To provide us with better estimations on how many cache entries we can
2506  * store at once, we make a call to the executor here to ask it what
2507  * memory overheads there are for a single cache entry.
2508  *
2509  * XXX we also store the cache key, but that's not accounted for here.
2510  */
2511  est_entry_bytes = relation_byte_size(tuples, width) +
2513 
2514  /* estimate on the upper limit of cache entries we can hold at once */
2515  est_cache_entries = floor(hash_mem_bytes / est_entry_bytes);
2516 
2517  /* estimate on the distinct number of parameter values */
2518  ndistinct = estimate_num_groups(root, mpath->param_exprs, calls, NULL,
2519  &estinfo);
2520 
2521  /*
2522  * When the estimation fell back on using a default value, it's a bit too
2523  * risky to assume that it's ok to use a Memoize node. The use of a
2524  * default could cause us to use a Memoize node when it's really
2525  * inappropriate to do so. If we see that this has been done, then we'll
2526  * assume that every call will have unique parameters, which will almost
2527  * certainly mean a MemoizePath will never survive add_path().
2528  */
2529  if ((estinfo.flags & SELFLAG_USED_DEFAULT) != 0)
2530  ndistinct = calls;
2531 
2532  /*
2533  * Since we've already estimated the maximum number of entries we can
2534  * store at once and know the estimated number of distinct values we'll be
2535  * called with, we'll take this opportunity to set the path's est_entries.
2536  * This will ultimately determine the hash table size that the executor
2537  * will use. If we leave this at zero, the executor will just choose the
2538  * size itself. Really this is not the right place to do this, but it's
2539  * convenient since everything is already calculated.
2540  */
2541  mpath->est_entries = Min(Min(ndistinct, est_cache_entries),
2542  PG_UINT32_MAX);
2543 
2544  /*
2545  * When the number of distinct parameter values is above the amount we can
2546  * store in the cache, then we'll have to evict some entries from the
2547  * cache. This is not free. Here we estimate how often we'll incur the
2548  * cost of that eviction.
2549  */
2550  evict_ratio = 1.0 - Min(est_cache_entries, ndistinct) / ndistinct;
2551 
2552  /*
2553  * In order to estimate how costly a single scan will be, we need to
2554  * attempt to estimate what the cache hit ratio will be. To do that we
2555  * must look at how many scans are estimated in total for this node and
2556  * how many of those scans we expect to get a cache hit.
2557  */
2558  hit_ratio = 1.0 / ndistinct * Min(est_cache_entries, ndistinct) -
2559  (ndistinct / calls);
2560 
2561  /* Ensure we don't go negative */
2562  hit_ratio = Max(hit_ratio, 0.0);
2563 
2564  /*
2565  * Set the total_cost accounting for the expected cache hit ratio. We
2566  * also add on a cpu_operator_cost to account for a cache lookup. This
2567  * will happen regardless of whether it's a cache hit or not.
2568  */
2569  total_cost = input_total_cost * (1.0 - hit_ratio) + cpu_operator_cost;
2570 
2571  /* Now adjust the total cost to account for cache evictions */
2572 
2573  /* Charge a cpu_tuple_cost for evicting the actual cache entry */
2574  total_cost += cpu_tuple_cost * evict_ratio;
2575 
2576  /*
2577  * Charge a 10th of cpu_operator_cost to evict every tuple in that entry.
2578  * The per-tuple eviction is really just a pfree, so charging a whole
2579  * cpu_operator_cost seems a little excessive.
2580  */
2581  total_cost += cpu_operator_cost / 10.0 * evict_ratio * tuples;
2582 
2583  /*
2584  * Now adjust for storing things in the cache, since that's not free
2585  * either. Everything must go in the cache. We don't proportion this
2586  * over any ratio, just apply it once for the scan. We charge a
2587  * cpu_tuple_cost for the creation of the cache entry and also a
2588  * cpu_operator_cost for each tuple we expect to cache.
2589  */
2590  total_cost += cpu_tuple_cost + cpu_operator_cost * tuples;
2591 
2592  /*
2593  * Getting the first row must be also be proportioned according to the
2594  * expected cache hit ratio.
2595  */
2596  startup_cost = input_startup_cost * (1.0 - hit_ratio);
2597 
2598  /*
2599  * Additionally we charge a cpu_tuple_cost to account for cache lookups,
2600  * which we'll do regardless of whether it was a cache hit or not.
2601  */
2602  startup_cost += cpu_tuple_cost;
2603 
2604  *rescan_startup_cost = startup_cost;
2605  *rescan_total_cost = total_cost;
2606 }
#define PG_UINT32_MAX
Definition: c.h:526
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3390
double ExecEstimateCacheEntryOverheadBytes(double ntuples)
Definition: nodeMemoize.c:1134
#define SELFLAG_USED_DEFAULT
Definition: selfuncs.h:76
uint32 flags
Definition: selfuncs.h:80
uint32 est_entries
Definition: pathnodes.h:1875
Cardinality calls
Definition: pathnodes.h:1874
Path * subpath
Definition: pathnodes.h:1867
List * param_exprs
Definition: pathnodes.h:1869

References MemoizePath::calls, cpu_operator_cost, cpu_tuple_cost, MemoizePath::est_entries, estimate_num_groups(), ExecEstimateCacheEntryOverheadBytes(), EstimationInfo::flags, get_hash_memory_limit(), Max, Min, MemoizePath::param_exprs, PG_UINT32_MAX, relation_byte_size(), Path::rows, SELFLAG_USED_DEFAULT, Path::startup_cost, MemoizePath::subpath, and Path::total_cost.

Referenced by cost_rescan().

◆ cost_merge_append()

void cost_merge_append ( Path path,
PlannerInfo root,
List pathkeys,
int  n_streams,
Cost  input_startup_cost,
Cost  input_total_cost,
double  tuples 
)

Definition at line 2376 of file costsize.c.

2380 {
2381  Cost startup_cost = 0;
2382  Cost run_cost = 0;
2383  Cost comparison_cost;
2384  double N;
2385  double logN;
2386 
2387  /*
2388  * Avoid log(0)...
2389  */
2390  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2391  logN = LOG2(N);
2392 
2393  /* Assumed cost per tuple comparison */
2394  comparison_cost = 2.0 * cpu_operator_cost;
2395 
2396  /* Heap creation cost */
2397  startup_cost += comparison_cost * N * logN;
2398 
2399  /* Per-tuple heap maintenance cost */
2400  run_cost += tuples * comparison_cost * logN;
2401 
2402  /*
2403  * Although MergeAppend does not do any selection or projection, it's not
2404  * free; add a small per-tuple overhead.
2405  */
2406  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2407 
2408  path->startup_cost = startup_cost + input_startup_cost;
2409  path->total_cost = startup_cost + run_cost + input_total_cost;
2410 }

References APPEND_CPU_COST_MULTIPLIER, cpu_operator_cost, cpu_tuple_cost, LOG2, Path::startup_cost, and Path::total_cost.

Referenced by create_merge_append_path().

◆ cost_namedtuplestorescan()

void cost_namedtuplestorescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1709 of file costsize.c.

1711 {
1712  Cost startup_cost = 0;
1713  Cost run_cost = 0;
1714  QualCost qpqual_cost;
1715  Cost cpu_per_tuple;
1716 
1717  /* Should only be applied to base relations that are Tuplestores */
1718  Assert(baserel->relid > 0);
1719  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1720 
1721  /* Mark the path with the correct row estimate */
1722  if (param_info)
1723  path->rows = param_info->ppi_rows;
1724  else
1725  path->rows = baserel->rows;
1726 
1727  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1728  cpu_per_tuple = cpu_tuple_cost;
1729 
1730  /* Add scanning CPU costs */
1731  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1732 
1733  startup_cost += qpqual_cost.startup;
1734  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1735  run_cost += cpu_per_tuple * baserel->tuples;
1736 
1737  path->startup_cost = startup_cost;
1738  path->total_cost = startup_cost + run_cost;
1739 }
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1018

References Assert(), cpu_tuple_cost, get_restriction_qual_cost(), QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::rows, Path::rows, RTE_NAMEDTUPLESTORE, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_namedtuplestorescan_path().

◆ cost_qual_eval()

void cost_qual_eval ( QualCost cost,
List quals,
PlannerInfo root 
)

Definition at line 4368 of file costsize.c.

4369 {
4370  cost_qual_eval_context context;
4371  ListCell *l;
4372 
4373  context.root = root;
4374  context.total.startup = 0;
4375  context.total.per_tuple = 0;
4376 
4377  /* We don't charge any cost for the implicit ANDing at top level ... */
4378 
4379  foreach(l, quals)
4380  {
4381  Node *qual = (Node *) lfirst(l);
4382 
4383  cost_qual_eval_walker(qual, &context);
4384  }
4385 
4386  *cost = context.total;
4387 }
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4408
PlannerInfo * root
Definition: costsize.c:158

References cost_qual_eval_walker(), lfirst, QualCost::per_tuple, cost_qual_eval_context::root, QualCost::startup, and cost_qual_eval_context::total.

Referenced by add_foreign_grouping_paths(), cost_agg(), cost_group(), cost_index(), cost_subplan(), cost_tidrangescan(), cost_tidscan(), create_group_result_path(), create_minmaxagg_path(), estimate_path_cost_size(), final_cost_hashjoin(), final_cost_mergejoin(), final_cost_nestloop(), get_restriction_qual_cost(), inline_function(), plan_cluster_use_sort(), postgresGetForeignJoinPaths(), postgresGetForeignRelSize(), set_baserel_size_estimates(), and set_foreign_size_estimates().

◆ cost_qual_eval_node()

void cost_qual_eval_node ( QualCost cost,
Node qual,
PlannerInfo root 
)

◆ cost_qual_eval_walker()

static bool cost_qual_eval_walker ( Node node,
cost_qual_eval_context context 
)
static

Definition at line 4408 of file costsize.c.

4409 {
4410  if (node == NULL)
4411  return false;
4412 
4413  /*
4414  * RestrictInfo nodes contain an eval_cost field reserved for this
4415  * routine's use, so that it's not necessary to evaluate the qual clause's
4416  * cost more than once. If the clause's cost hasn't been computed yet,
4417  * the field's startup value will contain -1.
4418  */
4419  if (IsA(node, RestrictInfo))
4420  {
4421  RestrictInfo *rinfo = (RestrictInfo *) node;
4422 
4423  if (rinfo->eval_cost.startup < 0)
4424  {
4425  cost_qual_eval_context locContext;
4426 
4427  locContext.root = context->root;
4428  locContext.total.startup = 0;
4429  locContext.total.per_tuple = 0;
4430 
4431  /*
4432  * For an OR clause, recurse into the marked-up tree so that we
4433  * set the eval_cost for contained RestrictInfos too.
4434  */
4435  if (rinfo->orclause)
4436  cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
4437  else
4438  cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
4439 
4440  /*
4441  * If the RestrictInfo is marked pseudoconstant, it will be tested
4442  * only once, so treat its cost as all startup cost.
4443  */
4444  if (rinfo->pseudoconstant)
4445  {
4446  /* count one execution during startup */
4447  locContext.total.startup += locContext.total.per_tuple;
4448  locContext.total.per_tuple = 0;
4449  }
4450  rinfo->eval_cost = locContext.total;
4451  }
4452  context->total.startup += rinfo->eval_cost.startup;
4453  context->total.per_tuple += rinfo->eval_cost.per_tuple;
4454  /* do NOT recurse into children */
4455  return false;
4456  }
4457 
4458  /*
4459  * For each operator or function node in the given tree, we charge the
4460  * estimated execution cost given by pg_proc.procost (remember to multiply
4461  * this by cpu_operator_cost).
4462  *
4463  * Vars and Consts are charged zero, and so are boolean operators (AND,
4464  * OR, NOT). Simplistic, but a lot better than no model at all.
4465  *
4466  * Should we try to account for the possibility of short-circuit
4467  * evaluation of AND/OR? Probably *not*, because that would make the
4468  * results depend on the clause ordering, and we are not in any position
4469  * to expect that the current ordering of the clauses is the one that's
4470  * going to end up being used. The above per-RestrictInfo caching would
4471  * not mix well with trying to re-order clauses anyway.
4472  *
4473  * Another issue that is entirely ignored here is that if a set-returning
4474  * function is below top level in the tree, the functions/operators above
4475  * it will need to be evaluated multiple times. In practical use, such
4476  * cases arise so seldom as to not be worth the added complexity needed;
4477  * moreover, since our rowcount estimates for functions tend to be pretty
4478  * phony, the results would also be pretty phony.
4479  */
4480  if (IsA(node, FuncExpr))
4481  {
4482  add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
4483  &context->total);
4484  }
4485  else if (IsA(node, OpExpr) ||
4486  IsA(node, DistinctExpr) ||
4487  IsA(node, NullIfExpr))
4488  {
4489  /* rely on struct equivalence to treat these all alike */
4490  set_opfuncid((OpExpr *) node);
4491  add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
4492  &context->total);
4493  }
4494  else if (IsA(node, ScalarArrayOpExpr))
4495  {
4496  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
4497  Node *arraynode = (Node *) lsecond(saop->args);
4498  QualCost sacosts;
4499  QualCost hcosts;
4500  int estarraylen = estimate_array_length(arraynode);
4501 
4502  set_sa_opfuncid(saop);
4503  sacosts.startup = sacosts.per_tuple = 0;
4504  add_function_cost(context->root, saop->opfuncid, NULL,
4505  &sacosts);
4506 
4507  if (OidIsValid(saop->hashfuncid))
4508  {
4509  /* Handle costs for hashed ScalarArrayOpExpr */
4510  hcosts.startup = hcosts.per_tuple = 0;
4511 
4512  add_function_cost(context->root, saop->hashfuncid, NULL, &hcosts);
4513  context->total.startup += sacosts.startup + hcosts.startup;
4514 
4515  /* Estimate the cost of building the hashtable. */
4516  context->total.startup += estarraylen * hcosts.per_tuple;
4517 
4518  /*
4519  * XXX should we charge a little bit for sacosts.per_tuple when
4520  * building the table, or is it ok to assume there will be zero
4521  * hash collision?
4522  */
4523 
4524  /*
4525  * Charge for hashtable lookups. Charge a single hash and a
4526  * single comparison.
4527  */
4528  context->total.per_tuple += hcosts.per_tuple + sacosts.per_tuple;
4529  }
4530  else
4531  {
4532  /*
4533  * Estimate that the operator will be applied to about half of the
4534  * array elements before the answer is determined.
4535  */
4536  context->total.startup += sacosts.startup;
4537  context->total.per_tuple += sacosts.per_tuple *
4538  estimate_array_length(arraynode) * 0.5;
4539  }
4540  }
4541  else if (IsA(node, Aggref) ||
4542  IsA(node, WindowFunc))
4543  {
4544  /*
4545  * Aggref and WindowFunc nodes are (and should be) treated like Vars,
4546  * ie, zero execution cost in the current model, because they behave
4547  * essentially like Vars at execution. We disregard the costs of
4548  * their input expressions for the same reason. The actual execution
4549  * costs of the aggregate/window functions and their arguments have to
4550  * be factored into plan-node-specific costing of the Agg or WindowAgg
4551  * plan node.
4552  */
4553  return false; /* don't recurse into children */
4554  }
4555  else if (IsA(node, GroupingFunc))
4556  {
4557  /* Treat this as having cost 1 */
4558  context->total.per_tuple += cpu_operator_cost;
4559  return false; /* don't recurse into children */
4560  }
4561  else if (IsA(node, CoerceViaIO))
4562  {
4563  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
4564  Oid iofunc;
4565  Oid typioparam;
4566  bool typisvarlena;
4567 
4568  /* check the result type's input function */
4569  getTypeInputInfo(iocoerce->resulttype,
4570  &iofunc, &typioparam);
4571  add_function_cost(context->root, iofunc, NULL,
4572  &context->total);
4573  /* check the input type's output function */
4574  getTypeOutputInfo(exprType((Node *) iocoerce->arg),
4575  &iofunc, &typisvarlena);
4576  add_function_cost(context->root, iofunc, NULL,
4577  &context->total);
4578  }
4579  else if (IsA(node, ArrayCoerceExpr))
4580  {
4581  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
4582  QualCost perelemcost;
4583 
4584  cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
4585  context->root);
4586  context->total.startup += perelemcost.startup;
4587  if (perelemcost.per_tuple > 0)
4588  context->total.per_tuple += perelemcost.per_tuple *
4589  estimate_array_length((Node *) acoerce->arg);
4590  }
4591  else if (IsA(node, RowCompareExpr))
4592  {
4593  /* Conservatively assume we will check all the columns */
4594  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
4595  ListCell *lc;
4596 
4597  foreach(lc, rcexpr->opnos)
4598  {
4599  Oid opid = lfirst_oid(lc);
4600 
4601  add_function_cost(context->root, get_opcode(opid), NULL,
4602  &context->total);
4603  }
4604  }
4605  else if (IsA(node, MinMaxExpr) ||
4606  IsA(node, XmlExpr) ||
4607  IsA(node, CoerceToDomain) ||
4608  IsA(node, NextValueExpr))
4609  {
4610  /* Treat all these as having cost 1 */
4611  context->total.per_tuple += cpu_operator_cost;
4612  }
4613  else if (IsA(node, CurrentOfExpr))
4614  {
4615  /* Report high cost to prevent selection of anything but TID scan */
4616  context->total.startup += disable_cost;
4617  }
4618  else if (IsA(node, SubLink))
4619  {
4620  /* This routine should not be applied to un-planned expressions */
4621  elog(ERROR, "cannot handle unplanned sub-select");
4622  }
4623  else if (IsA(node, SubPlan))
4624  {
4625  /*
4626  * A subplan node in an expression typically indicates that the
4627  * subplan will be executed on each evaluation, so charge accordingly.
4628  * (Sub-selects that can be executed as InitPlans have already been
4629  * removed from the expression.)
4630  */
4631  SubPlan *subplan = (SubPlan *) node;
4632 
4633  context->total.startup += subplan->startup_cost;
4634  context->total.per_tuple += subplan->per_call_cost;
4635 
4636  /*
4637  * We don't want to recurse into the testexpr, because it was already
4638  * counted in the SubPlan node's costs. So we're done.
4639  */
4640  return false;
4641  }
4642  else if (IsA(node, AlternativeSubPlan))
4643  {
4644  /*
4645  * Arbitrarily use the first alternative plan for costing. (We should
4646  * certainly only include one alternative, and we don't yet have
4647  * enough information to know which one the executor is most likely to
4648  * use.)
4649  */
4650  AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
4651 
4652  return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
4653  context);
4654  }
4655  else if (IsA(node, PlaceHolderVar))
4656  {
4657  /*
4658  * A PlaceHolderVar should be given cost zero when considering general
4659  * expression evaluation costs. The expense of doing the contained
4660  * expression is charged as part of the tlist eval costs of the scan
4661  * or join where the PHV is first computed (see set_rel_width and
4662  * add_placeholders_to_joinrel). If we charged it again here, we'd be
4663  * double-counting the cost for each level of plan that the PHV
4664  * bubbles up through. Hence, return without recursing into the
4665  * phexpr.
4666  */
4667  return false;
4668  }
4669 
4670  /* recurse into children */
4672  (void *) context);
4673 }
#define OidIsValid(objectId)
Definition: c.h:711
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2865
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1267
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2832
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1683
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1672
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:151
#define lsecond(l)
Definition: pg_list.h:181
#define lfirst_oid(lc)
Definition: pg_list.h:172
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:2007
unsigned int Oid
Definition: postgres_ext.h:31
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2133
Expr * arg
Definition: primnodes.h:1021
Oid resulttype
Definition: primnodes.h:1022
Cost startup_cost
Definition: primnodes.h:916
Cost per_call_cost
Definition: primnodes.h:917

References add_function_cost(), CoerceViaIO::arg, ArrayCoerceExpr::arg, ScalarArrayOpExpr::args, RestrictInfo::clause, cost_qual_eval_node(), cpu_operator_cost, disable_cost, ArrayCoerceExpr::elemexpr, elog(), ERROR, estimate_array_length(), expression_tree_walker, exprType(), get_opcode(), getTypeInputInfo(), getTypeOutputInfo(), IsA, lfirst_oid, linitial, lsecond, OidIsValid, RowCompareExpr::opnos, SubPlan::per_call_cost, QualCost::per_tuple, CoerceViaIO::resulttype, cost_qual_eval_context::root, set_opfuncid(), set_sa_opfuncid(), QualCost::startup, SubPlan::startup_cost, AlternativeSubPlan::subplans, and cost_qual_eval_context::total.

Referenced by cost_qual_eval(), and cost_qual_eval_node().

◆ cost_recursive_union()

void cost_recursive_union ( Path runion,
Path nrterm,
Path rterm 
)

Definition at line 1783 of file costsize.c.

1784 {
1785  Cost startup_cost;
1786  Cost total_cost;
1787  double total_rows;
1788 
1789  /* We probably have decent estimates for the non-recursive term */
1790  startup_cost = nrterm->startup_cost;
1791  total_cost = nrterm->total_cost;
1792  total_rows = nrterm->rows;
1793 
1794  /*
1795  * We arbitrarily assume that about 10 recursive iterations will be
1796  * needed, and that we've managed to get a good fix on the cost and output
1797  * size of each one of them. These are mighty shaky assumptions but it's
1798  * hard to see how to do better.
1799  */
1800  total_cost += 10 * rterm->total_cost;
1801  total_rows += 10 * rterm->rows;
1802 
1803  /*
1804  * Also charge cpu_tuple_cost per row to account for the costs of
1805  * manipulating the tuplestores. (We don't worry about possible
1806  * spill-to-disk costs.)
1807  */
1808  total_cost += cpu_tuple_cost * total_rows;
1809 
1810  runion->startup_cost = startup_cost;
1811  runion->total_cost = total_cost;
1812  runion->rows = total_rows;
1813  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1814  rterm->pathtarget->width);
1815 }

References cpu_tuple_cost, Max, Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by create_recursiveunion_path().

◆ cost_rescan()

static void cost_rescan ( PlannerInfo root,
Path path,
Cost rescan_startup_cost,
Cost rescan_total_cost 
)
static

Definition at line 4256 of file costsize.c.

4259 {
4260  switch (path->pathtype)
4261  {
4262  case T_FunctionScan:
4263 
4264  /*
4265  * Currently, nodeFunctionscan.c always executes the function to
4266  * completion before returning any rows, and caches the results in
4267  * a tuplestore. So the function eval cost is all startup cost
4268  * and isn't paid over again on rescans. However, all run costs
4269  * will be paid over again.
4270  */
4271  *rescan_startup_cost = 0;
4272  *rescan_total_cost = path->total_cost - path->startup_cost;
4273  break;
4274  case T_HashJoin:
4275 
4276  /*
4277  * If it's a single-batch join, we don't need to rebuild the hash
4278  * table during a rescan.
4279  */
4280  if (((HashPath *) path)->num_batches == 1)
4281  {
4282  /* Startup cost is exactly the cost of hash table building */
4283  *rescan_startup_cost = 0;
4284  *rescan_total_cost = path->total_cost - path->startup_cost;
4285  }
4286  else
4287  {
4288  /* Otherwise, no special treatment */
4289  *rescan_startup_cost = path->startup_cost;
4290  *rescan_total_cost = path->total_cost;
4291  }
4292  break;
4293  case T_CteScan:
4294  case T_WorkTableScan:
4295  {
4296  /*
4297  * These plan types materialize their final result in a
4298  * tuplestore or tuplesort object. So the rescan cost is only
4299  * cpu_tuple_cost per tuple, unless the result is large enough
4300  * to spill to disk.
4301  */
4302  Cost run_cost = cpu_tuple_cost * path->rows;
4303  double nbytes = relation_byte_size(path->rows,
4304  path->pathtarget->width);
4305  long work_mem_bytes = work_mem * 1024L;
4306 
4307  if (nbytes > work_mem_bytes)
4308  {
4309  /* It will spill, so account for re-read cost */
4310  double npages = ceil(nbytes / BLCKSZ);
4311 
4312  run_cost += seq_page_cost * npages;
4313  }
4314  *rescan_startup_cost = 0;
4315  *rescan_total_cost = run_cost;
4316  }
4317  break;
4318  case T_Material:
4319  case T_Sort:
4320  {
4321  /*
4322  * These plan types not only materialize their results, but do
4323  * not implement qual filtering or projection. So they are
4324  * even cheaper to rescan than the ones above. We charge only
4325  * cpu_operator_cost per tuple. (Note: keep that in sync with
4326  * the run_cost charge in cost_sort, and also see comments in
4327  * cost_material before you change it.)
4328  */
4329  Cost run_cost = cpu_operator_cost * path->rows;
4330  double nbytes = relation_byte_size(path->rows,
4331  path->pathtarget->width);
4332  long work_mem_bytes = work_mem * 1024L;
4333 
4334  if (nbytes > work_mem_bytes)
4335  {
4336  /* It will spill, so account for re-read cost */
4337  double npages = ceil(nbytes / BLCKSZ);
4338 
4339  run_cost += seq_page_cost * npages;
4340  }
4341  *rescan_startup_cost = 0;
4342  *rescan_total_cost = run_cost;
4343  }
4344  break;
4345  case T_Memoize:
4346  /* All the hard work is done by cost_memoize_rescan */
4347  cost_memoize_rescan(root, (MemoizePath *) path,
4348  rescan_startup_cost, rescan_total_cost);
4349  break;
4350  default:
4351  *rescan_startup_cost = path->startup_cost;
4352  *rescan_total_cost = path->total_cost;
4353  break;
4354  }
4355 }
static void cost_memoize_rescan(PlannerInfo *root, MemoizePath *mpath, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:2481

References cost_memoize_rescan(), cpu_operator_cost, cpu_tuple_cost, Path::pathtype, relation_byte_size(), seq_page_cost, Path::startup_cost, Path::total_cost, and work_mem.

Referenced by initial_cost_nestloop().

◆ cost_resultscan()

void cost_resultscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1746 of file costsize.c.

1748 {
1749  Cost startup_cost = 0;
1750  Cost run_cost = 0;
1751  QualCost qpqual_cost;
1752  Cost cpu_per_tuple;
1753 
1754  /* Should only be applied to RTE_RESULT base relations */
1755  Assert(baserel->relid > 0);
1756  Assert(baserel->rtekind == RTE_RESULT);
1757 
1758  /* Mark the path with the correct row estimate */
1759  if (param_info)
1760  path->rows = param_info->ppi_rows;
1761  else
1762  path->rows = baserel->rows;
1763 
1764  /* We charge qual cost plus cpu_tuple_cost */
1765  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1766 
1767  startup_cost += qpqual_cost.startup;
1768  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1769  run_cost += cpu_per_tuple * baserel->tuples;
1770 
1771  path->startup_cost = startup_cost;
1772  path->total_cost = startup_cost + run_cost;
1773 }
@ RTE_RESULT
Definition: parsenodes.h:1019

References Assert(), cpu_tuple_cost, get_restriction_qual_cost(), QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::rows, Path::rows, RTE_RESULT, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_resultscan_path().

◆ cost_samplescan()

void cost_samplescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 331 of file costsize.c.

333 {
334  Cost startup_cost = 0;
335  Cost run_cost = 0;
336  RangeTblEntry *rte;
337  TableSampleClause *tsc;
338  TsmRoutine *tsm;
339  double spc_seq_page_cost,
340  spc_random_page_cost,
341  spc_page_cost;
342  QualCost qpqual_cost;
343  Cost cpu_per_tuple;
344 
345  /* Should only be applied to base relations with tablesample clauses */
346  Assert(baserel->relid > 0);
347  rte = planner_rt_fetch(baserel->relid, root);
348  Assert(rte->rtekind == RTE_RELATION);
349  tsc = rte->tablesample;
350  Assert(tsc != NULL);
351  tsm = GetTsmRoutine(tsc->tsmhandler);
352 
353  /* Mark the path with the correct row estimate */
354  if (param_info)
355  path->rows = param_info->ppi_rows;
356  else
357  path->rows = baserel->rows;
358 
359  /* fetch estimated page cost for tablespace containing table */
361  &spc_random_page_cost,
362  &spc_seq_page_cost);
363 
364  /* if NextSampleBlock is used, assume random access, else sequential */
365  spc_page_cost = (tsm->NextSampleBlock != NULL) ?
366  spc_random_page_cost : spc_seq_page_cost;
367 
368  /*
369  * disk costs (recall that baserel->pages has already been set to the
370  * number of pages the sampling method will visit)
371  */
372  run_cost += spc_page_cost * baserel->pages;
373 
374  /*
375  * CPU costs (recall that baserel->tuples has already been set to the
376  * number of tuples the sampling method will select). Note that we ignore
377  * execution cost of the TABLESAMPLE parameter expressions; they will be
378  * evaluated only once per scan, and in most usages they'll likely be
379  * simple constants anyway. We also don't charge anything for the
380  * calculations the sampling method might do internally.
381  */
382  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
383 
384  startup_cost += qpqual_cost.startup;
385  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
386  run_cost += cpu_per_tuple * baserel->tuples;
387  /* tlist eval costs are paid per output row, not per tuple scanned */
388  startup_cost += path->pathtarget->cost.startup;
389  run_cost += path->pathtarget->cost.per_tuple * path->rows;
390 
391  path->startup_cost = startup_cost;
392  path->total_cost = startup_cost + run_cost;
393 }
struct TableSampleClause * tablesample
Definition: parsenodes.h:1060
NextSampleBlock_function NextSampleBlock
Definition: tsmapi.h:73
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27

References Assert(), cpu_tuple_cost, get_restriction_qual_cost(), get_tablespace_page_costs(), GetTsmRoutine(), TsmRoutine::NextSampleBlock, RelOptInfo::pages, QualCost::per_tuple, planner_rt_fetch, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, RelOptInfo::rows, Path::rows, RTE_RELATION, RangeTblEntry::rtekind, QualCost::startup, Path::startup_cost, RangeTblEntry::tablesample, Path::total_cost, TableSampleClause::tsmhandler, and RelOptInfo::tuples.

Referenced by create_samplescan_path().

◆ cost_seqscan()

void cost_seqscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 254 of file costsize.c.

256 {
257  Cost startup_cost = 0;
258  Cost cpu_run_cost;
259  Cost disk_run_cost;
260  double spc_seq_page_cost;
261  QualCost qpqual_cost;
262  Cost cpu_per_tuple;
263 
264  /* Should only be applied to base relations */
265  Assert(baserel->relid > 0);
266  Assert(baserel->rtekind == RTE_RELATION);
267 
268  /* Mark the path with the correct row estimate */
269  if (param_info)
270  path->rows = param_info->ppi_rows;
271  else
272  path->rows = baserel->rows;
273 
274  if (!enable_seqscan)
275  startup_cost += disable_cost;
276 
277  /* fetch estimated page cost for tablespace containing table */
279  NULL,
280  &spc_seq_page_cost);
281 
282  /*
283  * disk costs
284  */
285  disk_run_cost = spc_seq_page_cost * baserel->pages;
286 
287  /* CPU costs */
288  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
289 
290  startup_cost += qpqual_cost.startup;
291  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
292  cpu_run_cost = cpu_per_tuple * baserel->tuples;
293  /* tlist eval costs are paid per output row, not per tuple scanned */
294  startup_cost += path->pathtarget->cost.startup;
295  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
296 
297  /* Adjust costing for parallelism, if used. */
298  if (path->parallel_workers > 0)
299  {
300  double parallel_divisor = get_parallel_divisor(path);
301 
302  /* The CPU cost is divided among all the workers. */
303  cpu_run_cost /= parallel_divisor;
304 
305  /*
306  * It may be possible to amortize some of the I/O cost, but probably
307  * not very much, because most operating systems already do aggressive
308  * prefetching. For now, we assume that the disk run cost can't be
309  * amortized at all.
310  */
311 
312  /*
313  * In the case of a parallel plan, the row count needs to represent
314  * the number of tuples processed per worker.
315  */
316  path->rows = clamp_row_est(path->rows / parallel_divisor);
317  }
318 
319  path->startup_cost = startup_cost;
320  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
321 }
bool enable_seqscan
Definition: costsize.c:135

References Assert(), clamp_row_est(), cpu_tuple_cost, disable_cost, enable_seqscan, get_parallel_divisor(), get_restriction_qual_cost(), get_tablespace_page_costs(), RelOptInfo::pages, Path::parallel_workers, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_seqscan_path().

◆ cost_sort()

void cost_sort ( Path path,
PlannerInfo root,
List pathkeys,
Cost  input_cost,
double  tuples,
int  width,
Cost  comparison_cost,
int  sort_mem,
double  limit_tuples 
)

Definition at line 2096 of file costsize.c.

2101 {
2102  Cost startup_cost;
2103  Cost run_cost;
2104 
2105  cost_tuplesort(&startup_cost, &run_cost,
2106  tuples, width,
2107  comparison_cost, sort_mem,
2108  limit_tuples);
2109 
2110  if (!enable_sort)
2111  startup_cost += disable_cost;
2112 
2113  startup_cost += input_cost;
2114 
2115  path->rows = tuples;
2116  path->startup_cost = startup_cost;
2117  path->total_cost = startup_cost + run_cost;
2118 }
bool enable_sort
Definition: costsize.c:140

References cost_tuplesort(), disable_cost, enable_sort, Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by adjust_foreign_grouping_path_cost(), choose_hashed_setop(), cost_append(), create_gather_merge_path(), create_groupingsets_path(), create_merge_append_path(), create_sort_path(), create_unique_path(), initial_cost_mergejoin(), label_sort_with_costsize(), and plan_cluster_use_sort().

◆ cost_subplan()

void cost_subplan ( PlannerInfo root,
SubPlan subplan,
Plan plan 
)

Definition at line 4163 of file costsize.c.

4164 {
4165  QualCost sp_cost;
4166 
4167  /* Figure any cost for evaluating the testexpr */
4168  cost_qual_eval(&sp_cost,
4169  make_ands_implicit((Expr *) subplan->testexpr),
4170  root);
4171 
4172  if (subplan->useHashTable)
4173  {
4174  /*
4175  * If we are using a hash table for the subquery outputs, then the
4176  * cost of evaluating the query is a one-time cost. We charge one
4177  * cpu_operator_cost per tuple for the work of loading the hashtable,
4178  * too.
4179  */
4180  sp_cost.startup += plan->total_cost +
4181  cpu_operator_cost * plan->plan_rows;
4182 
4183  /*
4184  * The per-tuple costs include the cost of evaluating the lefthand
4185  * expressions, plus the cost of probing the hashtable. We already
4186  * accounted for the lefthand expressions as part of the testexpr, and
4187  * will also have counted one cpu_operator_cost for each comparison
4188  * operator. That is probably too low for the probing cost, but it's
4189  * hard to make a better estimate, so live with it for now.
4190  */
4191  }
4192  else
4193  {
4194  /*
4195  * Otherwise we will be rescanning the subplan output on each
4196  * evaluation. We need to estimate how much of the output we will
4197  * actually need to scan. NOTE: this logic should agree with the
4198  * tuple_fraction estimates used by make_subplan() in
4199  * plan/subselect.c.
4200  */
4201  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4202 
4203  if (subplan->subLinkType == EXISTS_SUBLINK)
4204  {
4205  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4206  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4207  }
4208  else if (subplan->subLinkType == ALL_SUBLINK ||
4209  subplan->subLinkType == ANY_SUBLINK)
4210  {
4211  /* assume we need 50% of the tuples */
4212  sp_cost.per_tuple += 0.50 * plan_run_cost;
4213  /* also charge a cpu_operator_cost per row examined */
4214  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4215  }
4216  else
4217  {
4218  /* assume we need all tuples */
4219  sp_cost.per_tuple += plan_run_cost;
4220  }
4221 
4222  /*
4223  * Also account for subplan's startup cost. If the subplan is
4224  * uncorrelated or undirect correlated, AND its topmost node is one
4225  * that materializes its output, assume that we'll only need to pay
4226  * its startup cost once; otherwise assume we pay the startup cost
4227  * every time.
4228  */
4229  if (subplan->parParam == NIL &&
4231  sp_cost.startup += plan->startup_cost;
4232  else
4233  sp_cost.per_tuple += plan->startup_cost;
4234  }
4235 
4236  subplan->startup_cost = sp_cost.startup;
4237  subplan->per_call_cost = sp_cost.per_tuple;
4238 }
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:637
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
@ ANY_SUBLINK
Definition: primnodes.h:826
@ ALL_SUBLINK
Definition: primnodes.h:825
@ EXISTS_SUBLINK
Definition: primnodes.h:824
Cost total_cost
Definition: plannodes.h:130
Cost startup_cost
Definition: plannodes.h:129
Cardinality plan_rows
Definition: plannodes.h:135
bool useHashTable
Definition: primnodes.h:902
Node * testexpr
Definition: primnodes.h:890
List * parParam
Definition: primnodes.h:913
SubLinkType subLinkType
Definition: primnodes.h:888

References ALL_SUBLINK, ANY_SUBLINK, clamp_row_est(), cost_qual_eval(), cpu_operator_cost, ExecMaterializesOutput(), EXISTS_SUBLINK, make_ands_implicit(), NIL, nodeTag, SubPlan::parParam, SubPlan::per_call_cost, QualCost::per_tuple, Plan::plan_rows, QualCost::startup, Plan::startup_cost, SubPlan::startup_cost, SubPlan::subLinkType, SubPlan::testexpr, Plan::total_cost, and SubPlan::useHashTable.

Referenced by build_subplan(), SS_make_initplan_from_plan(), and SS_process_ctes().

◆ cost_subqueryscan()

void cost_subqueryscan ( SubqueryScanPath path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info,
bool  trivial_pathtarget 
)

Definition at line 1421 of file costsize.c.

1424 {
1425  Cost startup_cost;
1426  Cost run_cost;
1427  List *qpquals;
1428  QualCost qpqual_cost;
1429  Cost cpu_per_tuple;
1430 
1431  /* Should only be applied to base relations that are subqueries */
1432  Assert(baserel->relid > 0);
1433  Assert(baserel->rtekind == RTE_SUBQUERY);
1434 
1435  /*
1436  * We compute the rowcount estimate as the subplan's estimate times the
1437  * selectivity of relevant restriction clauses. In simple cases this will
1438  * come out the same as baserel->rows; but when dealing with parallelized
1439  * paths we must do it like this to get the right answer.
1440  */
1441  if (param_info)
1442  qpquals = list_concat_copy(param_info->ppi_clauses,
1443  baserel->baserestrictinfo);
1444  else
1445  qpquals = baserel->baserestrictinfo;
1446 
1447  path->path.rows = clamp_row_est(path->subpath->rows *
1449  qpquals,
1450  0,
1451  JOIN_INNER,
1452  NULL));
1453 
1454  /*
1455  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1456  * any restriction clauses and tlist that will be attached to the
1457  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1458  * projection overhead.
1459  */
1460  path->path.startup_cost = path->subpath->startup_cost;
1461  path->path.total_cost = path->subpath->total_cost;
1462 
1463  /*
1464  * However, if there are no relevant restriction clauses and the
1465  * pathtarget is trivial, then we expect that setrefs.c will optimize away
1466  * the SubqueryScan plan node altogether, so we should just make its cost
1467  * and rowcount equal to the input path's.
1468  *
1469  * Note: there are some edge cases where createplan.c will apply a
1470  * different targetlist to the SubqueryScan node, thus falsifying our
1471  * current estimate of whether the target is trivial, and making the cost
1472  * estimate (though not the rowcount) wrong. It does not seem worth the
1473  * extra complication to try to account for that exactly, especially since
1474  * that behavior falsifies other cost estimates as well.
1475  */
1476  if (qpquals == NIL && trivial_pathtarget)
1477  return;
1478 
1479  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1480 
1481  startup_cost = qpqual_cost.startup;
1482  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1483  run_cost = cpu_per_tuple * path->subpath->rows;
1484 
1485  /* tlist eval costs are paid per output row, not per tuple scanned */
1486  startup_cost += path->path.pathtarget->cost.startup;
1487  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1488 
1489  path->path.startup_cost += startup_cost;
1490  path->path.total_cost += startup_cost + run_cost;
1491 }
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:597
@ RTE_SUBQUERY
Definition: parsenodes.h:1012
List * ppi_clauses
Definition: pathnodes.h:1466
List * baserestrictinfo
Definition: pathnodes.h:930

References Assert(), RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), cpu_tuple_cost, get_restriction_qual_cost(), JOIN_INNER, list_concat_copy(), NIL, SubqueryScanPath::path, QualCost::per_tuple, ParamPathInfo::ppi_clauses, RelOptInfo::relid, Path::rows, RTE_SUBQUERY, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, SubqueryScanPath::subpath, and Path::total_cost.

Referenced by create_subqueryscan_path().

◆ cost_tablefuncscan()

void cost_tablefuncscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1562 of file costsize.c.

1564 {
1565  Cost startup_cost = 0;
1566  Cost run_cost = 0;
1567  QualCost qpqual_cost;
1568  Cost cpu_per_tuple;
1569  RangeTblEntry *rte;
1570  QualCost exprcost;
1571 
1572  /* Should only be applied to base relations that are functions */
1573  Assert(baserel->relid > 0);
1574  rte = planner_rt_fetch(baserel->relid, root);
1575  Assert(rte->rtekind == RTE_TABLEFUNC);
1576 
1577  /* Mark the path with the correct row estimate */
1578  if (param_info)
1579  path->rows = param_info->ppi_rows;
1580  else
1581  path->rows = baserel->rows;
1582 
1583  /*
1584  * Estimate costs of executing the table func expression(s).
1585  *
1586  * XXX in principle we ought to charge tuplestore spill costs if the
1587  * number of rows is large. However, given how phony our rowcount
1588  * estimates for tablefuncs tend to be, there's not a lot of point in that
1589  * refinement right now.
1590  */
1591  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1592 
1593  startup_cost += exprcost.startup + exprcost.per_tuple;
1594 
1595  /* Add scanning CPU costs */
1596  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1597 
1598  startup_cost += qpqual_cost.startup;
1599  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1600  run_cost += cpu_per_tuple * baserel->tuples;
1601 
1602  /* tlist eval costs are paid per output row, not per tuple scanned */
1603  startup_cost += path->pathtarget->cost.startup;
1604  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1605 
1606  path->startup_cost = startup_cost;
1607  path->total_cost = startup_cost + run_cost;
1608 }
@ RTE_TABLEFUNC
Definition: parsenodes.h:1015
TableFunc * tablefunc
Definition: parsenodes.h:1130

References Assert(), cost_qual_eval_node(), cpu_tuple_cost, get_restriction_qual_cost(), QualCost::per_tuple, planner_rt_fetch, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::rows, Path::rows, RTE_TABLEFUNC, RangeTblEntry::rtekind, QualCost::startup, Path::startup_cost, RangeTblEntry::tablefunc, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_tablefuncscan_path().

◆ cost_tidrangescan()

void cost_tidrangescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
List tidrangequals,
ParamPathInfo param_info 
)

Definition at line 1327 of file costsize.c.

1330 {
1331  Selectivity selectivity;
1332  double pages;
1333  Cost startup_cost = 0;
1334  Cost run_cost = 0;
1335  QualCost qpqual_cost;
1336  Cost cpu_per_tuple;
1337  QualCost tid_qual_cost;
1338  double ntuples;
1339  double nseqpages;
1340  double spc_random_page_cost;
1341  double spc_seq_page_cost;
1342 
1343  /* Should only be applied to base relations */
1344  Assert(baserel->relid > 0);
1345  Assert(baserel->rtekind == RTE_RELATION);
1346 
1347  /* Mark the path with the correct row estimate */
1348  if (param_info)
1349  path->rows = param_info->ppi_rows;
1350  else
1351  path->rows = baserel->rows;
1352 
1353  /* Count how many tuples and pages we expect to scan */
1354  selectivity = clauselist_selectivity(root, tidrangequals, baserel->relid,
1355  JOIN_INNER, NULL);
1356  pages = ceil(selectivity * baserel->pages);
1357 
1358  if (pages <= 0.0)
1359  pages = 1.0;
1360 
1361  /*
1362  * The first page in a range requires a random seek, but each subsequent
1363  * page is just a normal sequential page read. NOTE: it's desirable for
1364  * TID Range Scans to cost more than the equivalent Sequential Scans,
1365  * because Seq Scans have some performance advantages such as scan
1366  * synchronization and parallelizability, and we'd prefer one of them to
1367  * be picked unless a TID Range Scan really is better.
1368  */
1369  ntuples = selectivity * baserel->tuples;
1370  nseqpages = pages - 1.0;
1371 
1372  if (!enable_tidscan)
1373  startup_cost += disable_cost;
1374 
1375  /*
1376  * The TID qual expressions will be computed once, any other baserestrict
1377  * quals once per retrieved tuple.
1378  */
1379  cost_qual_eval(&tid_qual_cost, tidrangequals, root);
1380 
1381  /* fetch estimated page cost for tablespace containing table */
1383  &spc_random_page_cost,
1384  &spc_seq_page_cost);
1385 
1386  /* disk costs; 1 random page and the remainder as seq pages */
1387  run_cost += spc_random_page_cost + spc_seq_page_cost * nseqpages;
1388 
1389  /* Add scanning CPU costs */
1390  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1391 
1392  /*
1393  * XXX currently we assume TID quals are a subset of qpquals at this
1394  * point; they will be removed (if possible) when we create the plan, so
1395  * we subtract their cost from the total qpqual cost. (If the TID quals
1396  * can't be removed, this is a mistake and we're going to underestimate
1397  * the CPU cost a bit.)
1398  */
1399  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1400  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1401  tid_qual_cost.per_tuple;
1402  run_cost += cpu_per_tuple * ntuples;
1403 
1404  /* tlist eval costs are paid per output row, not per tuple scanned */
1405  startup_cost += path->pathtarget->cost.startup;
1406  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1407 
1408  path->startup_cost = startup_cost;
1409  path->total_cost = startup_cost + run_cost;
1410 }
bool enable_tidscan
Definition: costsize.c:139

References Assert(), clauselist_selectivity(), cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_tidscan, get_restriction_qual_cost(), get_tablespace_page_costs(), JOIN_INNER, RelOptInfo::pages, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_tidrangescan_path().

◆ cost_tidscan()

void cost_tidscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
List tidquals,
ParamPathInfo param_info 
)

Definition at line 1219 of file costsize.c.

1221 {
1222  Cost startup_cost = 0;
1223  Cost run_cost = 0;
1224  bool isCurrentOf = false;
1225  QualCost qpqual_cost;
1226  Cost cpu_per_tuple;
1227  QualCost tid_qual_cost;
1228  int ntuples;
1229  ListCell *l;
1230  double spc_random_page_cost;
1231 
1232  /* Should only be applied to base relations */
1233  Assert(baserel->relid > 0);
1234  Assert(baserel->rtekind == RTE_RELATION);
1235 
1236  /* Mark the path with the correct row estimate */
1237  if (param_info)
1238  path->rows = param_info->ppi_rows;
1239  else
1240  path->rows = baserel->rows;
1241 
1242  /* Count how many tuples we expect to retrieve */
1243  ntuples = 0;
1244  foreach(l, tidquals)
1245  {
1246  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
1247  Expr *qual = rinfo->clause;
1248 
1249  if (IsA(qual, ScalarArrayOpExpr))
1250  {
1251  /* Each element of the array yields 1 tuple */
1252  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) qual;
1253  Node *arraynode = (Node *) lsecond(saop->args);
1254 
1255  ntuples += estimate_array_length(arraynode);
1256  }
1257  else if (IsA(qual, CurrentOfExpr))
1258  {
1259  /* CURRENT OF yields 1 tuple */
1260  isCurrentOf = true;
1261  ntuples++;
1262  }
1263  else
1264  {
1265  /* It's just CTID = something, count 1 tuple */
1266  ntuples++;
1267  }
1268  }
1269 
1270  /*
1271  * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
1272  * understands how to do it correctly. Therefore, honor enable_tidscan
1273  * only when CURRENT OF isn't present. Also note that cost_qual_eval
1274  * counts a CurrentOfExpr as having startup cost disable_cost, which we
1275  * subtract off here; that's to prevent other plan types such as seqscan
1276  * from winning.
1277  */
1278  if (isCurrentOf)
1279  {
1281  startup_cost -= disable_cost;
1282  }
1283  else if (!enable_tidscan)
1284  startup_cost += disable_cost;
1285 
1286  /*
1287  * The TID qual expressions will be computed once, any other baserestrict
1288  * quals once per retrieved tuple.
1289  */
1290  cost_qual_eval(&tid_qual_cost, tidquals, root);
1291 
1292  /* fetch estimated page cost for tablespace containing table */
1294  &spc_random_page_cost,
1295  NULL);
1296 
1297  /* disk costs --- assume each tuple on a different page */
1298  run_cost += spc_random_page_cost * ntuples;
1299 
1300  /* Add scanning CPU costs */
1301  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1302 
1303  /* XXX currently we assume TID quals are a subset of qpquals */
1304  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1305  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1306  tid_qual_cost.per_tuple;
1307  run_cost += cpu_per_tuple * ntuples;
1308 
1309  /* tlist eval costs are paid per output row, not per tuple scanned */
1310  startup_cost += path->pathtarget->cost.startup;
1311  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1312 
1313  path->startup_cost = startup_cost;
1314  path->total_cost = startup_cost + run_cost;
1315 }
QualCost baserestrictcost
Definition: pathnodes.h:932

References ScalarArrayOpExpr::args, Assert(), RelOptInfo::baserestrictcost, RestrictInfo::clause, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_tidscan, estimate_array_length(), get_restriction_qual_cost(), get_tablespace_page_costs(), IsA, lfirst_node, lsecond, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, and Path::total_cost.

Referenced by create_tidscan_path().

◆ cost_tuplesort()

static void cost_tuplesort ( Cost startup_cost,
Cost run_cost,
double  tuples,
int  width,
Cost  comparison_cost,
int  sort_mem,
double  limit_tuples 
)
static

Definition at line 1854 of file costsize.c.

1858 {
1859  double input_bytes = relation_byte_size(tuples, width);
1860  double output_bytes;
1861  double output_tuples;
1862  long sort_mem_bytes = sort_mem * 1024L;
1863 
1864  /*
1865  * We want to be sure the cost of a sort is never estimated as zero, even
1866  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1867  */
1868  if (tuples < 2.0)
1869  tuples = 2.0;
1870 
1871  /* Include the default cost-per-comparison */
1872  comparison_cost += 2.0 * cpu_operator_cost;
1873 
1874  /* Do we have a useful LIMIT? */
1875  if (limit_tuples > 0 && limit_tuples < tuples)
1876  {
1877  output_tuples = limit_tuples;
1878  output_bytes = relation_byte_size(output_tuples, width);
1879  }
1880  else
1881  {
1882  output_tuples = tuples;
1883  output_bytes = input_bytes;
1884  }
1885 
1886  if (output_bytes > sort_mem_bytes)
1887  {
1888  /*
1889  * We'll have to use a disk-based sort of all the tuples
1890  */
1891  double npages = ceil(input_bytes / BLCKSZ);
1892  double nruns = input_bytes / sort_mem_bytes;
1893  double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1894  double log_runs;
1895  double npageaccesses;
1896 
1897  /*
1898  * CPU costs
1899  *
1900  * Assume about N log2 N comparisons
1901  */
1902  *startup_cost = comparison_cost * tuples * LOG2(tuples);
1903 
1904  /* Disk costs */
1905 
1906  /* Compute logM(r) as log(r) / log(M) */
1907  if (nruns > mergeorder)
1908  log_runs = ceil(log(nruns) / log(mergeorder));
1909  else
1910  log_runs = 1.0;
1911  npageaccesses = 2.0 * npages * log_runs;
1912  /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1913  *startup_cost += npageaccesses *
1914  (seq_page_cost * 0.75 + random_page_cost * 0.25);
1915  }
1916  else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1917  {
1918  /*
1919  * We'll use a bounded heap-sort keeping just K tuples in memory, for
1920  * a total number of tuple comparisons of N log2 K; but the constant
1921  * factor is a bit higher than for quicksort. Tweak it so that the
1922  * cost curve is continuous at the crossover point.
1923  */
1924  *startup_cost = comparison_cost * tuples * LOG2(2.0 * output_tuples);
1925  }
1926  else
1927  {
1928  /* We'll use plain quicksort on all the input tuples */
1929  *startup_cost = comparison_cost * tuples * LOG2(tuples);
1930  }
1931 
1932  /*
1933  * Also charge a small amount (arbitrarily set equal to operator cost) per
1934  * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1935  * doesn't do qual-checking or projection, so it has less overhead than
1936  * most plan nodes. Note it's correct to use tuples not output_tuples
1937  * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1938  * counting the LIMIT otherwise.
1939  */
1940  *run_cost = cpu_operator_cost * tuples;
1941 }
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:1804

References cpu_operator_cost, LOG2, random_page_cost, relation_byte_size(), seq_page_cost, and tuplesort_merge_order().

Referenced by cost_incremental_sort(), and cost_sort().

◆ cost_valuesscan()

void cost_valuesscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1618 of file costsize.c.

1620 {
1621  Cost startup_cost = 0;
1622  Cost run_cost = 0;
1623  QualCost qpqual_cost;
1624  Cost cpu_per_tuple;
1625 
1626  /* Should only be applied to base relations that are values lists */
1627  Assert(baserel->relid > 0);
1628  Assert(baserel->rtekind == RTE_VALUES);
1629 
1630  /* Mark the path with the correct row estimate */
1631  if (param_info)
1632  path->rows = param_info->ppi_rows;
1633  else
1634  path->rows = baserel->rows;
1635 
1636  /*
1637  * For now, estimate list evaluation cost at one operator eval per list
1638  * (probably pretty bogus, but is it worth being smarter?)
1639  */
1640  cpu_per_tuple = cpu_operator_cost;
1641 
1642  /* Add scanning CPU costs */
1643  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1644 
1645  startup_cost += qpqual_cost.startup;
1646  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1647  run_cost += cpu_per_tuple * baserel->tuples;
1648 
1649  /* tlist eval costs are paid per output row, not per tuple scanned */
1650  startup_cost += path->pathtarget->cost.startup;
1651  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1652 
1653  path->startup_cost = startup_cost;
1654  path->total_cost = startup_cost + run_cost;
1655 }
@ RTE_VALUES
Definition: parsenodes.h:1016

References Assert(), cpu_operator_cost, cpu_tuple_cost, get_restriction_qual_cost(), QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::rows, Path::rows, RTE_VALUES, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_valuesscan_path().

◆ cost_windowagg()

void cost_windowagg ( Path path,
PlannerInfo root,
List windowFuncs,
int  numPartCols,
int  numOrderCols,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples 
)

Definition at line 2818 of file costsize.c.

2822 {
2823  Cost startup_cost;
2824  Cost total_cost;
2825  ListCell *lc;
2826 
2827  startup_cost = input_startup_cost;
2828  total_cost = input_total_cost;
2829 
2830  /*
2831  * Window functions are assumed to cost their stated execution cost, plus
2832  * the cost of evaluating their input expressions, per tuple. Since they
2833  * may in fact evaluate their inputs at multiple rows during each cycle,
2834  * this could be a drastic underestimate; but without a way to know how
2835  * many rows the window function will fetch, it's hard to do better. In
2836  * any case, it's a good estimate for all the built-in window functions,
2837  * so we'll just do this for now.
2838  */
2839  foreach(lc, windowFuncs)
2840  {
2841  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
2842  Cost wfunccost;
2843  QualCost argcosts;
2844 
2845  argcosts.startup = argcosts.per_tuple = 0;
2846  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
2847  &argcosts);
2848  startup_cost += argcosts.startup;
2849  wfunccost = argcosts.per_tuple;
2850 
2851  /* also add the input expressions' cost to per-input-row costs */
2852  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
2853  startup_cost += argcosts.startup;
2854  wfunccost += argcosts.per_tuple;
2855 
2856  /*
2857  * Add the filter's cost to per-input-row costs. XXX We should reduce
2858  * input expression costs according to filter selectivity.
2859  */
2860  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
2861  startup_cost += argcosts.startup;
2862  wfunccost += argcosts.per_tuple;
2863 
2864  total_cost += wfunccost * input_tuples;
2865  }
2866 
2867  /*
2868  * We also charge cpu_operator_cost per grouping column per tuple for
2869  * grouping comparisons, plus cpu_tuple_cost per tuple for general
2870  * overhead.
2871  *
2872  * XXX this neglects costs of spooling the data to disk when it overflows
2873  * work_mem. Sooner or later that should get accounted for.
2874  */
2875  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
2876  total_cost += cpu_tuple_cost * input_tuples;
2877 
2878  path->rows = input_tuples;
2879  path->startup_cost = startup_cost;
2880  path->total_cost = total_cost;
2881 }
List * args
Definition: primnodes.h:493
Expr * aggfilter
Definition: primnodes.h:494
Oid winfnoid
Definition: primnodes.h:489

References add_function_cost(), WindowFunc::aggfilter, WindowFunc::args, cost_qual_eval_node(), cpu_operator_cost, cpu_tuple_cost, lfirst_node, QualCost::per_tuple, Path::rows, QualCost::startup, Path::startup_cost, Path::total_cost, and WindowFunc::winfnoid.

Referenced by create_windowagg_path().

◆ extract_nonindex_conditions()

static List * extract_nonindex_conditions ( List qual_clauses,
List indexclauses 
)
static

Definition at line 810 of file costsize.c.

811 {
812  List *result = NIL;
813  ListCell *lc;
814 
815  foreach(lc, qual_clauses)
816  {
817  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
818 
819  if (rinfo->pseudoconstant)
820  continue; /* we may drop pseudoconstants here */
821  if (is_redundant_with_indexclauses(rinfo, indexclauses))
822  continue; /* dup or derived from same EquivalenceClass */
823  /* ... skip the predicate proof attempt createplan.c will try ... */
824  result = lappend(result, rinfo);
825  }
826  return result;
827 }
bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
Definition: equivclass.c:3159

References is_redundant_with_indexclauses(), lappend(), lfirst_node, and NIL.

Referenced by cost_index().

◆ final_cost_hashjoin()

void final_cost_hashjoin ( PlannerInfo root,
HashPath path,
JoinCostWorkspace workspace,
JoinPathExtraData extra 
)

Definition at line 3909 of file costsize.c.

3912 {
3913  Path *outer_path = path->jpath.outerjoinpath;
3914  Path *inner_path = path->jpath.innerjoinpath;
3915  double outer_path_rows = outer_path->rows;
3916  double inner_path_rows = inner_path->rows;
3917  double inner_path_rows_total = workspace->inner_rows_total;
3918  List *hashclauses = path->path_hashclauses;
3919  Cost startup_cost = workspace->startup_cost;
3920  Cost run_cost = workspace->run_cost;
3921  int numbuckets = workspace->numbuckets;
3922  int numbatches = workspace->numbatches;
3923  Cost cpu_per_tuple;
3924  QualCost hash_qual_cost;
3925  QualCost qp_qual_cost;
3926  double hashjointuples;
3927  double virtualbuckets;
3928  Selectivity innerbucketsize;
3929  Selectivity innermcvfreq;
3930  ListCell *hcl;
3931 
3932  /* Mark the path with the correct row estimate */
3933  if (path->jpath.path.param_info)
3934  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3935  else
3936  path->jpath.path.rows = path->jpath.path.parent->rows;
3937 
3938  /* For partial paths, scale row estimate. */
3939  if (path->jpath.path.parallel_workers > 0)
3940  {
3941  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3942 
3943  path->jpath.path.rows =
3944  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3945  }
3946 
3947  /*
3948  * We could include disable_cost in the preliminary estimate, but that
3949  * would amount to optimizing for the case where the join method is
3950  * disabled, which doesn't seem like the way to bet.
3951  */
3952  if (!enable_hashjoin)
3953  startup_cost += disable_cost;
3954 
3955  /* mark the path with estimated # of batches */
3956  path->num_batches = numbatches;
3957 
3958  /* store the total number of tuples (sum of partial row estimates) */
3959  path->inner_rows_total = inner_path_rows_total;
3960 
3961  /* and compute the number of "virtual" buckets in the whole join */
3962  virtualbuckets = (double) numbuckets * (double) numbatches;
3963 
3964  /*
3965  * Determine bucketsize fraction and MCV frequency for the inner relation.
3966  * We use the smallest bucketsize or MCV frequency estimated for any
3967  * individual hashclause; this is undoubtedly conservative.
3968  *
3969  * BUT: if inner relation has been unique-ified, we can assume it's good
3970  * for hashing. This is important both because it's the right answer, and
3971  * because we avoid contaminating the cache with a value that's wrong for
3972  * non-unique-ified paths.
3973  */
3974  if (IsA(inner_path, UniquePath))
3975  {
3976  innerbucketsize = 1.0 / virtualbuckets;
3977  innermcvfreq = 0.0;
3978  }
3979  else
3980  {
3981  innerbucketsize = 1.0;
3982  innermcvfreq = 1.0;
3983  foreach(hcl, hashclauses)
3984  {
3985  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
3986  Selectivity thisbucketsize;
3987  Selectivity thismcvfreq;
3988 
3989  /*
3990  * First we have to figure out which side of the hashjoin clause
3991  * is the inner side.
3992  *
3993  * Since we tend to visit the same clauses over and over when
3994  * planning a large query, we cache the bucket stats estimates in
3995  * the RestrictInfo node to avoid repeated lookups of statistics.
3996  */
3997  if (bms_is_subset(restrictinfo->right_relids,
3998  inner_path->parent->relids))
3999  {
4000  /* righthand side is inner */
4001  thisbucketsize = restrictinfo->right_bucketsize;
4002  if (thisbucketsize < 0)
4003  {
4004  /* not cached yet */
4006  get_rightop(restrictinfo->clause),
4007  virtualbuckets,
4008  &restrictinfo->right_mcvfreq,
4009  &restrictinfo->right_bucketsize);
4010  thisbucketsize = restrictinfo->right_bucketsize;
4011  }
4012  thismcvfreq = restrictinfo->right_mcvfreq;
4013  }
4014  else
4015  {
4016  Assert(bms_is_subset(restrictinfo->left_relids,
4017  inner_path->parent->relids));
4018  /* lefthand side is inner */
4019  thisbucketsize = restrictinfo->left_bucketsize;
4020  if (thisbucketsize < 0)
4021  {
4022  /* not cached yet */
4024  get_leftop(restrictinfo->clause),
4025  virtualbuckets,
4026  &restrictinfo->left_mcvfreq,
4027  &restrictinfo->left_bucketsize);
4028  thisbucketsize = restrictinfo->left_bucketsize;
4029  }
4030  thismcvfreq = restrictinfo->left_mcvfreq;
4031  }
4032 
4033  if (innerbucketsize > thisbucketsize)
4034  innerbucketsize = thisbucketsize;
4035  if (innermcvfreq > thismcvfreq)
4036  innermcvfreq = thismcvfreq;
4037  }
4038  }
4039 
4040  /*
4041  * If the bucket holding the inner MCV would exceed hash_mem, we don't
4042  * want to hash unless there is really no other alternative, so apply
4043  * disable_cost. (The executor normally copes with excessive memory usage
4044  * by splitting batches, but obviously it cannot separate equal values
4045  * that way, so it will be unable to drive the batch size below hash_mem
4046  * when this is true.)
4047  */
4048  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
4049  inner_path->pathtarget->width) > get_hash_memory_limit())
4050  startup_cost += disable_cost;
4051 
4052  /*
4053  * Compute cost of the hashquals and qpquals (other restriction clauses)
4054  * separately.
4055  */
4056  cost_qual_eval(&hash_qual_cost, hashclauses, root);
4057  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
4058  qp_qual_cost.startup -= hash_qual_cost.startup;
4059  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4060 
4061  /* CPU costs */
4062 
4063  if (path->jpath.jointype == JOIN_SEMI ||
4064  path->jpath.jointype == JOIN_ANTI ||
4065  extra->inner_unique)
4066  {
4067  double outer_matched_rows;
4068  Selectivity inner_scan_frac;
4069 
4070  /*
4071  * With a SEMI or ANTI join, or if the innerrel is known unique, the
4072  * executor will stop after the first match.
4073  *
4074  * For an outer-rel row that has at least one match, we can expect the
4075  * bucket scan to stop after a fraction 1/(match_count+1) of the
4076  * bucket's rows, if the matches are evenly distributed. Since they
4077  * probably aren't quite evenly distributed, we apply a fuzz factor of
4078  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
4079  * to clamp inner_scan_frac to at most 1.0; but since match_count is
4080  * at least 1, no such clamp is needed now.)
4081  */
4082  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
4083  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4084 
4085  startup_cost += hash_qual_cost.startup;
4086  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4087  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
4088 
4089  /*
4090  * For unmatched outer-rel rows, the picture is quite a lot different.
4091  * In the first place, there is no reason to assume that these rows
4092  * preferentially hit heavily-populated buckets; instead assume they
4093  * are uncorrelated with the inner distribution and so they see an
4094  * average bucket size of inner_path_rows / virtualbuckets. In the
4095  * second place, it seems likely that they will have few if any exact
4096  * hash-code matches and so very few of the tuples in the bucket will
4097  * actually require eval of the hash quals. We don't have any good
4098  * way to estimate how many will, but for the moment assume that the
4099  * effective cost per bucket entry is one-tenth what it is for
4100  * matchable tuples.
4101  */
4102  run_cost += hash_qual_cost.per_tuple *
4103  (outer_path_rows - outer_matched_rows) *
4104  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
4105 
4106  /* Get # of tuples that will pass the basic join */
4107  if (path->jpath.jointype == JOIN_ANTI)
4108  hashjointuples = outer_path_rows - outer_matched_rows;
4109  else
4110  hashjointuples = outer_matched_rows;
4111  }
4112  else
4113  {
4114  /*
4115  * The number of tuple comparisons needed is the number of outer
4116  * tuples times the typical number of tuples in a hash bucket, which
4117  * is the inner relation size times its bucketsize fraction. At each
4118  * one, we need to evaluate the hashjoin quals. But actually,
4119  * charging the full qual eval cost at each tuple is pessimistic,
4120  * since we don't evaluate the quals unless the hash values match
4121  * exactly. For lack of a better idea, halve the cost estimate to
4122  * allow for that.
4123  */
4124  startup_cost += hash_qual_cost.startup;
4125  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4126  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
4127 
4128  /*
4129  * Get approx # tuples passing the hashquals. We use
4130  * approx_tuple_count here because we need an estimate done with
4131  * JOIN_INNER semantics.
4132  */
4133  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
4134  }
4135 
4136  /*
4137  * For each tuple that gets through the hashjoin proper, we charge
4138  * cpu_tuple_cost plus the cost of evaluating additional restriction
4139  * clauses that are to be applied at the join. (This is pessimistic since
4140  * not all of the quals may get evaluated at each tuple.)
4141  */
4142  startup_cost += qp_qual_cost.startup;
4143  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4144  run_cost += cpu_per_tuple * hashjointuples;
4145 
4146  /* tlist eval costs are paid per output row, not per tuple scanned */
4147  startup_cost += path->jpath.path.pathtarget->cost.startup;
4148  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4149 
4150  path->jpath.path.startup_cost = startup_cost;
4151  path->jpath.path.total_cost = startup_cost + run_cost;
4152 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:316
bool enable_hashjoin
Definition: costsize.c:147
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4932
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:93
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:81
void estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
Definition: selfuncs.c:3767
List * path_hashclauses
Definition: pathnodes.h:2026
Cardinality inner_rows_total
Definition: pathnodes.h:2028
int num_batches
Definition: pathnodes.h:2027
JoinPath jpath
Definition: pathnodes.h:2025
Cardinality inner_rows_total
Definition: pathnodes.h:3140
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:3019
JoinType jointype
Definition: pathnodes.h:1943
List * joinrestrictinfo
Definition: pathnodes.h:1951

References approx_tuple_count(), Assert(), bms_is_subset(), clamp_row_est(), RestrictInfo::clause, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_hashjoin, estimate_hash_bucket_stats(), get_hash_memory_limit(), get_leftop(), get_parallel_divisor(), get_rightop(), HashPath::inner_rows_total, JoinCostWorkspace::inner_rows_total, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, IsA, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, HashPath::jpath, lfirst_node, SemiAntiJoinFactors::match_count, HashPath::num_batches, JoinCostWorkspace::numbatches, JoinCostWorkspace::numbuckets, SemiAntiJoinFactors::outer_match_frac, JoinPath::outerjoinpath, HashPath::path_hashclauses, QualCost::per_tuple, relation_byte_size(), Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, QualCost::startup, and JoinCostWorkspace::startup_cost.

Referenced by create_hashjoin_path().

◆ final_cost_mergejoin()

void final_cost_mergejoin ( PlannerInfo root,
MergePath path,
JoinCostWorkspace workspace,
JoinPathExtraData extra 
)

Definition at line 3473 of file costsize.c.

3476 {
3477  Path *outer_path = path->jpath.outerjoinpath;
3478  Path *inner_path = path->jpath.innerjoinpath;
3479  double inner_path_rows = inner_path->rows;
3480  List *mergeclauses = path->path_mergeclauses;
3481  List *innersortkeys = path->innersortkeys;
3482  Cost startup_cost = workspace->startup_cost;
3483  Cost run_cost = workspace->run_cost;
3484  Cost inner_run_cost = workspace->inner_run_cost;
3485  double outer_rows = workspace->outer_rows;
3486  double inner_rows = workspace->inner_rows;
3487  double outer_skip_rows = workspace->outer_skip_rows;
3488  double inner_skip_rows = workspace->inner_skip_rows;
3489  Cost cpu_per_tuple,
3490  bare_inner_cost,
3491  mat_inner_cost;
3492  QualCost merge_qual_cost;
3493  QualCost qp_qual_cost;
3494  double mergejointuples,
3495  rescannedtuples;
3496  double rescanratio;
3497 
3498  /* Protect some assumptions below that rowcounts aren't zero */
3499  if (inner_path_rows <= 0)
3500  inner_path_rows = 1;
3501 
3502  /* Mark the path with the correct row estimate */
3503  if (path->jpath.path.param_info)
3504  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3505  else
3506  path->jpath.path.rows = path->jpath.path.parent->rows;
3507 
3508  /* For partial paths, scale row estimate. */
3509  if (path->jpath.path.parallel_workers > 0)
3510  {
3511  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3512 
3513  path->jpath.path.rows =
3514  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3515  }
3516 
3517  /*
3518  * We could include disable_cost in the preliminary estimate, but that
3519  * would amount to optimizing for the case where the join method is
3520  * disabled, which doesn't seem like the way to bet.
3521  */
3522  if (!enable_mergejoin)
3523  startup_cost += disable_cost;
3524 
3525  /*
3526  * Compute cost of the mergequals and qpquals (other restriction clauses)
3527  * separately.
3528  */
3529  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
3530  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3531  qp_qual_cost.startup -= merge_qual_cost.startup;
3532  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
3533 
3534  /*
3535  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3536  * executor will stop scanning for matches after the first match. When
3537  * all the joinclauses are merge clauses, this means we don't ever need to
3538  * back up the merge, and so we can skip mark/restore overhead.
3539  */
3540  if ((path->jpath.jointype == JOIN_SEMI ||
3541  path->jpath.jointype == JOIN_ANTI ||
3542  extra->inner_unique) &&
3545  path->skip_mark_restore = true;
3546  else
3547  path->skip_mark_restore = false;
3548 
3549  /*
3550  * Get approx # tuples passing the mergequals. We use approx_tuple_count
3551  * here because we need an estimate done with JOIN_INNER semantics.
3552  */
3553  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
3554 
3555  /*
3556  * When there are equal merge keys in the outer relation, the mergejoin
3557  * must rescan any matching tuples in the inner relation. This means
3558  * re-fetching inner tuples; we have to estimate how often that happens.
3559  *
3560  * For regular inner and outer joins, the number of re-fetches can be
3561  * estimated approximately as size of merge join output minus size of
3562  * inner relation. Assume that the distinct key values are 1, 2, ..., and
3563  * denote the number of values of each key in the outer relation as m1,
3564  * m2, ...; in the inner relation, n1, n2, ... Then we have
3565  *
3566  * size of join = m1 * n1 + m2 * n2 + ...
3567  *
3568  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
3569  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
3570  * relation
3571  *
3572  * This equation works correctly for outer tuples having no inner match
3573  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
3574  * are effectively subtracting those from the number of rescanned tuples,
3575  * when we should not. Can we do better without expensive selectivity
3576  * computations?
3577  *
3578  * The whole issue is moot if we are working from a unique-ified outer
3579  * input, or if we know we don't need to mark/restore at all.
3580  */
3581  if (IsA(outer_path, UniquePath) || path->skip_mark_restore)
3582  rescannedtuples = 0;
3583  else
3584  {
3585  rescannedtuples = mergejointuples - inner_path_rows;
3586  /* Must clamp because of possible underestimate */
3587  if (rescannedtuples < 0)
3588  rescannedtuples = 0;
3589  }
3590 
3591  /*
3592  * We'll inflate various costs this much to account for rescanning. Note
3593  * that this is to be multiplied by something involving inner_rows, or
3594  * another number related to the portion of the inner rel we'll scan.
3595  */
3596  rescanratio = 1.0 + (rescannedtuples / inner_rows);
3597 
3598  /*
3599  * Decide whether we want to materialize the inner input to shield it from
3600  * mark/restore and performing re-fetches. Our cost model for regular
3601  * re-fetches is that a re-fetch costs the same as an original fetch,
3602  * which is probably an overestimate; but on the other hand we ignore the
3603  * bookkeeping costs of mark/restore. Not clear if it's worth developing
3604  * a more refined model. So we just need to inflate the inner run cost by
3605  * rescanratio.
3606  */
3607  bare_inner_cost = inner_run_cost * rescanratio;
3608 
3609  /*
3610  * When we interpose a Material node the re-fetch cost is assumed to be
3611  * just cpu_operator_cost per tuple, independently of the underlying
3612  * plan's cost; and we charge an extra cpu_operator_cost per original
3613  * fetch as well. Note that we're assuming the materialize node will
3614  * never spill to disk, since it only has to remember tuples back to the
3615  * last mark. (If there are a huge number of duplicates, our other cost
3616  * factors will make the path so expensive that it probably won't get
3617  * chosen anyway.) So we don't use cost_rescan here.
3618  *
3619  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3620  * of the generated Material node.
3621  */
3622  mat_inner_cost = inner_run_cost +
3623  cpu_operator_cost * inner_rows * rescanratio;
3624 
3625  /*
3626  * If we don't need mark/restore at all, we don't need materialization.
3627  */
3628  if (path->skip_mark_restore)
3629  path->materialize_inner = false;
3630 
3631  /*
3632  * Prefer materializing if it looks cheaper, unless the user has asked to
3633  * suppress materialization.
3634  */
3635  else if (enable_material && mat_inner_cost < bare_inner_cost)
3636  path->materialize_inner = true;
3637 
3638  /*
3639  * Even if materializing doesn't look cheaper, we *must* do it if the
3640  * inner path is to be used directly (without sorting) and it doesn't
3641  * support mark/restore.
3642  *
3643  * Since the inner side must be ordered, and only Sorts and IndexScans can
3644  * create order to begin with, and they both support mark/restore, you
3645  * might think there's no problem --- but you'd be wrong. Nestloop and
3646  * merge joins can *preserve* the order of their inputs, so they can be
3647  * selected as the input of a mergejoin, and they don't support
3648  * mark/restore at present.
3649  *
3650  * We don't test the value of enable_material here, because
3651  * materialization is required for correctness in this case, and turning
3652  * it off does not entitle us to deliver an invalid plan.
3653  */
3654  else if (innersortkeys == NIL &&
3655  !ExecSupportsMarkRestore(inner_path))
3656  path->materialize_inner = true;
3657 
3658  /*
3659  * Also, force materializing if the inner path is to be sorted and the
3660  * sort is expected to spill to disk. This is because the final merge
3661  * pass can be done on-the-fly if it doesn't have to support mark/restore.
3662  * We don't try to adjust the cost estimates for this consideration,
3663  * though.
3664  *
3665  * Since materialization is a performance optimization in this case,
3666  * rather than necessary for correctness, we skip it if enable_material is
3667  * off.
3668  */
3669  else if (enable_material && innersortkeys != NIL &&
3670  relation_byte_size(inner_path_rows,
3671  inner_path->pathtarget->width) >
3672  (work_mem * 1024L))
3673  path->materialize_inner = true;
3674  else
3675  path->materialize_inner = false;
3676 
3677  /* Charge the right incremental cost for the chosen case */
3678  if (path->materialize_inner)
3679  run_cost += mat_inner_cost;
3680  else
3681  run_cost += bare_inner_cost;
3682 
3683  /* CPU costs */
3684 
3685  /*
3686  * The number of tuple comparisons needed is approximately number of outer
3687  * rows plus number of inner rows plus number of rescanned tuples (can we
3688  * refine this?). At each one, we need to evaluate the mergejoin quals.
3689  */
3690  startup_cost += merge_qual_cost.startup;
3691  startup_cost += merge_qual_cost.per_tuple *
3692  (outer_skip_rows + inner_skip_rows * rescanratio);
3693  run_cost += merge_qual_cost.per_tuple *
3694  ((outer_rows - outer_skip_rows) +
3695  (inner_rows - inner_skip_rows) * rescanratio);
3696 
3697  /*
3698  * For each tuple that gets through the mergejoin proper, we charge
3699  * cpu_tuple_cost plus the cost of evaluating additional restriction
3700  * clauses that are to be applied at the join. (This is pessimistic since
3701  * not all of the quals may get evaluated at each tuple.)
3702  *
3703  * Note: we could adjust for SEMI/ANTI joins skipping some qual
3704  * evaluations here, but it's probably not worth the trouble.
3705  */
3706  startup_cost += qp_qual_cost.startup;
3707  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3708  run_cost += cpu_per_tuple * mergejointuples;
3709 
3710  /* tlist eval costs are paid per output row, not per tuple scanned */
3711  startup_cost += path->jpath.path.pathtarget->cost.startup;
3712  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3713 
3714  path->jpath.path.startup_cost = startup_cost;
3715  path->jpath.path.total_cost = startup_cost + run_cost;
3716 }
bool enable_material
Definition: costsize.c:144
bool enable_mergejoin
Definition: costsize.c:146
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:419
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Cardinality inner_rows
Definition: pathnodes.h:3133
Cardinality outer_rows
Definition: pathnodes.h:3132
Cardinality inner_skip_rows
Definition: pathnodes.h:3135
Cardinality outer_skip_rows
Definition: pathnodes.h:3134
bool skip_mark_restore
Definition: pathnodes.h:2010
List * innersortkeys
Definition: pathnodes.h:2009
JoinPath jpath
Definition: pathnodes.h:2006
bool materialize_inner
Definition: pathnodes.h:2011
List * path_mergeclauses
Definition: pathnodes.h:2007

References approx_tuple_count(), clamp_row_est(), cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, disable_cost, enable_material, enable_mergejoin, ExecSupportsMarkRestore(), get_parallel_divisor(), if(), JoinCostWorkspace::inner_rows, JoinCostWorkspace::inner_run_cost, JoinCostWorkspace::inner_skip_rows, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, MergePath::innersortkeys, IsA, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, MergePath::jpath, list_length(), MergePath::materialize_inner, NIL, JoinCostWorkspace::outer_rows, JoinCostWorkspace::outer_skip_rows, JoinPath::outerjoinpath, MergePath::path_mergeclauses, QualCost::per_tuple, relation_byte_size(), Path::rows, JoinCostWorkspace::run_cost, MergePath::skip_mark_restore, QualCost::startup, JoinCostWorkspace::startup_cost, and work_mem.

Referenced by create_mergejoin_path().

◆ final_cost_nestloop()

void final_cost_nestloop ( PlannerInfo root,
NestPath path,
JoinCostWorkspace workspace,
JoinPathExtraData extra 
)

Definition at line 3037 of file costsize.c.

3040 {
3041  Path *outer_path = path->jpath.outerjoinpath;
3042  Path *inner_path = path->jpath.innerjoinpath;
3043  double outer_path_rows = outer_path->rows;
3044  double inner_path_rows = inner_path->rows;
3045  Cost startup_cost = workspace->startup_cost;
3046  Cost run_cost = workspace->run_cost;
3047  Cost cpu_per_tuple;
3048  QualCost restrict_qual_cost;
3049  double ntuples;
3050 
3051  /* Protect some assumptions below that rowcounts aren't zero */
3052  if (outer_path_rows <= 0)
3053  outer_path_rows = 1;
3054  if (inner_path_rows <= 0)
3055  inner_path_rows = 1;
3056  /* Mark the path with the correct row estimate */
3057  if (path->jpath.path.param_info)
3058  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3059  else
3060  path->jpath.path.rows = path->jpath.path.parent->rows;
3061 
3062  /* For partial paths, scale row estimate. */
3063  if (path->jpath.path.parallel_workers > 0)
3064  {
3065  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3066 
3067  path->jpath.path.rows =
3068  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3069  }
3070 
3071  /*
3072  * We could include disable_cost in the preliminary estimate, but that
3073  * would amount to optimizing for the case where the join method is
3074  * disabled, which doesn't seem like the way to bet.
3075  */
3076  if (!enable_nestloop)
3077  startup_cost += disable_cost;
3078 
3079  /* cost of inner-relation source data (we already dealt with outer rel) */
3080 
3081  if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
3082  extra->inner_unique)
3083  {
3084  /*
3085  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3086  * executor will stop after the first match.
3087  */
3088  Cost inner_run_cost = workspace->inner_run_cost;
3089  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
3090  double outer_matched_rows;
3091  double outer_unmatched_rows;
3092  Selectivity inner_scan_frac;
3093 
3094  /*
3095  * For an outer-rel row that has at least one match, we can expect the
3096  * inner scan to stop after a fraction 1/(match_count+1) of the inner
3097  * rows, if the matches are evenly distributed. Since they probably
3098  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
3099  * that fraction. (If we used a larger fuzz factor, we'd have to
3100  * clamp inner_scan_frac to at most 1.0; but since match_count is at
3101  * least 1, no such clamp is needed now.)
3102  */
3103  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3104  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
3105  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3106 
3107  /*
3108  * Compute number of tuples processed (not number emitted!). First,
3109  * account for successfully-matched outer rows.
3110  */
3111  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
3112 
3113  /*
3114  * Now we need to estimate the actual costs of scanning the inner
3115  * relation, which may be quite a bit less than N times inner_run_cost
3116  * due to early scan stops. We consider two cases. If the inner path
3117  * is an indexscan using all the joinquals as indexquals, then an
3118  * unmatched outer row results in an indexscan returning no rows,
3119  * which is probably quite cheap. Otherwise, the executor will have
3120  * to scan the whole inner rel for an unmatched row; not so cheap.
3121  */
3122  if (has_indexed_join_quals(path))
3123  {
3124  /*
3125  * Successfully-matched outer rows will only require scanning
3126  * inner_scan_frac of the inner relation. In this case, we don't
3127  * need to charge the full inner_run_cost even when that's more
3128  * than inner_rescan_run_cost, because we can assume that none of
3129  * the inner scans ever scan the whole inner relation. So it's
3130  * okay to assume that all the inner scan executions can be
3131  * fractions of the full cost, even if materialization is reducing
3132  * the rescan cost. At this writing, it's impossible to get here
3133  * for a materialized inner scan, so inner_run_cost and
3134  * inner_rescan_run_cost will be the same anyway; but just in
3135  * case, use inner_run_cost for the first matched tuple and
3136  * inner_rescan_run_cost for additional ones.
3137  */
3138  run_cost += inner_run_cost * inner_scan_frac;
3139  if (outer_matched_rows > 1)
3140  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
3141 
3142  /*
3143  * Add the cost of inner-scan executions for unmatched outer rows.
3144  * We estimate this as the same cost as returning the first tuple
3145  * of a nonempty scan. We consider that these are all rescans,
3146  * since we used inner_run_cost once already.
3147  */
3148  run_cost += outer_unmatched_rows *
3149  inner_rescan_run_cost / inner_path_rows;
3150 
3151  /*
3152  * We won't be evaluating any quals at all for unmatched rows, so
3153  * don't add them to ntuples.
3154  */
3155  }
3156  else
3157  {
3158  /*
3159  * Here, a complicating factor is that rescans may be cheaper than
3160  * first scans. If we never scan all the way to the end of the
3161  * inner rel, it might be (depending on the plan type) that we'd
3162  * never pay the whole inner first-scan run cost. However it is
3163  * difficult to estimate whether that will happen (and it could
3164  * not happen if there are any unmatched outer rows!), so be
3165  * conservative and always charge the whole first-scan cost once.
3166  * We consider this charge to correspond to the first unmatched
3167  * outer row, unless there isn't one in our estimate, in which
3168  * case blame it on the first matched row.
3169  */
3170 
3171  /* First, count all unmatched join tuples as being processed */
3172  ntuples += outer_unmatched_rows * inner_path_rows;
3173 
3174  /* Now add the forced full scan, and decrement appropriate count */
3175  run_cost += inner_run_cost;
3176  if (outer_unmatched_rows >= 1)
3177  outer_unmatched_rows -= 1;
3178  else
3179  outer_matched_rows -= 1;
3180 
3181  /* Add inner run cost for additional outer tuples having matches */
3182  if (outer_matched_rows > 0)
3183  run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
3184 
3185  /* Add inner run cost for additional unmatched outer tuples */
3186  if (outer_unmatched_rows > 0)
3187  run_cost += outer_unmatched_rows * inner_rescan_run_cost;
3188  }
3189  }
3190  else
3191  {
3192  /* Normal-case source costs were included in preliminary estimate */
3193 
3194  /* Compute number of tuples processed (not number emitted!) */
3195  ntuples = outer_path_rows * inner_path_rows;
3196  }
3197 
3198  /* CPU costs */
3199  cost_qual_eval(&restrict_qual_cost, path->jpath.joinrestrictinfo, root);
3200  startup_cost += restrict_qual_cost.startup;
3201  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
3202  run_cost += cpu_per_tuple * ntuples;
3203 
3204  /* tlist eval costs are paid per output row, not per tuple scanned */
3205  startup_cost += path->jpath.path.pathtarget->cost.startup;
3206  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3207 
3208  path->jpath.path.startup_cost = startup_cost;
3209  path->jpath.path.total_cost = startup_cost + run_cost;
3210 }
static bool has_indexed_join_quals(NestPath *path)
Definition: costsize.c:4839
bool enable_nestloop
Definition: costsize.c:143
Cost inner_rescan_run_cost
Definition: pathnodes.h:3129
JoinPath jpath
Definition: pathnodes.h:1966

References clamp_row_est(), cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_nestloop, get_parallel_divisor(), has_indexed_join_quals(), JoinCostWorkspace::inner_rescan_run_cost, JoinCostWorkspace::inner_run_cost, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, NestPath::jpath, SemiAntiJoinFactors::match_count, SemiAntiJoinFactors::outer_match_frac, JoinPath::outerjoinpath, QualCost::per_tuple, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, QualCost::startup, and JoinCostWorkspace::startup_cost.

Referenced by create_nestloop_path().

◆ get_foreign_key_join_selectivity()

static Selectivity get_foreign_key_join_selectivity ( PlannerInfo root,
Relids  outer_relids,
Relids  inner_relids,
SpecialJoinInfo sjinfo,
List **  restrictlist 
)
static

Definition at line 5290 of file costsize.c.

5295 {
5296  Selectivity fkselec = 1.0;
5297  JoinType jointype = sjinfo->jointype;
5298  List *worklist = *restrictlist;
5299  ListCell *lc;
5300 
5301  /* Consider each FK constraint that is known to match the query */
5302  foreach(lc, root->fkey_list)
5303  {
5304  ForeignKeyOptInfo *fkinfo = (ForeignKeyOptInfo *) lfirst(lc);
5305  bool ref_is_outer;
5306  List *removedlist;
5307  ListCell *cell;
5308 
5309  /*
5310  * This FK is not relevant unless it connects a baserel on one side of
5311  * this join to a baserel on the other side.
5312  */
5313  if (bms_is_member(fkinfo->con_relid, outer_relids) &&
5314  bms_is_member(fkinfo->ref_relid, inner_relids))
5315  ref_is_outer = false;
5316  else if (bms_is_member(fkinfo->ref_relid, outer_relids) &&
5317  bms_is_member(fkinfo->con_relid, inner_relids))
5318  ref_is_outer = true;
5319  else
5320  continue;
5321 
5322  /*
5323  * If we're dealing with a semi/anti join, and the FK's referenced
5324  * relation is on the outside, then knowledge of the FK doesn't help
5325  * us figure out what we need to know (which is the fraction of outer
5326  * rows that have matches). On the other hand, if the referenced rel
5327  * is on the inside, then all outer rows must have matches in the
5328  * referenced table (ignoring nulls). But any restriction or join
5329  * clauses that filter that table will reduce the fraction of matches.
5330  * We can account for restriction clauses, but it's too hard to guess
5331  * how many table rows would get through a join that's inside the RHS.
5332  * Hence, if either case applies, punt and ignore the FK.
5333  */
5334  if ((jointype == JOIN_SEMI || jointype == JOIN_ANTI) &&
5335  (ref_is_outer || bms_membership(inner_relids) != BMS_SINGLETON))
5336  continue;
5337 
5338  /*
5339  * Modify the restrictlist by removing clauses that match the FK (and
5340  * putting them into removedlist instead). It seems unsafe to modify
5341  * the originally-passed List structure, so we make a shallow copy the
5342  * first time through.
5343  */
5344  if (worklist == *restrictlist)
5345  worklist = list_copy(worklist);
5346 
5347  removedlist = NIL;
5348  foreach(cell, worklist)
5349  {
5350  RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
5351  bool remove_it = false;
5352  int i;
5353 
5354  /* Drop this clause if it matches any column of the FK */
5355  for (i = 0; i < fkinfo->nkeys; i++)
5356  {
5357  if (rinfo->parent_ec)
5358  {
5359  /*
5360  * EC-derived clauses can only match by EC. It is okay to
5361  * consider any clause derived from the same EC as
5362  * matching the FK: even if equivclass.c chose to generate
5363  * a clause equating some other pair of Vars, it could
5364  * have generated one equating the FK's Vars. So for
5365  * purposes of estimation, we can act as though it did so.
5366  *
5367  * Note: checking parent_ec is a bit of a cheat because
5368  * there are EC-derived clauses that don't have parent_ec
5369  * set; but such clauses must compare expressions that
5370  * aren't just Vars, so they cannot match the FK anyway.
5371  */
5372  if (fkinfo->eclass[i] == rinfo->parent_ec)
5373  {
5374  remove_it = true;
5375  break;
5376  }
5377  }
5378  else
5379  {
5380  /*
5381  * Otherwise, see if rinfo was previously matched to FK as
5382  * a "loose" clause.
5383  */
5384  if (list_member_ptr(fkinfo->rinfos[i], rinfo))
5385  {
5386  remove_it = true;
5387  break;
5388  }
5389  }
5390  }
5391  if (remove_it)
5392  {
5393  worklist = foreach_delete_current(worklist, cell);
5394  removedlist = lappend(removedlist, rinfo);
5395  }
5396  }
5397 
5398  /*
5399  * If we failed to remove all the matching clauses we expected to
5400  * find, chicken out and ignore this FK; applying its selectivity
5401  * might result in double-counting. Put any clauses we did manage to
5402  * remove back into the worklist.
5403  *
5404  * Since the matching clauses are known not outerjoin-delayed, they
5405  * would normally have appeared in the initial joinclause list. If we
5406  * didn't find them, there are two possibilities:
5407  *
5408  * 1. If the FK match is based on an EC that is ec_has_const, it won't
5409  * have generated any join clauses at all. We discount such ECs while
5410  * checking to see if we have "all" the clauses. (Below, we'll adjust
5411  * the selectivity estimate for this case.)
5412  *
5413  * 2. The clauses were matched to some other FK in a previous
5414  * iteration of this loop, and thus removed from worklist. (A likely
5415  * case is that two FKs are matched to the same EC; there will be only
5416  * one EC-derived clause in the initial list, so the first FK will
5417  * consume it.) Applying both FKs' selectivity independently risks
5418  * underestimating the join size; in particular, this would undo one
5419  * of the main things that ECs were invented for, namely to avoid
5420  * double-counting the selectivity of redundant equality conditions.
5421  * Later we might think of a reasonable way to combine the estimates,
5422  * but for now, just punt, since this is a fairly uncommon situation.
5423  */
5424  if (removedlist == NIL ||
5425  list_length(removedlist) !=
5426  (fkinfo->nmatched_ec - fkinfo->nconst_ec + fkinfo->nmatched_ri))
5427  {
5428  worklist = list_concat(worklist, removedlist);
5429  continue;
5430  }
5431 
5432  /*
5433  * Finally we get to the payoff: estimate selectivity using the
5434  * knowledge that each referencing row will match exactly one row in
5435  * the referenced table.
5436  *
5437  * XXX that's not true in the presence of nulls in the referencing
5438  * column(s), so in principle we should derate the estimate for those.
5439  * However (1) if there are any strict restriction clauses for the
5440  * referencing column(s) elsewhere in the query, derating here would
5441  * be double-counting the null fraction, and (2) it's not very clear
5442  * how to combine null fractions for multiple referencing columns. So
5443  * we do nothing for now about correcting for nulls.
5444  *
5445  * XXX another point here is that if either side of an FK constraint
5446  * is an inheritance parent, we estimate as though the constraint
5447  * covers all its children as well. This is not an unreasonable
5448  * assumption for a referencing table, ie the user probably applied
5449  * identical constraints to all child tables (though perhaps we ought
5450  * to check that). But it's not possible to have done that for a
5451  * referenced table. Fortunately, precisely because that doesn't
5452  * work, it is uncommon in practice to have an FK referencing a parent
5453  * table. So, at least for now, disregard inheritance here.
5454  */
5455  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
5456  {
5457  /*
5458  * For JOIN_SEMI and JOIN_ANTI, we only get here when the FK's
5459  * referenced table is exactly the inside of the join. The join
5460  * selectivity is defined as the fraction of LHS rows that have
5461  * matches. The FK implies that every LHS row has a match *in the
5462  * referenced table*; but any restriction clauses on it will
5463  * reduce the number of matches. Hence we take the join
5464  * selectivity as equal to the selectivity of the table's
5465  * restriction clauses, which is rows / tuples; but we must guard
5466  * against tuples == 0.
5467  */
5468  RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5469  double ref_tuples = Max(ref_rel->tuples, 1.0);
5470 
5471  fkselec *= ref_rel->rows / ref_tuples;
5472  }
5473  else
5474  {
5475  /*
5476  * Otherwise, selectivity is exactly 1/referenced-table-size; but
5477  * guard against tuples == 0. Note we should use the raw table
5478  * tuple count, not any estimate of its filtered or joined size.
5479  */
5480  RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5481  double ref_tuples = Max(ref_rel->tuples, 1.0);
5482 
5483  fkselec *= 1.0 / ref_tuples;
5484  }
5485 
5486  /*
5487  * If any of the FK columns participated in ec_has_const ECs, then
5488  * equivclass.c will have generated "var = const" restrictions for
5489  * each side of the join, thus reducing the sizes of both input
5490  * relations. Taking the fkselec at face value would amount to
5491  * double-counting the selectivity of the constant restriction for the
5492  * referencing Var. Hence, look for the restriction clause(s) that
5493  * were applied to the referencing Var(s), and divide out their
5494  * selectivity to correct for this.
5495  */
5496  if (fkinfo->nconst_ec > 0)
5497  {
5498  for (int i = 0; i < fkinfo->nkeys; i++)
5499  {
5500  EquivalenceClass *ec = fkinfo->eclass[i];
5501 
5502  if (ec && ec->ec_has_const)
5503  {
5504  EquivalenceMember *em = fkinfo->fk_eclass_member[i];
5506  em);
5507 
5508  if (rinfo)
5509  {
5510  Selectivity s0;
5511 
5512  s0 = clause_selectivity(root,
5513  (Node *) rinfo,
5514  0,
5515  jointype,
5516  sjinfo);
5517  if (s0 > 0)
5518  fkselec /= s0;
5519  }
5520  }
5521  }
5522  }
5523  }
5524 
5525  *restrictlist = worklist;
5526  CLAMP_PROBABILITY(fkselec);
5527  return fkselec;
5528 }
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:675
@ BMS_SINGLETON
Definition: bitmapset.h:74
RestrictInfo * find_derived_clause_for_ec_member(EquivalenceClass *ec, EquivalenceMember *em)
Definition: equivclass.c:2511
List * list_copy(const List *oldlist)
Definition: list.c:1572
bool list_member_ptr(const List *list, const void *datum)
Definition: list.c:681
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:388
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:360
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:63
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: pathnodes.h:1201
List * rinfos[INDEX_MAX_KEYS]
Definition: pathnodes.h:1205
struct EquivalenceMember * fk_eclass_member[INDEX_MAX_KEYS]
Definition: pathnodes.h:1203
List * fkey_list
Definition: pathnodes.h:369

References bms_is_member(), bms_membership(), BMS_SINGLETON, CLAMP_PROBABILITY, clause_selectivity(), ForeignKeyOptInfo::con_relid, EquivalenceClass::ec_has_const, ForeignKeyOptInfo::eclass, find_base_rel(), find_derived_clause_for_ec_member(), ForeignKeyOptInfo::fk_eclass_member, PlannerInfo::fkey_list, foreach_delete_current, i, JOIN_ANTI, JOIN_SEMI, SpecialJoinInfo::jointype, lappend(), lfirst, list_concat(), list_copy(), list_length(), list_member_ptr(), Max, ForeignKeyOptInfo::nconst_ec, NIL, ForeignKeyOptInfo::nkeys, ForeignKeyOptInfo::nmatched_ec, ForeignKeyOptInfo::nmatched_ri, ForeignKeyOptInfo::ref_relid, ForeignKeyOptInfo::rinfos, RelOptInfo::rows, and RelOptInfo::tuples.

Referenced by calc_joinrel_size_estimate().

◆ get_indexpath_pages()

static double get_indexpath_pages ( Path bitmapqual)
static

Definition at line 933 of file costsize.c.

934 {
935  double result = 0;
936  ListCell *l;
937 
938  if (IsA(bitmapqual, BitmapAndPath))
939  {
940  BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
941 
942  foreach(l, apath->bitmapquals)
943  {
944  result += get_indexpath_pages((Path *) lfirst(l));
945  }
946  }
947  else if (IsA(bitmapqual, BitmapOrPath))
948  {
949  BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
950 
951  foreach(l, opath->bitmapquals)
952  {
953  result += get_indexpath_pages((Path *) lfirst(l));
954  }
955  }
956  else if (IsA(bitmapqual, IndexPath))
957  {
958  IndexPath *ipath = (IndexPath *) bitmapqual;
959 
960  result = (double) ipath->indexinfo->pages;
961  }
962  else
963  elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
964 
965  return result;
966 }
BlockNumber pages
Definition: pathnodes.h:1072

References BitmapAndPath::bitmapquals, BitmapOrPath::bitmapquals, elog(), ERROR, IndexPath::indexinfo, IsA, lfirst, nodeTag, and IndexOptInfo::pages.

Referenced by compute_bitmap_pages().

◆ get_parallel_divisor()

static double get_parallel_divisor ( Path path)
static

Definition at line 6106 of file costsize.c.

6107 {
6108  double parallel_divisor = path->parallel_workers;
6109 
6110  /*
6111  * Early experience with parallel query suggests that when there is only
6112  * one worker, the leader often makes a very substantial contribution to
6113  * executing the parallel portion of the plan, but as more workers are
6114  * added, it does less and less, because it's busy reading tuples from the
6115  * workers and doing whatever non-parallel post-processing is needed. By
6116  * the time we reach 4 workers, the leader no longer makes a meaningful
6117  * contribution. Thus, for now, estimate that the leader spends 30% of
6118  * its time servicing each worker, and the remainder executing the
6119  * parallel plan.
6120  */
6122  {
6123  double leader_contribution;
6124 
6125  leader_contribution = 1.0 - (0.3 * path->parallel_workers);
6126  if (leader_contribution > 0)
6127  parallel_divisor += leader_contribution;
6128  }
6129 
6130  return parallel_divisor;
6131 }
bool parallel_leader_participation
Definition: planner.c:72

References parallel_leader_participation, and Path::parallel_workers.

Referenced by cost_append(), cost_bitmap_heap_scan(), cost_index(), cost_seqscan(), final_cost_hashjoin(), final_cost_mergejoin(), final_cost_nestloop(), and initial_cost_hashjoin().

◆ get_parameterized_baserel_size()

double get_parameterized_baserel_size ( PlannerInfo root,
RelOptInfo rel,
List param_clauses 
)

Definition at line 5018 of file costsize.c.

5020 {
5021  List *allclauses;
5022  double nrows;
5023 
5024  /*
5025  * Estimate the number of rows returned by the parameterized scan, knowing
5026  * that it will apply all the extra join clauses as well as the rel's own
5027  * restriction clauses. Note that we force the clauses to be treated as
5028  * non-join clauses during selectivity estimation.
5029  */
5030  allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
5031  nrows = rel->tuples *
5033  allclauses,
5034  rel->relid, /* do not use 0! */
5035  JOIN_INNER,
5036  NULL);
5037  nrows = clamp_row_est(nrows);
5038  /* For safety, make sure result is not more than the base estimate */
5039  if (nrows > rel->rows)
5040  nrows = rel->rows;
5041  return nrows;
5042 }

References RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), JOIN_INNER, list_concat_copy(), RelOptInfo::relid, RelOptInfo::rows, and RelOptInfo::tuples.

Referenced by get_baserel_parampathinfo().

◆ get_parameterized_joinrel_size()

double get_parameterized_joinrel_size ( PlannerInfo root,
RelOptInfo rel,
Path outer_path,
Path inner_path,
SpecialJoinInfo sjinfo,
List restrict_clauses 
)

Definition at line 5099 of file costsize.c.

5104 {
5105  double nrows;
5106 
5107  /*
5108  * Estimate the number of rows returned by the parameterized join as the
5109  * sizes of the input paths times the selectivity of the clauses that have
5110