PostgreSQL Source Code  git master
costsize.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/amapi.h"
#include "access/htup_details.h"
#include "access/tsmapi.h"
#include "executor/executor.h"
#include "executor/nodeHash.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
 

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 *joinpath)
 
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)
 
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_subqueryscan (SubqueryScanPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
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)
 
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)
 
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)
 
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
 
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_hashagg = true
 
bool enable_nestloop = true
 
bool enable_material = 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
 

Macro Definition Documentation

◆ APPEND_CPU_COST_MULTIPLIER

#define APPEND_CPU_COST_MULTIPLIER   0.5

Definition at line 107 of file costsize.c.

Referenced by cost_append(), and cost_merge_append().

◆ LOG2

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

Definition at line 100 of file costsize.c.

Referenced by cost_gather_merge(), cost_merge_append(), and cost_sort().

Function Documentation

◆ append_nonpartial_cost()

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

Definition at line 1799 of file costsize.c.

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

Referenced by cost_append().

1800 {
1801  Cost *costarr;
1802  int arrlen;
1803  ListCell *l;
1804  ListCell *cell;
1805  int i;
1806  int path_index;
1807  int min_index;
1808  int max_index;
1809 
1810  if (numpaths == 0)
1811  return 0;
1812 
1813  /*
1814  * Array length is number of workers or number of relevant paths,
1815  * whichever is less.
1816  */
1817  arrlen = Min(parallel_workers, numpaths);
1818  costarr = (Cost *) palloc(sizeof(Cost) * arrlen);
1819 
1820  /* The first few paths will each be claimed by a different worker. */
1821  path_index = 0;
1822  foreach(cell, subpaths)
1823  {
1824  Path *subpath = (Path *) lfirst(cell);
1825 
1826  if (path_index == arrlen)
1827  break;
1828  costarr[path_index++] = subpath->total_cost;
1829  }
1830 
1831  /*
1832  * Since subpaths are sorted by decreasing cost, the last one will have
1833  * the minimum cost.
1834  */
1835  min_index = arrlen - 1;
1836 
1837  /*
1838  * For each of the remaining subpaths, add its cost to the array element
1839  * with minimum cost.
1840  */
1841  for_each_cell(l, subpaths, cell)
1842  {
1843  Path *subpath = (Path *) lfirst(l);
1844  int i;
1845 
1846  /* Consider only the non-partial paths */
1847  if (path_index++ == numpaths)
1848  break;
1849 
1850  costarr[min_index] += subpath->total_cost;
1851 
1852  /* Update the new min cost array index */
1853  for (min_index = i = 0; i < arrlen; i++)
1854  {
1855  if (costarr[i] < costarr[min_index])
1856  min_index = i;
1857  }
1858  }
1859 
1860  /* Return the highest cost from the array */
1861  for (max_index = i = 0; i < arrlen; i++)
1862  {
1863  if (costarr[i] > costarr[max_index])
1864  max_index = i;
1865  }
1866 
1867  return costarr[max_index];
1868 }
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:390
#define Min(x, y)
Definition: c.h:904
Cost total_cost
Definition: pathnodes.h:1126
#define lfirst(lc)
Definition: pg_list.h:190
void * palloc(Size size)
Definition: mcxt.c:949
int i
double Cost
Definition: nodes.h:659
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241

◆ approx_tuple_count()

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

Definition at line 4348 of file costsize.c.

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::parent, RelOptInfo::relids, Path::rows, SpecialJoinInfo::semi_can_btree, SpecialJoinInfo::semi_can_hash, SpecialJoinInfo::semi_operators, SpecialJoinInfo::semi_rhs_exprs, SpecialJoinInfo::syn_lefthand, SpecialJoinInfo::syn_righthand, T_SpecialJoinInfo, and SpecialJoinInfo::type.

Referenced by final_cost_hashjoin(), and final_cost_mergejoin().

4349 {
4350  double tuples;
4351  double outer_tuples = path->outerjoinpath->rows;
4352  double inner_tuples = path->innerjoinpath->rows;
4353  SpecialJoinInfo sjinfo;
4354  Selectivity selec = 1.0;
4355  ListCell *l;
4356 
4357  /*
4358  * Make up a SpecialJoinInfo for JOIN_INNER semantics.
4359  */
4360  sjinfo.type = T_SpecialJoinInfo;
4361  sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
4362  sjinfo.min_righthand = path->innerjoinpath->parent->relids;
4363  sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
4364  sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
4365  sjinfo.jointype = JOIN_INNER;
4366  /* we don't bother trying to make the remaining fields valid */
4367  sjinfo.lhs_strict = false;
4368  sjinfo.delay_upper_joins = false;
4369  sjinfo.semi_can_btree = false;
4370  sjinfo.semi_can_hash = false;
4371  sjinfo.semi_operators = NIL;
4372  sjinfo.semi_rhs_exprs = NIL;
4373 
4374  /* Get the approximate selectivity */
4375  foreach(l, quals)
4376  {
4377  Node *qual = (Node *) lfirst(l);
4378 
4379  /* Note that clause_selectivity will be able to cache its result */
4380  selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
4381  }
4382 
4383  /* Apply it to the input relation sizes */
4384  tuples = selec * outer_tuples * inner_tuples;
4385 
4386  return clamp_row_est(tuples);
4387 }
#define NIL
Definition: pg_list.h:65
Relids min_righthand
Definition: pathnodes.h:2134
Path * innerjoinpath
Definition: pathnodes.h:1496
Definition: nodes.h:525
double Selectivity
Definition: nodes.h:658
Relids syn_lefthand
Definition: pathnodes.h:2135
Relids syn_righthand
Definition: pathnodes.h:2136
List * semi_rhs_exprs
Definition: pathnodes.h:2144
RelOptInfo * parent
Definition: pathnodes.h:1114
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:601
Relids relids
Definition: pathnodes.h:641
Path * outerjoinpath
Definition: pathnodes.h:1495
bool delay_upper_joins
Definition: pathnodes.h:2139
#define lfirst(lc)
Definition: pg_list.h:190
double rows
Definition: pathnodes.h:1124
JoinType jointype
Definition: pathnodes.h:2137
List * semi_operators
Definition: pathnodes.h:2143
double clamp_row_est(double nrows)
Definition: costsize.c:187
Relids min_lefthand
Definition: pathnodes.h:2133

◆ cached_scansel()

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

Definition at line 3177 of file costsize.c.

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

Referenced by initial_cost_mergejoin().

3178 {
3179  MergeScanSelCache *cache;
3180  ListCell *lc;
3181  Selectivity leftstartsel,
3182  leftendsel,
3183  rightstartsel,
3184  rightendsel;
3185  MemoryContext oldcontext;
3186 
3187  /* Do we have this result already? */
3188  foreach(lc, rinfo->scansel_cache)
3189  {
3190  cache = (MergeScanSelCache *) lfirst(lc);
3191  if (cache->opfamily == pathkey->pk_opfamily &&
3192  cache->collation == pathkey->pk_eclass->ec_collation &&
3193  cache->strategy == pathkey->pk_strategy &&
3194  cache->nulls_first == pathkey->pk_nulls_first)
3195  return cache;
3196  }
3197 
3198  /* Nope, do the computation */
3199  mergejoinscansel(root,
3200  (Node *) rinfo->clause,
3201  pathkey->pk_opfamily,
3202  pathkey->pk_strategy,
3203  pathkey->pk_nulls_first,
3204  &leftstartsel,
3205  &leftendsel,
3206  &rightstartsel,
3207  &rightendsel);
3208 
3209  /* Cache the result in suitably long-lived workspace */
3210  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
3211 
3212  cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
3213  cache->opfamily = pathkey->pk_opfamily;
3214  cache->collation = pathkey->pk_eclass->ec_collation;
3215  cache->strategy = pathkey->pk_strategy;
3216  cache->nulls_first = pathkey->pk_nulls_first;
3217  cache->leftstartsel = leftstartsel;
3218  cache->leftendsel = leftendsel;
3219  cache->rightstartsel = rightstartsel;
3220  cache->rightendsel = rightendsel;
3221 
3222  rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
3223 
3224  MemoryContextSwitchTo(oldcontext);
3225 
3226  return cache;
3227 }
Selectivity leftendsel
Definition: pathnodes.h:2040
void mergejoinscansel(PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
Definition: selfuncs.c:2624
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:525
double Selectivity
Definition: nodes.h:658
int pk_strategy
Definition: pathnodes.h:1013
bool pk_nulls_first
Definition: pathnodes.h:1014
Selectivity rightstartsel
Definition: pathnodes.h:2041
List * lappend(List *list, void *datum)
Definition: list.c:322
Expr * clause
Definition: pathnodes.h:1943
#define lfirst(lc)
Definition: pg_list.h:190
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1011
Oid pk_opfamily
Definition: pathnodes.h:1012
void * palloc(Size size)
Definition: mcxt.c:949
MemoryContext planner_cxt
Definition: pathnodes.h:329
Selectivity rightendsel
Definition: pathnodes.h:2042
List * scansel_cache
Definition: pathnodes.h:1995
Selectivity leftstartsel
Definition: pathnodes.h:2039

◆ 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 4556 of file costsize.c.

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().

4564 {
4565  /* This apparently-useless variable dodges a compiler bug in VS2013: */
4566  List *restrictlist = restrictlist_in;
4567  JoinType jointype = sjinfo->jointype;
4568  Selectivity fkselec;
4569  Selectivity jselec;
4570  Selectivity pselec;
4571  double nrows;
4572 
4573  /*
4574  * Compute joinclause selectivity. Note that we are only considering
4575  * clauses that become restriction clauses at this join level; we are not
4576  * double-counting them because they were not considered in estimating the
4577  * sizes of the component rels.
4578  *
4579  * First, see whether any of the joinclauses can be matched to known FK
4580  * constraints. If so, drop those clauses from the restrictlist, and
4581  * instead estimate their selectivity using FK semantics. (We do this
4582  * without regard to whether said clauses are local or "pushed down".
4583  * Probably, an FK-matching clause could never be seen as pushed down at
4584  * an outer join, since it would be strict and hence would be grounds for
4585  * join strength reduction.) fkselec gets the net selectivity for
4586  * FK-matching clauses, or 1.0 if there are none.
4587  */
4588  fkselec = get_foreign_key_join_selectivity(root,
4589  outer_rel->relids,
4590  inner_rel->relids,
4591  sjinfo,
4592  &restrictlist);
4593 
4594  /*
4595  * For an outer join, we have to distinguish the selectivity of the join's
4596  * own clauses (JOIN/ON conditions) from any clauses that were "pushed
4597  * down". For inner joins we just count them all as joinclauses.
4598  */
4599  if (IS_OUTER_JOIN(jointype))
4600  {
4601  List *joinquals = NIL;
4602  List *pushedquals = NIL;
4603  ListCell *l;
4604 
4605  /* Grovel through the clauses to separate into two lists */
4606  foreach(l, restrictlist)
4607  {
4608  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4609 
4610  if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
4611  pushedquals = lappend(pushedquals, rinfo);
4612  else
4613  joinquals = lappend(joinquals, rinfo);
4614  }
4615 
4616  /* Get the separate selectivities */
4617  jselec = clauselist_selectivity(root,
4618  joinquals,
4619  0,
4620  jointype,
4621  sjinfo);
4622  pselec = clauselist_selectivity(root,
4623  pushedquals,
4624  0,
4625  jointype,
4626  sjinfo);
4627 
4628  /* Avoid leaking a lot of ListCells */
4629  list_free(joinquals);
4630  list_free(pushedquals);
4631  }
4632  else
4633  {
4634  jselec = clauselist_selectivity(root,
4635  restrictlist,
4636  0,
4637  jointype,
4638  sjinfo);
4639  pselec = 0.0; /* not used, keep compiler quiet */
4640  }
4641 
4642  /*
4643  * Basically, we multiply size of Cartesian product by selectivity.
4644  *
4645  * If we are doing an outer join, take that into account: the joinqual
4646  * selectivity has to be clamped using the knowledge that the output must
4647  * be at least as large as the non-nullable input. However, any
4648  * pushed-down quals are applied after the outer join, so their
4649  * selectivity applies fully.
4650  *
4651  * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
4652  * of LHS rows that have matches, and we apply that straightforwardly.
4653  */
4654  switch (jointype)
4655  {
4656  case JOIN_INNER:
4657  nrows = outer_rows * inner_rows * fkselec * jselec;
4658  /* pselec not used */
4659  break;
4660  case JOIN_LEFT:
4661  nrows = outer_rows * inner_rows * fkselec * jselec;
4662  if (nrows < outer_rows)
4663  nrows = outer_rows;
4664  nrows *= pselec;
4665  break;
4666  case JOIN_FULL:
4667  nrows = outer_rows * inner_rows * fkselec * jselec;
4668  if (nrows < outer_rows)
4669  nrows = outer_rows;
4670  if (nrows < inner_rows)
4671  nrows = inner_rows;
4672  nrows *= pselec;
4673  break;
4674  case JOIN_SEMI:
4675  nrows = outer_rows * fkselec * jselec;
4676  /* pselec not used */
4677  break;
4678  case JOIN_ANTI:
4679  nrows = outer_rows * (1.0 - fkselec * jselec);
4680  nrows *= pselec;
4681  break;
4682  default:
4683  /* other values not expected here */
4684  elog(ERROR, "unrecognized join type: %d", (int) jointype);
4685  nrows = 0; /* keep compiler quiet */
4686  break;
4687  }
4688 
4689  return clamp_row_est(nrows);
4690 }
#define NIL
Definition: pg_list.h:65
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:741
double Selectivity
Definition: nodes.h:658
JoinType
Definition: nodes.h:692
static Selectivity get_foreign_key_join_selectivity(PlannerInfo *root, Relids outer_relids, Relids inner_relids, SpecialJoinInfo *sjinfo, List **restrictlist)
Definition: costsize.c:4708
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:193
Relids relids
Definition: pathnodes.h:641
List * lappend(List *list, void *datum)
Definition: list.c:322
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2020
JoinType jointype
Definition: pathnodes.h:2137
void list_free(List *list)
Definition: list.c:1377
#define elog(elevel,...)
Definition: elog.h:226
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:70
double clamp_row_est(double nrows)
Definition: costsize.c:187
Definition: pg_list.h:50

◆ clamp_row_est()

double clamp_row_est ( double  nrows)

Definition at line 187 of file costsize.c.

References rint().

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(), 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_foreign_size(), system_rows_samplescangetsamplesize(), system_samplescangetsamplesize(), and system_time_samplescangetsamplesize().

188 {
189  /*
190  * Force estimate to be at least one row, to make explain output look
191  * better and to avoid possible divide-by-zero when interpolating costs.
192  * Make it an integer, too.
193  */
194  if (nrows <= 1.0)
195  nrows = 1.0;
196  else
197  nrows = rint(nrows);
198 
199  return nrows;
200 }
double rint(double x)
Definition: rint.c:21

◆ compute_bitmap_pages()

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

Definition at line 5508 of file costsize.c.

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().

5510 {
5511  Cost indexTotalCost;
5512  Selectivity indexSelectivity;
5513  double T;
5514  double pages_fetched;
5515  double tuples_fetched;
5516  double heap_pages;
5517  long maxentries;
5518 
5519  /*
5520  * Fetch total cost of obtaining the bitmap, as well as its total
5521  * selectivity.
5522  */
5523  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
5524 
5525  /*
5526  * Estimate number of main-table pages fetched.
5527  */
5528  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
5529 
5530  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
5531 
5532  /*
5533  * For a single scan, the number of heap pages that need to be fetched is
5534  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
5535  * re-reads needed).
5536  */
5537  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
5538 
5539  /*
5540  * Calculate the number of pages fetched from the heap. Then based on
5541  * current work_mem estimate get the estimated maxentries in the bitmap.
5542  * (Note that we always do this calculation based on the number of pages
5543  * that would be fetched in a single iteration, even if loop_count > 1.
5544  * That's correct, because only that number of entries will be stored in
5545  * the bitmap at one time.)
5546  */
5547  heap_pages = Min(pages_fetched, baserel->pages);
5548  maxentries = tbm_calculate_entries(work_mem * 1024L);
5549 
5550  if (loop_count > 1)
5551  {
5552  /*
5553  * For repeated bitmap scans, scale up the number of tuples fetched in
5554  * the Mackert and Lohman formula by the number of scans, so that we
5555  * estimate the number of pages fetched by all the scans. Then
5556  * pro-rate for one scan.
5557  */
5558  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
5559  baserel->pages,
5560  get_indexpath_pages(bitmapqual),
5561  root);
5562  pages_fetched /= loop_count;
5563  }
5564 
5565  if (pages_fetched >= T)
5566  pages_fetched = T;
5567  else
5568  pages_fetched = ceil(pages_fetched);
5569 
5570  if (maxentries < heap_pages)
5571  {
5572  double exact_pages;
5573  double lossy_pages;
5574 
5575  /*
5576  * Crude approximation of the number of lossy pages. Because of the
5577  * way tbm_lossify() is coded, the number of lossy pages increases
5578  * very sharply as soon as we run short of memory; this formula has
5579  * that property and seems to perform adequately in testing, but it's
5580  * possible we could do better somehow.
5581  */
5582  lossy_pages = Max(0, heap_pages - maxentries / 2);
5583  exact_pages = heap_pages - lossy_pages;
5584 
5585  /*
5586  * If there are lossy pages then recompute the number of tuples
5587  * processed by the bitmap heap node. We assume here that the chance
5588  * of a given tuple coming from an exact page is the same as the
5589  * chance that a given page is exact. This might not be true, but
5590  * it's not clear how we can do any better.
5591  */
5592  if (lossy_pages > 0)
5593  tuples_fetched =
5594  clamp_row_est(indexSelectivity *
5595  (exact_pages / heap_pages) * baserel->tuples +
5596  (lossy_pages / heap_pages) * baserel->tuples);
5597  }
5598 
5599  if (cost)
5600  *cost = indexTotalCost;
5601  if (tuple)
5602  *tuple = tuples_fetched;
5603 
5604  return pages_fetched;
5605 }
double tuples
Definition: pathnodes.h:681
#define Min(x, y)
Definition: c.h:904
double Selectivity
Definition: nodes.h:658
static const uint32 T[65]
Definition: md5.c:101
int work_mem
Definition: globals.c:121
#define Max(x, y)
Definition: c.h:898
BlockNumber pages
Definition: pathnodes.h:680
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:890
long tbm_calculate_entries(double maxbytes)
Definition: tidbitmap.c:1545
double clamp_row_est(double nrows)
Definition: costsize.c:187
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:825
double Cost
Definition: nodes.h:659
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1041

◆ 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 4147 of file costsize.c.

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, SpecialJoinInfo::syn_righthand, T_SpecialJoinInfo, and SpecialJoinInfo::type.

Referenced by add_paths_to_joinrel().

4155 {
4156  Selectivity jselec;
4157  Selectivity nselec;
4158  Selectivity avgmatch;
4159  SpecialJoinInfo norm_sjinfo;
4160  List *joinquals;
4161  ListCell *l;
4162 
4163  /*
4164  * In an ANTI join, we must ignore clauses that are "pushed down", since
4165  * those won't affect the match logic. In a SEMI join, we do not
4166  * distinguish joinquals from "pushed down" quals, so just use the whole
4167  * restrictinfo list. For other outer join types, we should consider only
4168  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
4169  */
4170  if (IS_OUTER_JOIN(jointype))
4171  {
4172  joinquals = NIL;
4173  foreach(l, restrictlist)
4174  {
4175  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4176 
4177  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
4178  joinquals = lappend(joinquals, rinfo);
4179  }
4180  }
4181  else
4182  joinquals = restrictlist;
4183 
4184  /*
4185  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
4186  */
4187  jselec = clauselist_selectivity(root,
4188  joinquals,
4189  0,
4190  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
4191  sjinfo);
4192 
4193  /*
4194  * Also get the normal inner-join selectivity of the join clauses.
4195  */
4196  norm_sjinfo.type = T_SpecialJoinInfo;
4197  norm_sjinfo.min_lefthand = outerrel->relids;
4198  norm_sjinfo.min_righthand = innerrel->relids;
4199  norm_sjinfo.syn_lefthand = outerrel->relids;
4200  norm_sjinfo.syn_righthand = innerrel->relids;
4201  norm_sjinfo.jointype = JOIN_INNER;
4202  /* we don't bother trying to make the remaining fields valid */
4203  norm_sjinfo.lhs_strict = false;
4204  norm_sjinfo.delay_upper_joins = false;
4205  norm_sjinfo.semi_can_btree = false;
4206  norm_sjinfo.semi_can_hash = false;
4207  norm_sjinfo.semi_operators = NIL;
4208  norm_sjinfo.semi_rhs_exprs = NIL;
4209 
4210  nselec = clauselist_selectivity(root,
4211  joinquals,
4212  0,
4213  JOIN_INNER,
4214  &norm_sjinfo);
4215 
4216  /* Avoid leaking a lot of ListCells */
4217  if (IS_OUTER_JOIN(jointype))
4218  list_free(joinquals);
4219 
4220  /*
4221  * jselec can be interpreted as the fraction of outer-rel rows that have
4222  * any matches (this is true for both SEMI and ANTI cases). And nselec is
4223  * the fraction of the Cartesian product that matches. So, the average
4224  * number of matches for each outer-rel row that has at least one match is
4225  * nselec * inner_rows / jselec.
4226  *
4227  * Note: it is correct to use the inner rel's "rows" count here, even
4228  * though we might later be considering a parameterized inner path with
4229  * fewer rows. This is because we have included all the join clauses in
4230  * the selectivity estimate.
4231  */
4232  if (jselec > 0) /* protect against zero divide */
4233  {
4234  avgmatch = nselec * innerrel->rows / jselec;
4235  /* Clamp to sane range */
4236  avgmatch = Max(1.0, avgmatch);
4237  }
4238  else
4239  avgmatch = 1.0;
4240 
4241  semifactors->outer_match_frac = jselec;
4242  semifactors->match_count = avgmatch;
4243 }
#define NIL
Definition: pg_list.h:65
Relids min_righthand
Definition: pathnodes.h:2134
Selectivity outer_match_frac
Definition: pathnodes.h:2358
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:741
double Selectivity
Definition: nodes.h:658
Relids syn_lefthand
Definition: pathnodes.h:2135
Relids syn_righthand
Definition: pathnodes.h:2136
List * semi_rhs_exprs
Definition: pathnodes.h:2144
#define lfirst_node(type, lc)
Definition: pg_list.h:193
Relids relids
Definition: pathnodes.h:641
List * lappend(List *list, void *datum)
Definition: list.c:322
bool delay_upper_joins
Definition: pathnodes.h:2139
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2020
double rows
Definition: pathnodes.h:644
#define Max(x, y)
Definition: c.h:898
JoinType jointype
Definition: pathnodes.h:2137
Selectivity match_count
Definition: pathnodes.h:2359
List * semi_operators
Definition: pathnodes.h:2143
void list_free(List *list)
Definition: list.c:1377
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:70
Definition: pg_list.h:50
Relids min_lefthand
Definition: pathnodes.h:2133

◆ 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 
)

Definition at line 2151 of file costsize.c.

References AGG_HASHED, AGG_MIXED, AGG_PLAIN, AGG_SORTED, Assert, clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, disable_cost, enable_hashagg, AggClauseCosts::finalCost, JOIN_INNER, MemSet, QualCost::per_tuple, Path::rows, QualCost::startup, Path::startup_cost, Path::total_cost, and AggClauseCosts::transCost.

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

2157 {
2158  double output_tuples;
2159  Cost startup_cost;
2160  Cost total_cost;
2161  AggClauseCosts dummy_aggcosts;
2162 
2163  /* Use all-zero per-aggregate costs if NULL is passed */
2164  if (aggcosts == NULL)
2165  {
2166  Assert(aggstrategy == AGG_HASHED);
2167  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
2168  aggcosts = &dummy_aggcosts;
2169  }
2170 
2171  /*
2172  * The transCost.per_tuple component of aggcosts should be charged once
2173  * per input tuple, corresponding to the costs of evaluating the aggregate
2174  * transfns and their input expressions. The finalCost.per_tuple component
2175  * is charged once per output tuple, corresponding to the costs of
2176  * evaluating the finalfns. Startup costs are of course charged but once.
2177  *
2178  * If we are grouping, we charge an additional cpu_operator_cost per
2179  * grouping column per input tuple for grouping comparisons.
2180  *
2181  * We will produce a single output tuple if not grouping, and a tuple per
2182  * group otherwise. We charge cpu_tuple_cost for each output tuple.
2183  *
2184  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2185  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2186  * input path is already sorted appropriately, AGG_SORTED should be
2187  * preferred (since it has no risk of memory overflow). This will happen
2188  * as long as the computed total costs are indeed exactly equal --- but if
2189  * there's roundoff error we might do the wrong thing. So be sure that
2190  * the computations below form the same intermediate values in the same
2191  * order.
2192  */
2193  if (aggstrategy == AGG_PLAIN)
2194  {
2195  startup_cost = input_total_cost;
2196  startup_cost += aggcosts->transCost.startup;
2197  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2198  startup_cost += aggcosts->finalCost.startup;
2199  startup_cost += aggcosts->finalCost.per_tuple;
2200  /* we aren't grouping */
2201  total_cost = startup_cost + cpu_tuple_cost;
2202  output_tuples = 1;
2203  }
2204  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2205  {
2206  /* Here we are able to deliver output on-the-fly */
2207  startup_cost = input_startup_cost;
2208  total_cost = input_total_cost;
2209  if (aggstrategy == AGG_MIXED && !enable_hashagg)
2210  {
2211  startup_cost += disable_cost;
2212  total_cost += disable_cost;
2213  }
2214  /* calcs phrased this way to match HASHED case, see note above */
2215  total_cost += aggcosts->transCost.startup;
2216  total_cost += aggcosts->transCost.per_tuple * input_tuples;
2217  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2218  total_cost += aggcosts->finalCost.startup;
2219  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2220  total_cost += cpu_tuple_cost * numGroups;
2221  output_tuples = numGroups;
2222  }
2223  else
2224  {
2225  /* must be AGG_HASHED */
2226  startup_cost = input_total_cost;
2227  if (!enable_hashagg)
2228  startup_cost += disable_cost;
2229  startup_cost += aggcosts->transCost.startup;
2230  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2231  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2232  startup_cost += aggcosts->finalCost.startup;
2233  total_cost = startup_cost;
2234  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2235  total_cost += cpu_tuple_cost * numGroups;
2236  output_tuples = numGroups;
2237  }
2238 
2239  /*
2240  * If there are quals (HAVING quals), account for their cost and
2241  * selectivity.
2242  */
2243  if (quals)
2244  {
2245  QualCost qual_cost;
2246 
2247  cost_qual_eval(&qual_cost, quals, root);
2248  startup_cost += qual_cost.startup;
2249  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2250 
2251  output_tuples = clamp_row_est(output_tuples *
2253  quals,
2254  0,
2255  JOIN_INNER,
2256  NULL));
2257  }
2258 
2259  path->rows = output_tuples;
2260  path->startup_cost = startup_cost;
2261  path->total_cost = total_cost;
2262 }
QualCost finalCost
Definition: pathnodes.h:63
#define MemSet(start, val, len)
Definition: c.h:955
QualCost transCost
Definition: pathnodes.h:62
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3819
Cost startup_cost
Definition: pathnodes.h:1125
Cost disable_cost
Definition: costsize.c:120
double cpu_operator_cost
Definition: costsize.c:114
Cost total_cost
Definition: pathnodes.h:1126
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
double cpu_tuple_cost
Definition: costsize.c:112
bool enable_hashagg
Definition: costsize.c:130
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:70
double clamp_row_est(double nrows)
Definition: costsize.c:187
double Cost
Definition: nodes.h:659

◆ cost_append()

void cost_append ( AppendPath apath)

Definition at line 1875 of file costsize.c.

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::pathtarget, Path::rows, Path::startup_cost, subpath(), AppendPath::subpaths, Path::total_cost, PathTarget::width, and work_mem.

Referenced by create_append_path().

1876 {
1877  ListCell *l;
1878 
1879  apath->path.startup_cost = 0;
1880  apath->path.total_cost = 0;
1881  apath->path.rows = 0;
1882 
1883  if (apath->subpaths == NIL)
1884  return;
1885 
1886  if (!apath->path.parallel_aware)
1887  {
1888  List *pathkeys = apath->path.pathkeys;
1889 
1890  if (pathkeys == NIL)
1891  {
1892  Path *subpath = (Path *) linitial(apath->subpaths);
1893 
1894  /*
1895  * For an unordered, non-parallel-aware Append we take the startup
1896  * cost as the startup cost of the first subpath.
1897  */
1898  apath->path.startup_cost = subpath->startup_cost;
1899 
1900  /* Compute rows and costs as sums of subplan rows and costs. */
1901  foreach(l, apath->subpaths)
1902  {
1903  Path *subpath = (Path *) lfirst(l);
1904 
1905  apath->path.rows += subpath->rows;
1906  apath->path.total_cost += subpath->total_cost;
1907  }
1908  }
1909  else
1910  {
1911  /*
1912  * For an ordered, non-parallel-aware Append we take the startup
1913  * cost as the sum of the subpath startup costs. This ensures
1914  * that we don't underestimate the startup cost when a query's
1915  * LIMIT is such that several of the children have to be run to
1916  * satisfy it. This might be overkill --- another plausible hack
1917  * would be to take the Append's startup cost as the maximum of
1918  * the child startup costs. But we don't want to risk believing
1919  * that an ORDER BY LIMIT query can be satisfied at small cost
1920  * when the first child has small startup cost but later ones
1921  * don't. (If we had the ability to deal with nonlinear cost
1922  * interpolation for partial retrievals, we would not need to be
1923  * so conservative about this.)
1924  *
1925  * This case is also different from the above in that we have to
1926  * account for possibly injecting sorts into subpaths that aren't
1927  * natively ordered.
1928  */
1929  foreach(l, apath->subpaths)
1930  {
1931  Path *subpath = (Path *) lfirst(l);
1932  Path sort_path; /* dummy for result of cost_sort */
1933 
1934  if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
1935  {
1936  /*
1937  * We'll need to insert a Sort node, so include costs for
1938  * that. We can use the parent's LIMIT if any, since we
1939  * certainly won't pull more than that many tuples from
1940  * any child.
1941  */
1942  cost_sort(&sort_path,
1943  NULL, /* doesn't currently need root */
1944  pathkeys,
1945  subpath->total_cost,
1946  subpath->rows,
1947  subpath->pathtarget->width,
1948  0.0,
1949  work_mem,
1950  apath->limit_tuples);
1951  subpath = &sort_path;
1952  }
1953 
1954  apath->path.rows += subpath->rows;
1955  apath->path.startup_cost += subpath->startup_cost;
1956  apath->path.total_cost += subpath->total_cost;
1957  }
1958  }
1959  }
1960  else /* parallel-aware */
1961  {
1962  int i = 0;
1963  double parallel_divisor = get_parallel_divisor(&apath->path);
1964 
1965  /* Parallel-aware Append never produces ordered output. */
1966  Assert(apath->path.pathkeys == NIL);
1967 
1968  /* Calculate startup cost. */
1969  foreach(l, apath->subpaths)
1970  {
1971  Path *subpath = (Path *) lfirst(l);
1972 
1973  /*
1974  * Append will start returning tuples when the child node having
1975  * lowest startup cost is done setting up. We consider only the
1976  * first few subplans that immediately get a worker assigned.
1977  */
1978  if (i == 0)
1979  apath->path.startup_cost = subpath->startup_cost;
1980  else if (i < apath->path.parallel_workers)
1981  apath->path.startup_cost = Min(apath->path.startup_cost,
1982  subpath->startup_cost);
1983 
1984  /*
1985  * Apply parallel divisor to subpaths. Scale the number of rows
1986  * for each partial subpath based on the ratio of the parallel
1987  * divisor originally used for the subpath to the one we adopted.
1988  * Also add the cost of partial paths to the total cost, but
1989  * ignore non-partial paths for now.
1990  */
1991  if (i < apath->first_partial_path)
1992  apath->path.rows += subpath->rows / parallel_divisor;
1993  else
1994  {
1995  double subpath_parallel_divisor;
1996 
1997  subpath_parallel_divisor = get_parallel_divisor(subpath);
1998  apath->path.rows += subpath->rows * (subpath_parallel_divisor /
1999  parallel_divisor);
2000  apath->path.total_cost += subpath->total_cost;
2001  }
2002 
2003  apath->path.rows = clamp_row_est(apath->path.rows);
2004 
2005  i++;
2006  }
2007 
2008  /* Add cost for non-partial subpaths. */
2009  apath->path.total_cost +=
2011  apath->first_partial_path,
2012  apath->path.parallel_workers);
2013  }
2014 
2015  /*
2016  * Although Append does not do any selection or projection, it's not free;
2017  * add a small per-tuple overhead.
2018  */
2019  apath->path.total_cost +=
2021 }
#define NIL
Definition: pg_list.h:65
PathTarget * pathtarget
Definition: pathnodes.h:1115
double limit_tuples
Definition: pathnodes.h:1377
#define Min(x, y)
Definition: c.h:904
int parallel_workers
Definition: pathnodes.h:1121
static Cost append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
Definition: costsize.c:1799
int first_partial_path
Definition: pathnodes.h:1376
List * subpaths
Definition: pathnodes.h:1374
#define linitial(l)
Definition: pg_list.h:195
Cost startup_cost
Definition: pathnodes.h:1125
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5475
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:107
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:1693
int work_mem
Definition: globals.c:121
Cost total_cost
Definition: pathnodes.h:1126
List * pathkeys
Definition: pathnodes.h:1128
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
double rows
Definition: pathnodes.h:1124
double cpu_tuple_cost
Definition: costsize.c:112
int i
bool parallel_aware
Definition: pathnodes.h:1119
double clamp_row_est(double nrows)
Definition: costsize.c:187
Definition: pg_list.h:50
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1084 of file costsize.c.

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 bitmap_and_cost_est(), and create_bitmap_and_path().

1085 {
1086  Cost totalCost;
1087  Selectivity selec;
1088  ListCell *l;
1089 
1090  /*
1091  * We estimate AND selectivity on the assumption that the inputs are
1092  * independent. This is probably often wrong, but we don't have the info
1093  * to do better.
1094  *
1095  * The runtime cost of the BitmapAnd itself is estimated at 100x
1096  * cpu_operator_cost for each tbm_intersect needed. Probably too small,
1097  * definitely too simplistic?
1098  */
1099  totalCost = 0.0;
1100  selec = 1.0;
1101  foreach(l, path->bitmapquals)
1102  {
1103  Path *subpath = (Path *) lfirst(l);
1104  Cost subCost;
1105  Selectivity subselec;
1106 
1107  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1108 
1109  selec *= subselec;
1110 
1111  totalCost += subCost;
1112  if (l != list_head(path->bitmapquals))
1113  totalCost += 100.0 * cpu_operator_cost;
1114  }
1115  path->bitmapselectivity = selec;
1116  path->path.rows = 0; /* per above, not used */
1117  path->path.startup_cost = totalCost;
1118  path->path.total_cost = totalCost;
1119 }
double Selectivity
Definition: nodes.h:658
Selectivity bitmapselectivity
Definition: pathnodes.h:1263
List * bitmapquals
Definition: pathnodes.h:1262
Cost startup_cost
Definition: pathnodes.h:1125
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
double cpu_operator_cost
Definition: costsize.c:114
Cost total_cost
Definition: pathnodes.h:1126
#define lfirst(lc)
Definition: pg_list.h:190
double rows
Definition: pathnodes.h:1124
double Cost
Definition: nodes.h:659
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1041

◆ 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 940 of file costsize.c.

References Assert, clamp_row_est(), compute_bitmap_pages(), PathTarget::cost, cpu_tuple_cost, disable_cost, enable_bitmapscan, get_parallel_divisor(), get_restriction_qual_cost(), get_tablespace_page_costs(), IsA, RelOptInfo::pages, Path::parallel_workers, Path::pathtarget, 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_and_cost_est(), bitmap_scan_cost_est(), and create_bitmap_heap_path().

943 {
944  Cost startup_cost = 0;
945  Cost run_cost = 0;
946  Cost indexTotalCost;
947  QualCost qpqual_cost;
948  Cost cpu_per_tuple;
949  Cost cost_per_page;
950  Cost cpu_run_cost;
951  double tuples_fetched;
952  double pages_fetched;
953  double spc_seq_page_cost,
954  spc_random_page_cost;
955  double T;
956 
957  /* Should only be applied to base relations */
958  Assert(IsA(baserel, RelOptInfo));
959  Assert(baserel->relid > 0);
960  Assert(baserel->rtekind == RTE_RELATION);
961 
962  /* Mark the path with the correct row estimate */
963  if (param_info)
964  path->rows = param_info->ppi_rows;
965  else
966  path->rows = baserel->rows;
967 
968  if (!enable_bitmapscan)
969  startup_cost += disable_cost;
970 
971  pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
972  loop_count, &indexTotalCost,
973  &tuples_fetched);
974 
975  startup_cost += indexTotalCost;
976  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
977 
978  /* Fetch estimated page costs for tablespace containing table. */
980  &spc_random_page_cost,
981  &spc_seq_page_cost);
982 
983  /*
984  * For small numbers of pages we should charge spc_random_page_cost
985  * apiece, while if nearly all the table's pages are being read, it's more
986  * appropriate to charge spc_seq_page_cost apiece. The effect is
987  * nonlinear, too. For lack of a better idea, interpolate like this to
988  * determine the cost per page.
989  */
990  if (pages_fetched >= 2.0)
991  cost_per_page = spc_random_page_cost -
992  (spc_random_page_cost - spc_seq_page_cost)
993  * sqrt(pages_fetched / T);
994  else
995  cost_per_page = spc_random_page_cost;
996 
997  run_cost += pages_fetched * cost_per_page;
998 
999  /*
1000  * Estimate CPU costs per tuple.
1001  *
1002  * Often the indexquals don't need to be rechecked at each tuple ... but
1003  * not always, especially not if there are enough tuples involved that the
1004  * bitmaps become lossy. For the moment, just assume they will be
1005  * rechecked always. This means we charge the full freight for all the
1006  * scan clauses.
1007  */
1008  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1009 
1010  startup_cost += qpqual_cost.startup;
1011  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1012  cpu_run_cost = cpu_per_tuple * tuples_fetched;
1013 
1014  /* Adjust costing for parallelism, if used. */
1015  if (path->parallel_workers > 0)
1016  {
1017  double parallel_divisor = get_parallel_divisor(path);
1018 
1019  /* The CPU cost is divided among all the workers. */
1020  cpu_run_cost /= parallel_divisor;
1021 
1022  path->rows = clamp_row_est(path->rows / parallel_divisor);
1023  }
1024 
1025 
1026  run_cost += cpu_run_cost;
1027 
1028  /* tlist eval costs are paid per output row, not per tuple scanned */
1029  startup_cost += path->pathtarget->cost.startup;
1030  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1031 
1032  path->startup_cost = startup_cost;
1033  path->total_cost = startup_cost + run_cost;
1034 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
PathTarget * pathtarget
Definition: pathnodes.h:1115
Oid reltablespace
Definition: pathnodes.h:670
int parallel_workers
Definition: pathnodes.h:1121
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1125
Cost disable_cost
Definition: costsize.c:120
static const uint32 T[65]
Definition: md5.c:101
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5475
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: pathnodes.h:669
bool enable_bitmapscan
Definition: costsize.c:127
RTEKind rtekind
Definition: pathnodes.h:671
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4105
BlockNumber pages
Definition: pathnodes.h:680
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
QualCost cost
Definition: pathnodes.h:1046
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
double clamp_row_est(double nrows)
Definition: costsize.c:187
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
Definition: costsize.c:5508
double Cost
Definition: nodes.h:659

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1128 of file costsize.c.

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().

1129 {
1130  Cost totalCost;
1131  Selectivity selec;
1132  ListCell *l;
1133 
1134  /*
1135  * We estimate OR selectivity on the assumption that the inputs are
1136  * non-overlapping, since that's often the case in "x IN (list)" type
1137  * situations. Of course, we clamp to 1.0 at the end.
1138  *
1139  * The runtime cost of the BitmapOr itself is estimated at 100x
1140  * cpu_operator_cost for each tbm_union needed. Probably too small,
1141  * definitely too simplistic? We are aware that the tbm_unions are
1142  * optimized out when the inputs are BitmapIndexScans.
1143  */
1144  totalCost = 0.0;
1145  selec = 0.0;
1146  foreach(l, path->bitmapquals)
1147  {
1148  Path *subpath = (Path *) lfirst(l);
1149  Cost subCost;
1150  Selectivity subselec;
1151 
1152  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1153 
1154  selec += subselec;
1155 
1156  totalCost += subCost;
1157  if (l != list_head(path->bitmapquals) &&
1158  !IsA(subpath, IndexPath))
1159  totalCost += 100.0 * cpu_operator_cost;
1160  }
1161  path->bitmapselectivity = Min(selec, 1.0);
1162  path->path.rows = 0; /* per above, not used */
1163  path->path.startup_cost = totalCost;
1164  path->path.total_cost = totalCost;
1165 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define Min(x, y)
Definition: c.h:904
double Selectivity
Definition: nodes.h:658
List * bitmapquals
Definition: pathnodes.h:1275
Cost startup_cost
Definition: pathnodes.h:1125
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
double cpu_operator_cost
Definition: costsize.c:114
Selectivity bitmapselectivity
Definition: pathnodes.h:1276
Cost total_cost
Definition: pathnodes.h:1126
#define lfirst(lc)
Definition: pg_list.h:190
double rows
Definition: pathnodes.h:1124
double Cost
Definition: nodes.h:659
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1041

◆ cost_bitmap_tree_node()

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

Definition at line 1041 of file costsize.c.

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().

1042 {
1043  if (IsA(path, IndexPath))
1044  {
1045  *cost = ((IndexPath *) path)->indextotalcost;
1046  *selec = ((IndexPath *) path)->indexselectivity;
1047 
1048  /*
1049  * Charge a small amount per retrieved tuple to reflect the costs of
1050  * manipulating the bitmap. This is mostly to make sure that a bitmap
1051  * scan doesn't look to be the same cost as an indexscan to retrieve a
1052  * single tuple.
1053  */
1054  *cost += 0.1 * cpu_operator_cost * path->rows;
1055  }
1056  else if (IsA(path, BitmapAndPath))
1057  {
1058  *cost = path->total_cost;
1059  *selec = ((BitmapAndPath *) path)->bitmapselectivity;
1060  }
1061  else if (IsA(path, BitmapOrPath))
1062  {
1063  *cost = path->total_cost;
1064  *selec = ((BitmapOrPath *) path)->bitmapselectivity;
1065  }
1066  else
1067  {
1068  elog(ERROR, "unrecognized node type: %d", nodeTag(path));
1069  *cost = *selec = 0; /* keep compiler quiet */
1070  }
1071 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define ERROR
Definition: elog.h:43
double cpu_operator_cost
Definition: costsize.c:114
Cost total_cost
Definition: pathnodes.h:1126
double rows
Definition: pathnodes.h:1124
#define nodeTag(nodeptr)
Definition: nodes.h:530
#define elog(elevel,...)
Definition: elog.h:226

◆ cost_ctescan()

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

Definition at line 1498 of file costsize.c.

References Assert, PathTarget::cost, cpu_tuple_cost, get_restriction_qual_cost(), Path::pathtarget, 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().

1500 {
1501  Cost startup_cost = 0;
1502  Cost run_cost = 0;
1503  QualCost qpqual_cost;
1504  Cost cpu_per_tuple;
1505 
1506  /* Should only be applied to base relations that are CTEs */
1507  Assert(baserel->relid > 0);
1508  Assert(baserel->rtekind == RTE_CTE);
1509 
1510  /* Mark the path with the correct row estimate */
1511  if (param_info)
1512  path->rows = param_info->ppi_rows;
1513  else
1514  path->rows = baserel->rows;
1515 
1516  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1517  cpu_per_tuple = cpu_tuple_cost;
1518 
1519  /* Add scanning CPU costs */
1520  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1521 
1522  startup_cost += qpqual_cost.startup;
1523  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1524  run_cost += cpu_per_tuple * baserel->tuples;
1525 
1526  /* tlist eval costs are paid per output row, not per tuple scanned */
1527  startup_cost += path->pathtarget->cost.startup;
1528  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1529 
1530  path->startup_cost = startup_cost;
1531  path->total_cost = startup_cost + run_cost;
1532 }
PathTarget * pathtarget
Definition: pathnodes.h:1115
double tuples
Definition: pathnodes.h:681
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1125
Index relid
Definition: pathnodes.h:669
RTEKind rtekind
Definition: pathnodes.h:671
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4105
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
QualCost cost
Definition: pathnodes.h:1046
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
double Cost
Definition: nodes.h:659

◆ cost_functionscan()

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

Definition at line 1331 of file costsize.c.

References Assert, PathTarget::cost, cost_qual_eval_node(), cpu_tuple_cost, RangeTblEntry::functions, get_restriction_qual_cost(), Path::pathtarget, 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().

1333 {
1334  Cost startup_cost = 0;
1335  Cost run_cost = 0;
1336  QualCost qpqual_cost;
1337  Cost cpu_per_tuple;
1338  RangeTblEntry *rte;
1339  QualCost exprcost;
1340 
1341  /* Should only be applied to base relations that are functions */
1342  Assert(baserel->relid > 0);
1343  rte = planner_rt_fetch(baserel->relid, root);
1344  Assert(rte->rtekind == RTE_FUNCTION);
1345 
1346  /* Mark the path with the correct row estimate */
1347  if (param_info)
1348  path->rows = param_info->ppi_rows;
1349  else
1350  path->rows = baserel->rows;
1351 
1352  /*
1353  * Estimate costs of executing the function expression(s).
1354  *
1355  * Currently, nodeFunctionscan.c always executes the functions to
1356  * completion before returning any rows, and caches the results in a
1357  * tuplestore. So the function eval cost is all startup cost, and per-row
1358  * costs are minimal.
1359  *
1360  * XXX in principle we ought to charge tuplestore spill costs if the
1361  * number of rows is large. However, given how phony our rowcount
1362  * estimates for functions tend to be, there's not a lot of point in that
1363  * refinement right now.
1364  */
1365  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1366 
1367  startup_cost += exprcost.startup + exprcost.per_tuple;
1368 
1369  /* Add scanning CPU costs */
1370  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1371 
1372  startup_cost += qpqual_cost.startup;
1373  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1374  run_cost += cpu_per_tuple * baserel->tuples;
1375 
1376  /* tlist eval costs are paid per output row, not per tuple scanned */
1377  startup_cost += path->pathtarget->cost.startup;
1378  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1379 
1380  path->startup_cost = startup_cost;
1381  path->total_cost = startup_cost + run_cost;
1382 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3845
PathTarget * pathtarget
Definition: pathnodes.h:1115
double tuples
Definition: pathnodes.h:681
Definition: nodes.h:525
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1125
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:371
Index relid
Definition: pathnodes.h:669
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4105
#define Assert(condition)
Definition: c.h:732
List * functions
Definition: parsenodes.h:1040
double rows
Definition: pathnodes.h:1124
QualCost cost
Definition: pathnodes.h:1046
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
RTEKind rtekind
Definition: parsenodes.h:974
double Cost
Definition: nodes.h:659

◆ cost_gather()

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

Definition at line 363 of file costsize.c.

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().

366 {
367  Cost startup_cost = 0;
368  Cost run_cost = 0;
369 
370  /* Mark the path with the correct row estimate */
371  if (rows)
372  path->path.rows = *rows;
373  else if (param_info)
374  path->path.rows = param_info->ppi_rows;
375  else
376  path->path.rows = rel->rows;
377 
378  startup_cost = path->subpath->startup_cost;
379 
380  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
381 
382  /* Parallel setup and communication cost. */
383  startup_cost += parallel_setup_cost;
384  run_cost += parallel_tuple_cost * path->path.rows;
385 
386  path->path.startup_cost = startup_cost;
387  path->path.total_cost = (startup_cost + run_cost);
388 }
double parallel_setup_cost
Definition: costsize.c:116
Cost startup_cost
Definition: pathnodes.h:1125
Path * subpath
Definition: pathnodes.h:1465
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
double rows
Definition: pathnodes.h:1124
double ppi_rows
Definition: pathnodes.h:1074
double Cost
Definition: nodes.h:659
double parallel_tuple_cost
Definition: costsize.c:115

◆ 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 401 of file costsize.c.

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().

405 {
406  Cost startup_cost = 0;
407  Cost run_cost = 0;
408  Cost comparison_cost;
409  double N;
410  double logN;
411 
412  /* Mark the path with the correct row estimate */
413  if (rows)
414  path->path.rows = *rows;
415  else if (param_info)
416  path->path.rows = param_info->ppi_rows;
417  else
418  path->path.rows = rel->rows;
419 
420  if (!enable_gathermerge)
421  startup_cost += disable_cost;
422 
423  /*
424  * Add one to the number of workers to account for the leader. This might
425  * be overgenerous since the leader will do less work than other workers
426  * in typical cases, but we'll go with it for now.
427  */
428  Assert(path->num_workers > 0);
429  N = (double) path->num_workers + 1;
430  logN = LOG2(N);
431 
432  /* Assumed cost per tuple comparison */
433  comparison_cost = 2.0 * cpu_operator_cost;
434 
435  /* Heap creation cost */
436  startup_cost += comparison_cost * N * logN;
437 
438  /* Per-tuple heap maintenance cost */
439  run_cost += path->path.rows * comparison_cost * logN;
440 
441  /* small cost for heap management, like cost_merge_append */
442  run_cost += cpu_operator_cost * path->path.rows;
443 
444  /*
445  * Parallel setup and communication cost. Since Gather Merge, unlike
446  * Gather, requires us to block until a tuple is available from every
447  * worker, we bump the IPC cost up a little bit as compared with Gather.
448  * For lack of a better idea, charge an extra 5%.
449  */
450  startup_cost += parallel_setup_cost;
451  run_cost += parallel_tuple_cost * path->path.rows * 1.05;
452 
453  path->path.startup_cost = startup_cost + input_startup_cost;
454  path->path.total_cost = (startup_cost + run_cost + input_total_cost);
455 }
double parallel_setup_cost
Definition: costsize.c:116
Cost startup_cost
Definition: pathnodes.h:1125
Cost disable_cost
Definition: costsize.c:120
double cpu_operator_cost
Definition: costsize.c:114
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
#define LOG2(x)
Definition: costsize.c:100
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
double ppi_rows
Definition: pathnodes.h:1074
bool enable_gathermerge
Definition: costsize.c:135
double Cost
Definition: nodes.h:659
double parallel_tuple_cost
Definition: costsize.c:115

◆ 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 2346 of file costsize.c.

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().

2351 {
2352  double output_tuples;
2353  Cost startup_cost;
2354  Cost total_cost;
2355 
2356  output_tuples = numGroups;
2357  startup_cost = input_startup_cost;
2358  total_cost = input_total_cost;
2359 
2360  /*
2361  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2362  * all columns get compared at most of the tuples.
2363  */
2364  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2365 
2366  /*
2367  * If there are quals (HAVING quals), account for their cost and
2368  * selectivity.
2369  */
2370  if (quals)
2371  {
2372  QualCost qual_cost;
2373 
2374  cost_qual_eval(&qual_cost, quals, root);
2375  startup_cost += qual_cost.startup;
2376  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2377 
2378  output_tuples = clamp_row_est(output_tuples *
2380  quals,
2381  0,
2382  JOIN_INNER,
2383  NULL));
2384  }
2385 
2386  path->rows = output_tuples;
2387  path->startup_cost = startup_cost;
2388  path->total_cost = total_cost;
2389 }
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3819
Cost startup_cost
Definition: pathnodes.h:1125
double cpu_operator_cost
Definition: costsize.c:114
Cost total_cost
Definition: pathnodes.h:1126
double rows
Definition: pathnodes.h:1124
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:70
double clamp_row_est(double nrows)
Definition: costsize.c:187
double Cost
Definition: nodes.h:659

◆ cost_index()

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

Definition at line 476 of file costsize.c.

References RelOptInfo::allvisfrac, IndexOptInfo::amcostestimate, Assert, clamp_row_est(), compute_parallel_worker(), PathTarget::cost, 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, IndexOptInfo::pages, Path::parallel_aware, Path::parallel_workers, Path::param_info, IndexPath::path, Path::pathtarget, Path::pathtype, QualCost::per_tuple, ParamPathInfo::ppi_clauses, ParamPathInfo::ppi_rows, IndexOptInfo::rel, RelOptInfo::relid, RelOptInfo::reltablespace, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, T_IndexOnlyScan, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_index_path(), and reparameterize_path().

478 {
479  IndexOptInfo *index = path->indexinfo;
480  RelOptInfo *baserel = index->rel;
481  bool indexonly = (path->path.pathtype == T_IndexOnlyScan);
482  amcostestimate_function amcostestimate;
483  List *qpquals;
484  Cost startup_cost = 0;
485  Cost run_cost = 0;
486  Cost cpu_run_cost = 0;
487  Cost indexStartupCost;
488  Cost indexTotalCost;
489  Selectivity indexSelectivity;
490  double indexCorrelation,
491  csquared;
492  double spc_seq_page_cost,
493  spc_random_page_cost;
494  Cost min_IO_cost,
495  max_IO_cost;
496  QualCost qpqual_cost;
497  Cost cpu_per_tuple;
498  double tuples_fetched;
499  double pages_fetched;
500  double rand_heap_pages;
501  double index_pages;
502 
503  /* Should only be applied to base relations */
504  Assert(IsA(baserel, RelOptInfo) &&
505  IsA(index, IndexOptInfo));
506  Assert(baserel->relid > 0);
507  Assert(baserel->rtekind == RTE_RELATION);
508 
509  /*
510  * Mark the path with the correct row estimate, and identify which quals
511  * will need to be enforced as qpquals. We need not check any quals that
512  * are implied by the index's predicate, so we can use indrestrictinfo not
513  * baserestrictinfo as the list of relevant restriction clauses for the
514  * rel.
515  */
516  if (path->path.param_info)
517  {
518  path->path.rows = path->path.param_info->ppi_rows;
519  /* qpquals come from the rel's restriction clauses and ppi_clauses */
521  path->indexclauses),
523  path->indexclauses));
524  }
525  else
526  {
527  path->path.rows = baserel->rows;
528  /* qpquals come from just the rel's restriction clauses */
530  path->indexclauses);
531  }
532 
533  if (!enable_indexscan)
534  startup_cost += disable_cost;
535  /* we don't need to check enable_indexonlyscan; indxpath.c does that */
536 
537  /*
538  * Call index-access-method-specific code to estimate the processing cost
539  * for scanning the index, as well as the selectivity of the index (ie,
540  * the fraction of main-table tuples we will have to retrieve) and its
541  * correlation to the main-table tuple order. We need a cast here because
542  * pathnodes.h uses a weak function type to avoid including amapi.h.
543  */
544  amcostestimate = (amcostestimate_function) index->amcostestimate;
545  amcostestimate(root, path, loop_count,
546  &indexStartupCost, &indexTotalCost,
547  &indexSelectivity, &indexCorrelation,
548  &index_pages);
549 
550  /*
551  * Save amcostestimate's results for possible use in bitmap scan planning.
552  * We don't bother to save indexStartupCost or indexCorrelation, because a
553  * bitmap scan doesn't care about either.
554  */
555  path->indextotalcost = indexTotalCost;
556  path->indexselectivity = indexSelectivity;
557 
558  /* all costs for touching index itself included here */
559  startup_cost += indexStartupCost;
560  run_cost += indexTotalCost - indexStartupCost;
561 
562  /* estimate number of main-table tuples fetched */
563  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
564 
565  /* fetch estimated page costs for tablespace containing table */
567  &spc_random_page_cost,
568  &spc_seq_page_cost);
569 
570  /*----------
571  * Estimate number of main-table pages fetched, and compute I/O cost.
572  *
573  * When the index ordering is uncorrelated with the table ordering,
574  * we use an approximation proposed by Mackert and Lohman (see
575  * index_pages_fetched() for details) to compute the number of pages
576  * fetched, and then charge spc_random_page_cost per page fetched.
577  *
578  * When the index ordering is exactly correlated with the table ordering
579  * (just after a CLUSTER, for example), the number of pages fetched should
580  * be exactly selectivity * table_size. What's more, all but the first
581  * will be sequential fetches, not the random fetches that occur in the
582  * uncorrelated case. So if the number of pages is more than 1, we
583  * ought to charge
584  * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
585  * For partially-correlated indexes, we ought to charge somewhere between
586  * these two estimates. We currently interpolate linearly between the
587  * estimates based on the correlation squared (XXX is that appropriate?).
588  *
589  * If it's an index-only scan, then we will not need to fetch any heap
590  * pages for which the visibility map shows all tuples are visible.
591  * Hence, reduce the estimated number of heap fetches accordingly.
592  * We use the measured fraction of the entire heap that is all-visible,
593  * which might not be particularly relevant to the subset of the heap
594  * that this query will fetch; but it's not clear how to do better.
595  *----------
596  */
597  if (loop_count > 1)
598  {
599  /*
600  * For repeated indexscans, the appropriate estimate for the
601  * uncorrelated case is to scale up the number of tuples fetched in
602  * the Mackert and Lohman formula by the number of scans, so that we
603  * estimate the number of pages fetched by all the scans; then
604  * pro-rate the costs for one scan. In this case we assume all the
605  * fetches are random accesses.
606  */
607  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
608  baserel->pages,
609  (double) index->pages,
610  root);
611 
612  if (indexonly)
613  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
614 
615  rand_heap_pages = pages_fetched;
616 
617  max_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
618 
619  /*
620  * In the perfectly correlated case, the number of pages touched by
621  * each scan is selectivity * table_size, and we can use the Mackert
622  * and Lohman formula at the page level to estimate how much work is
623  * saved by caching across scans. We still assume all the fetches are
624  * random, though, which is an overestimate that's hard to correct for
625  * without double-counting the cache effects. (But in most cases
626  * where such a plan is actually interesting, only one page would get
627  * fetched per scan anyway, so it shouldn't matter much.)
628  */
629  pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
630 
631  pages_fetched = index_pages_fetched(pages_fetched * loop_count,
632  baserel->pages,
633  (double) index->pages,
634  root);
635 
636  if (indexonly)
637  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
638 
639  min_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
640  }
641  else
642  {
643  /*
644  * Normal case: apply the Mackert and Lohman formula, and then
645  * interpolate between that and the correlation-derived result.
646  */
647  pages_fetched = index_pages_fetched(tuples_fetched,
648  baserel->pages,
649  (double) index->pages,
650  root);
651 
652  if (indexonly)
653  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
654 
655  rand_heap_pages = pages_fetched;
656 
657  /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
658  max_IO_cost = pages_fetched * spc_random_page_cost;
659 
660  /* min_IO_cost is for the perfectly correlated case (csquared=1) */
661  pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
662 
663  if (indexonly)
664  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
665 
666  if (pages_fetched > 0)
667  {
668  min_IO_cost = spc_random_page_cost;
669  if (pages_fetched > 1)
670  min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
671  }
672  else
673  min_IO_cost = 0;
674  }
675 
676  if (partial_path)
677  {
678  /*
679  * For index only scans compute workers based on number of index pages
680  * fetched; the number of heap pages we fetch might be so small as to
681  * effectively rule out parallelism, which we don't want to do.
682  */
683  if (indexonly)
684  rand_heap_pages = -1;
685 
686  /*
687  * Estimate the number of parallel workers required to scan index. Use
688  * the number of heap pages computed considering heap fetches won't be
689  * sequential as for parallel scans the pages are accessed in random
690  * order.
691  */
693  rand_heap_pages,
694  index_pages,
696 
697  /*
698  * Fall out if workers can't be assigned for parallel scan, because in
699  * such a case this path will be rejected. So there is no benefit in
700  * doing extra computation.
701  */
702  if (path->path.parallel_workers <= 0)
703  return;
704 
705  path->path.parallel_aware = true;
706  }
707 
708  /*
709  * Now interpolate based on estimated index order correlation to get total
710  * disk I/O cost for main table accesses.
711  */
712  csquared = indexCorrelation * indexCorrelation;
713 
714  run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
715 
716  /*
717  * Estimate CPU costs per tuple.
718  *
719  * What we want here is cpu_tuple_cost plus the evaluation costs of any
720  * qual clauses that we have to evaluate as qpquals.
721  */
722  cost_qual_eval(&qpqual_cost, qpquals, root);
723 
724  startup_cost += qpqual_cost.startup;
725  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
726 
727  cpu_run_cost += cpu_per_tuple * tuples_fetched;
728 
729  /* tlist eval costs are paid per output row, not per tuple scanned */
730  startup_cost += path->path.pathtarget->cost.startup;
731  cpu_run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
732 
733  /* Adjust costing for parallelism, if used. */
734  if (path->path.parallel_workers > 0)
735  {
736  double parallel_divisor = get_parallel_divisor(&path->path);
737 
738  path->path.rows = clamp_row_est(path->path.rows / parallel_divisor);
739 
740  /* The CPU cost is divided among all the workers. */
741  cpu_run_cost /= parallel_divisor;
742  }
743 
744  run_cost += cpu_run_cost;
745 
746  path->path.startup_cost = startup_cost;
747  path->path.total_cost = startup_cost + run_cost;
748 }
static List * extract_nonindex_conditions(List *qual_clauses, List *indexclauses)
Definition: costsize.c:767
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
PathTarget * pathtarget
Definition: pathnodes.h:1115
Path path
Definition: pathnodes.h:1176
IndexOptInfo * indexinfo
Definition: pathnodes.h:1177
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:3575
double tuples
Definition: pathnodes.h:681
Oid reltablespace
Definition: pathnodes.h:670
int parallel_workers
Definition: pathnodes.h:1121
ParamPathInfo * param_info
Definition: pathnodes.h:1117
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
List * indexclauses
Definition: pathnodes.h:1178
double Selectivity
Definition: nodes.h:658
Cost startup
Definition: pathnodes.h:45
double allvisfrac
Definition: pathnodes.h:682
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:794
NodeTag pathtype
Definition: pathnodes.h:1112
Cost per_tuple
Definition: pathnodes.h:46
RelOptInfo * rel
Definition: pathnodes.h:791
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3819
Cost startup_cost
Definition: pathnodes.h:1125
Cost indextotalcost
Definition: pathnodes.h:1182
Cost disable_cost
Definition: costsize.c:120
Selectivity indexselectivity
Definition: pathnodes.h:1183
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5475
void(* amcostestimate)()
Definition: pathnodes.h:838
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: pathnodes.h:669
List * indrestrictinfo
Definition: pathnodes.h:818
RTEKind rtekind
Definition: pathnodes.h:671
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
BlockNumber pages
Definition: pathnodes.h:680
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
List * ppi_clauses
Definition: pathnodes.h:1075
QualCost cost
Definition: pathnodes.h:1046
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
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:93
bool parallel_aware
Definition: pathnodes.h:1119
double clamp_row_est(double nrows)
Definition: costsize.c:187
int max_parallel_workers_per_gather
Definition: costsize.c:122
Definition: pg_list.h:50
bool enable_indexscan
Definition: costsize.c:125
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:825
double Cost
Definition: nodes.h:659

◆ cost_material()

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

Definition at line 2097 of file costsize.c.

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().

2100 {
2101  Cost startup_cost = input_startup_cost;
2102  Cost run_cost = input_total_cost - input_startup_cost;
2103  double nbytes = relation_byte_size(tuples, width);
2104  long work_mem_bytes = work_mem * 1024L;
2105 
2106  path->rows = tuples;
2107 
2108  /*
2109  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2110  * reflect bookkeeping overhead. (This rate must be more than what
2111  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2112  * if it is exactly the same then there will be a cost tie between
2113  * nestloop with A outer, materialized B inner and nestloop with B outer,
2114  * materialized A inner. The extra cost ensures we'll prefer
2115  * materializing the smaller rel.) Note that this is normally a good deal
2116  * less than cpu_tuple_cost; which is OK because a Material plan node
2117  * doesn't do qual-checking or projection, so it's got less overhead than
2118  * most plan nodes.
2119  */
2120  run_cost += 2 * cpu_operator_cost * tuples;
2121 
2122  /*
2123  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2124  * This cost is assumed to be evenly spread through the plan run phase,
2125  * which isn't exactly accurate but our cost model doesn't allow for
2126  * nonuniform costs within the run phase.
2127  */
2128  if (nbytes > work_mem_bytes)
2129  {
2130  double npages = ceil(nbytes / BLCKSZ);
2131 
2132  run_cost += seq_page_cost * npages;
2133  }
2134 
2135  path->startup_cost = startup_cost;
2136  path->total_cost = startup_cost + run_cost;
2137 }
Cost startup_cost
Definition: pathnodes.h:1125
double cpu_operator_cost
Definition: costsize.c:114
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5454
int work_mem
Definition: globals.c:121
Cost total_cost
Definition: pathnodes.h:1126
double rows
Definition: pathnodes.h:1124
double seq_page_cost
Definition: costsize.c:110
double Cost
Definition: nodes.h:659

◆ 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 2048 of file costsize.c.

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().

2052 {
2053  Cost startup_cost = 0;
2054  Cost run_cost = 0;
2055  Cost comparison_cost;
2056  double N;
2057  double logN;
2058 
2059  /*
2060  * Avoid log(0)...
2061  */
2062  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2063  logN = LOG2(N);
2064 
2065  /* Assumed cost per tuple comparison */
2066  comparison_cost = 2.0 * cpu_operator_cost;
2067 
2068  /* Heap creation cost */
2069  startup_cost += comparison_cost * N * logN;
2070 
2071  /* Per-tuple heap maintenance cost */
2072  run_cost += tuples * comparison_cost * logN;
2073 
2074  /*
2075  * Although MergeAppend does not do any selection or projection, it's not
2076  * free; add a small per-tuple overhead.
2077  */
2078  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2079 
2080  path->startup_cost = startup_cost + input_startup_cost;
2081  path->total_cost = startup_cost + run_cost + input_total_cost;
2082 }
Cost startup_cost
Definition: pathnodes.h:1125
double cpu_operator_cost
Definition: costsize.c:114
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:107
Cost total_cost
Definition: pathnodes.h:1126
#define LOG2(x)
Definition: costsize.c:100
double cpu_tuple_cost
Definition: costsize.c:112
double Cost
Definition: nodes.h:659

◆ cost_namedtuplestorescan()

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

Definition at line 1539 of file costsize.c.

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().

1541 {
1542  Cost startup_cost = 0;
1543  Cost run_cost = 0;
1544  QualCost qpqual_cost;
1545  Cost cpu_per_tuple;
1546 
1547  /* Should only be applied to base relations that are Tuplestores */
1548  Assert(baserel->relid > 0);
1549  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1550 
1551  /* Mark the path with the correct row estimate */
1552  if (param_info)
1553  path->rows = param_info->ppi_rows;
1554  else
1555  path->rows = baserel->rows;
1556 
1557  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1558  cpu_per_tuple = cpu_tuple_cost;
1559 
1560  /* Add scanning CPU costs */
1561  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1562 
1563  startup_cost += qpqual_cost.startup;
1564  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1565  run_cost += cpu_per_tuple * baserel->tuples;
1566 
1567  path->startup_cost = startup_cost;
1568  path->total_cost = startup_cost + run_cost;
1569 }
double tuples
Definition: pathnodes.h:681
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1125
Index relid
Definition: pathnodes.h:669
RTEKind rtekind
Definition: pathnodes.h:671
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4105
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
double Cost
Definition: nodes.h:659

◆ cost_qual_eval()

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

Definition at line 3819 of file costsize.c.

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_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().

3820 {
3821  cost_qual_eval_context context;
3822  ListCell *l;
3823 
3824  context.root = root;
3825  context.total.startup = 0;
3826  context.total.per_tuple = 0;
3827 
3828  /* We don't charge any cost for the implicit ANDing at top level ... */
3829 
3830  foreach(l, quals)
3831  {
3832  Node *qual = (Node *) lfirst(l);
3833 
3834  cost_qual_eval_walker(qual, &context);
3835  }
3836 
3837  *cost = context.total;
3838 }
PlannerInfo * root
Definition: costsize.c:144
Definition: nodes.h:525
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:3859
#define lfirst(lc)
Definition: pg_list.h:190

◆ cost_qual_eval_node()

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

Definition at line 3845 of file costsize.c.

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

Referenced by add_placeholders_to_joinrel(), cost_functionscan(), cost_qual_eval_walker(), cost_tablefuncscan(), cost_windowagg(), get_agg_clause_costs_walker(), index_other_operands_eval_cost(), make_sort_input_target(), order_qual_clauses(), set_pathtarget_cost_width(), and set_rel_width().

3846 {
3847  cost_qual_eval_context context;
3848 
3849  context.root = root;
3850  context.total.startup = 0;
3851  context.total.per_tuple = 0;
3852 
3853  cost_qual_eval_walker(qual, &context);
3854 
3855  *cost = context.total;
3856 }
PlannerInfo * root
Definition: costsize.c:144
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:3859

◆ cost_qual_eval_walker()

static bool cost_qual_eval_walker ( Node node,
cost_qual_eval_context context 
)
static

Definition at line 3859 of file costsize.c.

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(), RestrictInfo::eval_cost, expression_tree_walker(), exprType(), get_opcode(), getTypeInputInfo(), getTypeOutputInfo(), IsA, lfirst_oid, linitial, lsecond, ScalarArrayOpExpr::opfuncid, RowCompareExpr::opnos, RestrictInfo::orclause, SubPlan::per_call_cost, QualCost::per_tuple, RestrictInfo::pseudoconstant, 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().

3860 {
3861  if (node == NULL)
3862  return false;
3863 
3864  /*
3865  * RestrictInfo nodes contain an eval_cost field reserved for this
3866  * routine's use, so that it's not necessary to evaluate the qual clause's
3867  * cost more than once. If the clause's cost hasn't been computed yet,
3868  * the field's startup value will contain -1.
3869  */
3870  if (IsA(node, RestrictInfo))
3871  {
3872  RestrictInfo *rinfo = (RestrictInfo *) node;
3873 
3874  if (rinfo->eval_cost.startup < 0)
3875  {
3876  cost_qual_eval_context locContext;
3877 
3878  locContext.root = context->root;
3879  locContext.total.startup = 0;
3880  locContext.total.per_tuple = 0;
3881 
3882  /*
3883  * For an OR clause, recurse into the marked-up tree so that we
3884  * set the eval_cost for contained RestrictInfos too.
3885  */
3886  if (rinfo->orclause)
3887  cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
3888  else
3889  cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
3890 
3891  /*
3892  * If the RestrictInfo is marked pseudoconstant, it will be tested
3893  * only once, so treat its cost as all startup cost.
3894  */
3895  if (rinfo->pseudoconstant)
3896  {
3897  /* count one execution during startup */
3898  locContext.total.startup += locContext.total.per_tuple;
3899  locContext.total.per_tuple = 0;
3900  }
3901  rinfo->eval_cost = locContext.total;
3902  }
3903  context->total.startup += rinfo->eval_cost.startup;
3904  context->total.per_tuple += rinfo->eval_cost.per_tuple;
3905  /* do NOT recurse into children */
3906  return false;
3907  }
3908 
3909  /*
3910  * For each operator or function node in the given tree, we charge the
3911  * estimated execution cost given by pg_proc.procost (remember to multiply
3912  * this by cpu_operator_cost).
3913  *
3914  * Vars and Consts are charged zero, and so are boolean operators (AND,
3915  * OR, NOT). Simplistic, but a lot better than no model at all.
3916  *
3917  * Should we try to account for the possibility of short-circuit
3918  * evaluation of AND/OR? Probably *not*, because that would make the
3919  * results depend on the clause ordering, and we are not in any position
3920  * to expect that the current ordering of the clauses is the one that's
3921  * going to end up being used. The above per-RestrictInfo caching would
3922  * not mix well with trying to re-order clauses anyway.
3923  *
3924  * Another issue that is entirely ignored here is that if a set-returning
3925  * function is below top level in the tree, the functions/operators above
3926  * it will need to be evaluated multiple times. In practical use, such
3927  * cases arise so seldom as to not be worth the added complexity needed;
3928  * moreover, since our rowcount estimates for functions tend to be pretty
3929  * phony, the results would also be pretty phony.
3930  */
3931  if (IsA(node, FuncExpr))
3932  {
3933  add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
3934  &context->total);
3935  }
3936  else if (IsA(node, OpExpr) ||
3937  IsA(node, DistinctExpr) ||
3938  IsA(node, NullIfExpr))
3939  {
3940  /* rely on struct equivalence to treat these all alike */
3941  set_opfuncid((OpExpr *) node);
3942  add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
3943  &context->total);
3944  }
3945  else if (IsA(node, ScalarArrayOpExpr))
3946  {
3947  /*
3948  * Estimate that the operator will be applied to about half of the
3949  * array elements before the answer is determined.
3950  */
3951  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
3952  Node *arraynode = (Node *) lsecond(saop->args);
3953  QualCost sacosts;
3954 
3955  set_sa_opfuncid(saop);
3956  sacosts.startup = sacosts.per_tuple = 0;
3957  add_function_cost(context->root, saop->opfuncid, NULL,
3958  &sacosts);
3959  context->total.startup += sacosts.startup;
3960  context->total.per_tuple += sacosts.per_tuple *
3961  estimate_array_length(arraynode) * 0.5;
3962  }
3963  else if (IsA(node, Aggref) ||
3964  IsA(node, WindowFunc))
3965  {
3966  /*
3967  * Aggref and WindowFunc nodes are (and should be) treated like Vars,
3968  * ie, zero execution cost in the current model, because they behave
3969  * essentially like Vars at execution. We disregard the costs of
3970  * their input expressions for the same reason. The actual execution
3971  * costs of the aggregate/window functions and their arguments have to
3972  * be factored into plan-node-specific costing of the Agg or WindowAgg
3973  * plan node.
3974  */
3975  return false; /* don't recurse into children */
3976  }
3977  else if (IsA(node, CoerceViaIO))
3978  {
3979  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
3980  Oid iofunc;
3981  Oid typioparam;
3982  bool typisvarlena;
3983 
3984  /* check the result type's input function */
3985  getTypeInputInfo(iocoerce->resulttype,
3986  &iofunc, &typioparam);
3987  add_function_cost(context->root, iofunc, NULL,
3988  &context->total);
3989  /* check the input type's output function */
3990  getTypeOutputInfo(exprType((Node *) iocoerce->arg),
3991  &iofunc, &typisvarlena);
3992  add_function_cost(context->root, iofunc, NULL,
3993  &context->total);
3994  }
3995  else if (IsA(node, ArrayCoerceExpr))
3996  {
3997  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
3998  QualCost perelemcost;
3999 
4000  cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
4001  context->root);
4002  context->total.startup += perelemcost.startup;
4003  if (perelemcost.per_tuple > 0)
4004  context->total.per_tuple += perelemcost.per_tuple *
4005  estimate_array_length((Node *) acoerce->arg);
4006  }
4007  else if (IsA(node, RowCompareExpr))
4008  {
4009  /* Conservatively assume we will check all the columns */
4010  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
4011  ListCell *lc;
4012 
4013  foreach(lc, rcexpr->opnos)
4014  {
4015  Oid opid = lfirst_oid(lc);
4016 
4017  add_function_cost(context->root, get_opcode(opid), NULL,
4018  &context->total);
4019  }
4020  }
4021  else if (IsA(node, MinMaxExpr) ||
4022  IsA(node, SQLValueFunction) ||
4023  IsA(node, XmlExpr) ||
4024  IsA(node, CoerceToDomain) ||
4025  IsA(node, NextValueExpr))
4026  {
4027  /* Treat all these as having cost 1 */
4028  context->total.per_tuple += cpu_operator_cost;
4029  }
4030  else if (IsA(node, CurrentOfExpr))
4031  {
4032  /* Report high cost to prevent selection of anything but TID scan */
4033  context->total.startup += disable_cost;
4034  }
4035  else if (IsA(node, SubLink))
4036  {
4037  /* This routine should not be applied to un-planned expressions */
4038  elog(ERROR, "cannot handle unplanned sub-select");
4039  }
4040  else if (IsA(node, SubPlan))
4041  {
4042  /*
4043  * A subplan node in an expression typically indicates that the
4044  * subplan will be executed on each evaluation, so charge accordingly.
4045  * (Sub-selects that can be executed as InitPlans have already been
4046  * removed from the expression.)
4047  */
4048  SubPlan *subplan = (SubPlan *) node;
4049 
4050  context->total.startup += subplan->startup_cost;
4051  context->total.per_tuple += subplan->per_call_cost;
4052 
4053  /*
4054  * We don't want to recurse into the testexpr, because it was already
4055  * counted in the SubPlan node's costs. So we're done.
4056  */
4057  return false;
4058  }
4059  else if (IsA(node, AlternativeSubPlan))
4060  {
4061  /*
4062  * Arbitrarily use the first alternative plan for costing. (We should
4063  * certainly only include one alternative, and we don't yet have
4064  * enough information to know which one the executor is most likely to
4065  * use.)
4066  */
4067  AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
4068 
4069  return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
4070  context);
4071  }
4072  else if (IsA(node, PlaceHolderVar))
4073  {
4074  /*
4075  * A PlaceHolderVar should be given cost zero when considering general
4076  * expression evaluation costs. The expense of doing the contained
4077  * expression is charged as part of the tlist eval costs of the scan
4078  * or join where the PHV is first computed (see set_rel_width and
4079  * add_placeholders_to_joinrel). If we charged it again here, we'd be
4080  * double-counting the cost for each level of plan that the PHV
4081  * bubbles up through. Hence, return without recursing into the
4082  * phexpr.
4083  */
4084  return false;
4085  }
4086 
4087  /* recurse into children */
4089  (void *) context);
4090 }
QualCost eval_cost
Definition: pathnodes.h:1980
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3845
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
PlannerInfo * root
Definition: costsize.c:144
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2674
Expr * orclause
Definition: pathnodes.h:1974
Oid resulttype
Definition: primnodes.h:821
bool pseudoconstant
Definition: pathnodes.h:1951
Definition: nodes.h:525
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1906
unsigned int Oid
Definition: postgres_ext.h:31
#define lsecond(l)
Definition: pg_list.h:200
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:1890
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
Cost disable_cost
Definition: costsize.c:120
double cpu_operator_cost
Definition: costsize.c:114
Expr * arg
Definition: primnodes.h:820
Expr * elemexpr
Definition: primnodes.h:845
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2641
Expr * clause
Definition: pathnodes.h:1943
Cost per_call_cost
Definition: primnodes.h:719
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1092
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:3859
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1840
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1619
#define elog(elevel,...)
Definition: elog.h:226
Cost startup_cost
Definition: primnodes.h:718
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1630
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ cost_recursive_union()

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

Definition at line 1613 of file costsize.c.

References cpu_tuple_cost, Max, Path::pathtarget, Path::rows, Path::startup_cost, Path::total_cost, and PathTarget::width.

Referenced by create_recursiveunion_path().

1614 {
1615  Cost startup_cost;
1616  Cost total_cost;
1617  double total_rows;
1618 
1619  /* We probably have decent estimates for the non-recursive term */
1620  startup_cost = nrterm->startup_cost;
1621  total_cost = nrterm->total_cost;
1622  total_rows = nrterm->rows;
1623 
1624  /*
1625  * We arbitrarily assume that about 10 recursive iterations will be
1626  * needed, and that we've managed to get a good fix on the cost and output
1627  * size of each one of them. These are mighty shaky assumptions but it's
1628  * hard to see how to do better.
1629  */
1630  total_cost += 10 * rterm->total_cost;
1631  total_rows += 10 * rterm->rows;
1632 
1633  /*
1634  * Also charge cpu_tuple_cost per row to account for the costs of
1635  * manipulating the tuplestores. (We don't worry about possible
1636  * spill-to-disk costs.)
1637  */
1638  total_cost += cpu_tuple_cost * total_rows;
1639 
1640  runion->startup_cost = startup_cost;
1641  runion->total_cost = total_cost;
1642  runion->rows = total_rows;
1643  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1644  rterm->pathtarget->width);
1645 }
PathTarget * pathtarget
Definition: pathnodes.h:1115
Cost startup_cost
Definition: pathnodes.h:1125
Cost total_cost
Definition: pathnodes.h:1126
#define Max(x, y)
Definition: c.h:898
double rows
Definition: pathnodes.h:1124
double cpu_tuple_cost
Definition: costsize.c:112
double Cost
Definition: nodes.h:659

◆ cost_rescan()

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

Definition at line 3712 of file costsize.c.

References cpu_operator_cost, cpu_tuple_cost, Path::pathtype, relation_byte_size(), seq_page_cost, Path::startup_cost, T_CteScan, T_FunctionScan, T_HashJoin, T_Material, T_Sort, T_WorkTableScan, Path::total_cost, and work_mem.

Referenced by initial_cost_nestloop().

3715 {
3716  switch (path->pathtype)
3717  {
3718  case T_FunctionScan:
3719 
3720  /*
3721  * Currently, nodeFunctionscan.c always executes the function to
3722  * completion before returning any rows, and caches the results in
3723  * a tuplestore. So the function eval cost is all startup cost
3724  * and isn't paid over again on rescans. However, all run costs
3725  * will be paid over again.
3726  */
3727  *rescan_startup_cost = 0;
3728  *rescan_total_cost = path->total_cost - path->startup_cost;
3729  break;
3730  case T_HashJoin:
3731 
3732  /*
3733  * If it's a single-batch join, we don't need to rebuild the hash
3734  * table during a rescan.
3735  */
3736  if (((HashPath *) path)->num_batches == 1)
3737  {
3738  /* Startup cost is exactly the cost of hash table building */
3739  *rescan_startup_cost = 0;
3740  *rescan_total_cost = path->total_cost - path->startup_cost;
3741  }
3742  else
3743  {
3744  /* Otherwise, no special treatment */
3745  *rescan_startup_cost = path->startup_cost;
3746  *rescan_total_cost = path->total_cost;
3747  }
3748  break;
3749  case T_CteScan:
3750  case T_WorkTableScan:
3751  {
3752  /*
3753  * These plan types materialize their final result in a
3754  * tuplestore or tuplesort object. So the rescan cost is only
3755  * cpu_tuple_cost per tuple, unless the result is large enough
3756  * to spill to disk.
3757  */
3758  Cost run_cost = cpu_tuple_cost * path->rows;
3759  double nbytes = relation_byte_size(path->rows,
3760  path->pathtarget->width);
3761  long work_mem_bytes = work_mem * 1024L;
3762 
3763  if (nbytes > work_mem_bytes)
3764  {
3765  /* It will spill, so account for re-read cost */
3766  double npages = ceil(nbytes / BLCKSZ);
3767 
3768  run_cost += seq_page_cost * npages;
3769  }
3770  *rescan_startup_cost = 0;
3771  *rescan_total_cost = run_cost;
3772  }
3773  break;
3774  case T_Material:
3775  case T_Sort:
3776  {
3777  /*
3778  * These plan types not only materialize their results, but do
3779  * not implement qual filtering or projection. So they are
3780  * even cheaper to rescan than the ones above. We charge only
3781  * cpu_operator_cost per tuple. (Note: keep that in sync with
3782  * the run_cost charge in cost_sort, and also see comments in
3783  * cost_material before you change it.)
3784  */
3785  Cost run_cost = cpu_operator_cost * path->rows;
3786  double nbytes = relation_byte_size(path->rows,
3787  path->pathtarget->width);
3788  long work_mem_bytes = work_mem * 1024L;
3789 
3790  if (nbytes > work_mem_bytes)
3791  {
3792  /* It will spill, so account for re-read cost */
3793  double npages = ceil(nbytes / BLCKSZ);
3794 
3795  run_cost += seq_page_cost * npages;
3796  }
3797  *rescan_startup_cost = 0;
3798  *rescan_total_cost = run_cost;
3799  }
3800  break;
3801  default:
3802  *rescan_startup_cost = path->startup_cost;
3803  *rescan_total_cost = path->total_cost;
3804  break;
3805  }
3806 }
Definition: nodes.h:76
NodeTag pathtype
Definition: pathnodes.h:1112
Cost startup_cost
Definition: pathnodes.h:1125
double cpu_operator_cost
Definition: costsize.c:114
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5454
int work_mem
Definition: globals.c:121
Cost total_cost
Definition: pathnodes.h:1126
double cpu_tuple_cost
Definition: costsize.c:112
double seq_page_cost
Definition: costsize.c:110
double Cost
Definition: nodes.h:659

◆ cost_resultscan()

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

Definition at line 1576 of file costsize.c.

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().

1578 {
1579  Cost startup_cost = 0;
1580  Cost run_cost = 0;
1581  QualCost qpqual_cost;
1582  Cost cpu_per_tuple;
1583 
1584  /* Should only be applied to RTE_RESULT base relations */
1585  Assert(baserel->relid > 0);
1586  Assert(baserel->rtekind == RTE_RESULT);
1587 
1588  /* Mark the path with the correct row estimate */
1589  if (param_info)
1590  path->rows = param_info->ppi_rows;
1591  else
1592  path->rows = baserel->rows;
1593 
1594  /* We charge qual cost plus cpu_tuple_cost */
1595  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1596 
1597  startup_cost += qpqual_cost.startup;
1598  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1599  run_cost += cpu_per_tuple * baserel->tuples;
1600 
1601  path->startup_cost = startup_cost;
1602  path->total_cost = startup_cost + run_cost;
1603 }
double tuples
Definition: pathnodes.h:681
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1125
Index relid
Definition: pathnodes.h:669
RTEKind rtekind
Definition: pathnodes.h:671
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4105
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
double Cost
Definition: nodes.h:659

◆ cost_samplescan()

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

Definition at line 288 of file costsize.c.

References Assert, PathTarget::cost, cpu_tuple_cost, get_restriction_qual_cost(), get_tablespace_page_costs(), GetTsmRoutine(), TsmRoutine::NextSampleBlock, RelOptInfo::pages, Path::pathtarget, 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().

290 {
291  Cost startup_cost = 0;
292  Cost run_cost = 0;
293  RangeTblEntry *rte;
294  TableSampleClause *tsc;
295  TsmRoutine *tsm;
296  double spc_seq_page_cost,
297  spc_random_page_cost,
298  spc_page_cost;
299  QualCost qpqual_cost;
300  Cost cpu_per_tuple;
301 
302  /* Should only be applied to base relations with tablesample clauses */
303  Assert(baserel->relid > 0);
304  rte = planner_rt_fetch(baserel->relid, root);
305  Assert(rte->rtekind == RTE_RELATION);
306  tsc = rte->tablesample;
307  Assert(tsc != NULL);
308  tsm = GetTsmRoutine(tsc->tsmhandler);
309 
310  /* Mark the path with the correct row estimate */
311  if (param_info)
312  path->rows = param_info->ppi_rows;
313  else
314  path->rows = baserel->rows;
315 
316  /* fetch estimated page cost for tablespace containing table */
318  &spc_random_page_cost,
319  &spc_seq_page_cost);
320 
321  /* if NextSampleBlock is used, assume random access, else sequential */
322  spc_page_cost = (tsm->NextSampleBlock != NULL) ?
323  spc_random_page_cost : spc_seq_page_cost;
324 
325  /*
326  * disk costs (recall that baserel->pages has already been set to the
327  * number of pages the sampling method will visit)
328  */
329  run_cost += spc_page_cost * baserel->pages;
330 
331  /*
332  * CPU costs (recall that baserel->tuples has already been set to the
333  * number of tuples the sampling method will select). Note that we ignore
334  * execution cost of the TABLESAMPLE parameter expressions; they will be
335  * evaluated only once per scan, and in most usages they'll likely be
336  * simple constants anyway. We also don't charge anything for the
337  * calculations the sampling method might do internally.
338  */
339  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
340 
341  startup_cost += qpqual_cost.startup;
342  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
343  run_cost += cpu_per_tuple * baserel->tuples;
344  /* tlist eval costs are paid per output row, not per tuple scanned */
345  startup_cost += path->pathtarget->cost.startup;
346  run_cost += path->pathtarget->cost.per_tuple * path->rows;
347 
348  path->startup_cost = startup_cost;
349  path->total_cost = startup_cost + run_cost;
350 }
PathTarget * pathtarget
Definition: pathnodes.h:1115
double tuples
Definition: pathnodes.h:681
Oid reltablespace
Definition: pathnodes.h:670
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1125
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:371
NextSampleBlock_function NextSampleBlock
Definition: tsmapi.h:73
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: pathnodes.h:669
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4105
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
BlockNumber pages
Definition: pathnodes.h:680
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
QualCost cost
Definition: pathnodes.h:1046
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
RTEKind rtekind
Definition: parsenodes.h:974
struct TableSampleClause * tablesample
Definition: parsenodes.h:1004
double Cost
Definition: nodes.h:659

◆ cost_seqscan()

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

Definition at line 211 of file costsize.c.

References Assert, clamp_row_est(), PathTarget::cost, cpu_tuple_cost, disable_cost, enable_seqscan, get_parallel_divisor(), get_restriction_qual_cost(), get_tablespace_page_costs(), RelOptInfo::pages, Path::parallel_workers, Path::pathtarget, 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().

213 {
214  Cost startup_cost = 0;
215  Cost cpu_run_cost;
216  Cost disk_run_cost;
217  double spc_seq_page_cost;
218  QualCost qpqual_cost;
219  Cost cpu_per_tuple;
220 
221  /* Should only be applied to base relations */
222  Assert(baserel->relid > 0);
223  Assert(baserel->rtekind == RTE_RELATION);
224 
225  /* Mark the path with the correct row estimate */
226  if (param_info)
227  path->rows = param_info->ppi_rows;
228  else
229  path->rows = baserel->rows;
230 
231  if (!enable_seqscan)
232  startup_cost += disable_cost;
233 
234  /* fetch estimated page cost for tablespace containing table */
236  NULL,
237  &spc_seq_page_cost);
238 
239  /*
240  * disk costs
241  */
242  disk_run_cost = spc_seq_page_cost * baserel->pages;
243 
244  /* CPU costs */
245  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
246 
247  startup_cost += qpqual_cost.startup;
248  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
249  cpu_run_cost = cpu_per_tuple * baserel->tuples;
250  /* tlist eval costs are paid per output row, not per tuple scanned */
251  startup_cost += path->pathtarget->cost.startup;
252  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
253 
254  /* Adjust costing for parallelism, if used. */
255  if (path->parallel_workers > 0)
256  {
257  double parallel_divisor = get_parallel_divisor(path);
258 
259  /* The CPU cost is divided among all the workers. */
260  cpu_run_cost /= parallel_divisor;
261 
262  /*
263  * It may be possible to amortize some of the I/O cost, but probably
264  * not very much, because most operating systems already do aggressive
265  * prefetching. For now, we assume that the disk run cost can't be
266  * amortized at all.
267  */
268 
269  /*
270  * In the case of a parallel plan, the row count needs to represent
271  * the number of tuples processed per worker.
272  */
273  path->rows = clamp_row_est(path->rows / parallel_divisor);
274  }
275 
276  path->startup_cost = startup_cost;
277  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
278 }
PathTarget * pathtarget
Definition: pathnodes.h:1115
double tuples
Definition: pathnodes.h:681
Oid reltablespace
Definition: pathnodes.h:670
int parallel_workers
Definition: pathnodes.h:1121
bool enable_seqscan
Definition: costsize.c:124
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1125
Cost disable_cost
Definition: costsize.c:120
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5475
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: pathnodes.h:669
RTEKind rtekind
Definition: pathnodes.h:671
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4105
BlockNumber pages
Definition: pathnodes.h:680
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
QualCost cost
Definition: pathnodes.h:1046
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
double clamp_row_est(double nrows)
Definition: costsize.c:187
double Cost
Definition: nodes.h:659

◆ 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 1693 of file costsize.c.

References cpu_operator_cost, disable_cost, enable_sort, LOG2, random_page_cost, relation_byte_size(), Path::rows, seq_page_cost, Path::startup_cost, Path::total_cost, and tuplesort_merge_order().

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().

1697 {
1698  Cost startup_cost = input_cost;
1699  Cost run_cost = 0;
1700  double input_bytes = relation_byte_size(tuples, width);
1701  double output_bytes;
1702  double output_tuples;
1703  long sort_mem_bytes = sort_mem * 1024L;
1704 
1705  if (!enable_sort)
1706  startup_cost += disable_cost;
1707 
1708  path->rows = tuples;
1709 
1710  /*
1711  * We want to be sure the cost of a sort is never estimated as zero, even
1712  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1713  */
1714  if (tuples < 2.0)
1715  tuples = 2.0;
1716 
1717  /* Include the default cost-per-comparison */
1718  comparison_cost += 2.0 * cpu_operator_cost;
1719 
1720  /* Do we have a useful LIMIT? */
1721  if (limit_tuples > 0 && limit_tuples < tuples)
1722  {
1723  output_tuples = limit_tuples;
1724  output_bytes = relation_byte_size(output_tuples, width);
1725  }
1726  else
1727  {
1728  output_tuples = tuples;
1729  output_bytes = input_bytes;
1730  }
1731 
1732  if (output_bytes > sort_mem_bytes)
1733  {
1734  /*
1735  * We'll have to use a disk-based sort of all the tuples
1736  */
1737  double npages = ceil(input_bytes / BLCKSZ);
1738  double nruns = input_bytes / sort_mem_bytes;
1739  double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1740  double log_runs;
1741  double npageaccesses;
1742 
1743  /*
1744  * CPU costs
1745  *
1746  * Assume about N log2 N comparisons
1747  */
1748  startup_cost += comparison_cost * tuples * LOG2(tuples);
1749 
1750  /* Disk costs */
1751 
1752  /* Compute logM(r) as log(r) / log(M) */
1753  if (nruns > mergeorder)
1754  log_runs = ceil(log(nruns) / log(mergeorder));
1755  else
1756  log_runs = 1.0;
1757  npageaccesses = 2.0 * npages * log_runs;
1758  /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1759  startup_cost += npageaccesses *
1760  (seq_page_cost * 0.75 + random_page_cost * 0.25);
1761  }
1762  else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1763  {
1764  /*
1765  * We'll use a bounded heap-sort keeping just K tuples in memory, for
1766  * a total number of tuple comparisons of N log2 K; but the constant
1767  * factor is a bit higher than for quicksort. Tweak it so that the
1768  * cost curve is continuous at the crossover point.
1769  */
1770  startup_cost += comparison_cost * tuples * LOG2(2.0 * output_tuples);
1771  }
1772  else
1773  {
1774  /* We'll use plain quicksort on all the input tuples */
1775  startup_cost += comparison_cost * tuples * LOG2(tuples);
1776  }
1777 
1778  /*
1779  * Also charge a small amount (arbitrarily set equal to operator cost) per
1780  * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1781  * doesn't do qual-checking or projection, so it has less overhead than
1782  * most plan nodes. Note it's correct to use tuples not output_tuples
1783  * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1784  * counting the LIMIT otherwise.
1785  */
1786  run_cost += cpu_operator_cost * tuples;
1787 
1788  path->startup_cost = startup_cost;
1789  path->total_cost = startup_cost + run_cost;
1790 }
bool enable_sort
Definition: costsize.c:129
double random_page_cost
Definition: costsize.c:111
Cost startup_cost
Definition: pathnodes.h:1125
Cost disable_cost
Definition: costsize.c:120
double cpu_operator_cost
Definition: costsize.c:114
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5454
Cost total_cost
Definition: pathnodes.h:1126
#define LOG2(x)
Definition: costsize.c:100
double rows
Definition: pathnodes.h:1124
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:2353
double seq_page_cost
Definition: costsize.c:110
double Cost
Definition: nodes.h:659

◆ cost_subplan()

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

Definition at line 3619 of file costsize.c.

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().

3620 {
3621  QualCost sp_cost;
3622 
3623  /* Figure any cost for evaluating the testexpr */
3624  cost_qual_eval(&sp_cost,
3625  make_ands_implicit((Expr *) subplan->testexpr),
3626  root);
3627 
3628  if (subplan->useHashTable)
3629  {
3630  /*
3631  * If we are using a hash table for the subquery outputs, then the
3632  * cost of evaluating the query is a one-time cost. We charge one
3633  * cpu_operator_cost per tuple for the work of loading the hashtable,
3634  * too.
3635  */
3636  sp_cost.startup += plan->total_cost +
3637  cpu_operator_cost * plan->plan_rows;
3638 
3639  /*
3640  * The per-tuple costs include the cost of evaluating the lefthand
3641  * expressions, plus the cost of probing the hashtable. We already
3642  * accounted for the lefthand expressions as part of the testexpr, and
3643  * will also have counted one cpu_operator_cost for each comparison
3644  * operator. That is probably too low for the probing cost, but it's
3645  * hard to make a better estimate, so live with it for now.
3646  */
3647  }
3648  else
3649  {
3650  /*
3651  * Otherwise we will be rescanning the subplan output on each
3652  * evaluation. We need to estimate how much of the output we will
3653  * actually need to scan. NOTE: this logic should agree with the
3654  * tuple_fraction estimates used by make_subplan() in
3655  * plan/subselect.c.
3656  */
3657  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
3658 
3659  if (subplan->subLinkType == EXISTS_SUBLINK)
3660  {
3661  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
3662  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
3663  }
3664  else if (subplan->subLinkType == ALL_SUBLINK ||
3665  subplan->subLinkType == ANY_SUBLINK)
3666  {
3667  /* assume we need 50% of the tuples */
3668  sp_cost.per_tuple += 0.50 * plan_run_cost;
3669  /* also charge a cpu_operator_cost per row examined */
3670  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
3671  }
3672  else
3673  {
3674  /* assume we need all tuples */
3675  sp_cost.per_tuple += plan_run_cost;
3676  }
3677 
3678  /*
3679  * Also account for subplan's startup cost. If the subplan is
3680  * uncorrelated or undirect correlated, AND its topmost node is one
3681  * that materializes its output, assume that we'll only need to pay
3682  * its startup cost once; otherwise assume we pay the startup cost
3683  * every time.
3684  */
3685  if (subplan->parParam == NIL &&
3687  sp_cost.startup += plan->startup_cost;
3688  else
3689  sp_cost.per_tuple += plan->startup_cost;
3690  }
3691 
3692  subplan->startup_cost = sp_cost.startup;
3693  subplan->per_call_cost = sp_cost.per_tuple;
3694 }
#define NIL
Definition: pg_list.h:65
double plan_rows
Definition: plannodes.h:127
SubLinkType subLinkType
Definition: primnodes.h:690
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3819
Cost startup_cost
Definition: plannodes.h:121
double cpu_operator_cost
Definition: costsize.c:114
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:716
Node * testexpr
Definition: primnodes.h:692
Cost per_call_cost
Definition: primnodes.h:719
List * parParam
Definition: primnodes.h:715
#define nodeTag(nodeptr)
Definition: nodes.h:530
Cost total_cost
Definition: plannodes.h:122
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:611
bool useHashTable
Definition: primnodes.h:704
Cost startup_cost
Definition: primnodes.h:718
double clamp_row_est(double nrows)
Definition: costsize.c:187
double Cost
Definition: nodes.h:659

◆ cost_subqueryscan()

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

Definition at line 1282 of file costsize.c.

References Assert, PathTarget::cost, cpu_tuple_cost, get_restriction_qual_cost(), SubqueryScanPath::path, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::rows, Path::rows, RTE_SUBQUERY, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, SubqueryScanPath::subpath, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_subqueryscan_path().

1284 {
1285  Cost startup_cost;
1286  Cost run_cost;
1287  QualCost qpqual_cost;
1288  Cost cpu_per_tuple;
1289 
1290  /* Should only be applied to base relations that are subqueries */
1291  Assert(baserel->relid > 0);
1292  Assert(baserel->rtekind == RTE_SUBQUERY);
1293 
1294  /* Mark the path with the correct row estimate */
1295  if (param_info)
1296  path->path.rows = param_info->ppi_rows;
1297  else
1298  path->path.rows = baserel->rows;
1299 
1300  /*
1301  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1302  * any restriction clauses and tlist that will be attached to the
1303  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1304  * projection overhead.
1305  */
1306  path->path.startup_cost = path->subpath->startup_cost;
1307  path->path.total_cost = path->subpath->total_cost;
1308 
1309  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1310 
1311  startup_cost = qpqual_cost.startup;
1312  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1313  run_cost = cpu_per_tuple * baserel->tuples;
1314 
1315  /* tlist eval costs are paid per output row, not per tuple scanned */
1316  startup_cost += path->path.pathtarget->cost.startup;
1317  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1318 
1319  path->path.startup_cost += startup_cost;
1320  path->path.total_cost += startup_cost + run_cost;
1321 }
PathTarget * pathtarget
Definition: pathnodes.h:1115
double tuples
Definition: pathnodes.h:681
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1125
Index relid
Definition: pathnodes.h:669
RTEKind rtekind
Definition: pathnodes.h:671
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4105
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
QualCost cost
Definition: pathnodes.h:1046
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
double Cost
Definition: nodes.h:659

◆ cost_tablefuncscan()

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

Definition at line 1392 of file costsize.c.

References Assert, PathTarget::cost, cost_qual_eval_node(), cpu_tuple_cost, get_restriction_qual_cost(), Path::pathtarget, 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().

1394 {
1395  Cost startup_cost = 0;
1396  Cost run_cost = 0;
1397  QualCost qpqual_cost;
1398  Cost cpu_per_tuple;
1399  RangeTblEntry *rte;
1400  QualCost exprcost;
1401 
1402  /* Should only be applied to base relations that are functions */
1403  Assert(baserel->relid > 0);
1404  rte = planner_rt_fetch(baserel->relid, root);
1405  Assert(rte->rtekind == RTE_TABLEFUNC);
1406 
1407  /* Mark the path with the correct row estimate */
1408  if (param_info)
1409  path->rows = param_info->ppi_rows;
1410  else
1411  path->rows = baserel->rows;
1412 
1413  /*
1414  * Estimate costs of executing the table func expression(s).
1415  *
1416  * XXX in principle we ought to charge tuplestore spill costs if the
1417  * number of rows is large. However, given how phony our rowcount
1418  * estimates for tablefuncs tend to be, there's not a lot of point in that
1419  * refinement right now.
1420  */
1421  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1422 
1423  startup_cost += exprcost.startup + exprcost.per_tuple;
1424 
1425  /* Add scanning CPU costs */
1426  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1427 
1428  startup_cost += qpqual_cost.startup;
1429  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1430  run_cost += cpu_per_tuple * baserel->tuples;
1431 
1432  /* tlist eval costs are paid per output row, not per tuple scanned */
1433  startup_cost += path->pathtarget->cost.startup;
1434  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1435 
1436  path->startup_cost = startup_cost;
1437  path->total_cost = startup_cost + run_cost;
1438 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3845
PathTarget * pathtarget
Definition: pathnodes.h:1115
double tuples
Definition: pathnodes.h:681
Definition: nodes.h:525
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
TableFunc * tablefunc
Definition: parsenodes.h:1046
Cost startup_cost
Definition: pathnodes.h:1125
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:371
Index relid
Definition: pathnodes.h:669
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4105
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
QualCost cost
Definition: pathnodes.h:1046
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
RTEKind rtekind
Definition: parsenodes.h:974
double Cost
Definition: nodes.h:659

◆ cost_tidscan()

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

Definition at line 1176 of file costsize.c.

References ScalarArrayOpExpr::args, Assert, RelOptInfo::baserestrictcost, RestrictInfo::clause, PathTarget::cost, 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, Path::pathtarget, 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().

1178 {
1179  Cost startup_cost = 0;
1180  Cost run_cost = 0;
1181  bool isCurrentOf = false;
1182  QualCost qpqual_cost;
1183  Cost cpu_per_tuple;
1184  QualCost tid_qual_cost;
1185  int ntuples;
1186  ListCell *l;
1187  double spc_random_page_cost;
1188 
1189  /* Should only be applied to base relations */
1190  Assert(baserel->relid > 0);
1191  Assert(baserel->rtekind == RTE_RELATION);
1192 
1193  /* Mark the path with the correct row estimate */
1194  if (param_info)
1195  path->rows = param_info->ppi_rows;
1196  else
1197  path->rows = baserel->rows;
1198 
1199  /* Count how many tuples we expect to retrieve */
1200  ntuples = 0;
1201  foreach(l, tidquals)
1202  {
1203  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
1204  Expr *qual = rinfo->clause;
1205 
1206  if (IsA(qual, ScalarArrayOpExpr))
1207  {
1208  /* Each element of the array yields 1 tuple */
1209  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) qual;
1210  Node *arraynode = (Node *) lsecond(saop->args);
1211 
1212  ntuples += estimate_array_length(arraynode);
1213  }
1214  else if (IsA(qual, CurrentOfExpr))
1215  {
1216  /* CURRENT OF yields 1 tuple */
1217  isCurrentOf = true;
1218  ntuples++;
1219  }
1220  else
1221  {
1222  /* It's just CTID = something, count 1 tuple */
1223  ntuples++;
1224  }
1225  }
1226 
1227  /*
1228  * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
1229  * understands how to do it correctly. Therefore, honor enable_tidscan
1230  * only when CURRENT OF isn't present. Also note that cost_qual_eval
1231  * counts a CurrentOfExpr as having startup cost disable_cost, which we
1232  * subtract off here; that's to prevent other plan types such as seqscan
1233  * from winning.
1234  */
1235  if (isCurrentOf)
1236  {
1238  startup_cost -= disable_cost;
1239  }
1240  else if (!enable_tidscan)
1241  startup_cost += disable_cost;
1242 
1243  /*
1244  * The TID qual expressions will be computed once, any other baserestrict
1245  * quals once per retrieved tuple.
1246  */
1247  cost_qual_eval(&tid_qual_cost, tidquals, root);
1248 
1249  /* fetch estimated page cost for tablespace containing table */
1251  &spc_random_page_cost,
1252  NULL);
1253 
1254  /* disk costs --- assume each tuple on a different page */
1255  run_cost += spc_random_page_cost * ntuples;
1256 
1257  /* Add scanning CPU costs */
1258  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1259 
1260  /* XXX currently we assume TID quals are a subset of qpquals */
1261  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1262  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1263  tid_qual_cost.per_tuple;
1264  run_cost += cpu_per_tuple * ntuples;
1265 
1266  /* tlist eval costs are paid per output row, not per tuple scanned */
1267  startup_cost += path->pathtarget->cost.startup;
1268  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1269 
1270  path->startup_cost = startup_cost;
1271  path->total_cost = startup_cost + run_cost;
1272 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
PathTarget * pathtarget
Definition: pathnodes.h:1115
bool enable_tidscan
Definition: costsize.c:128
Oid reltablespace
Definition: pathnodes.h:670
Definition: nodes.h:525
#define lsecond(l)
Definition: pg_list.h:200
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:1890
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3819
Cost startup_cost
Definition: pathnodes.h:1125
Cost disable_cost
Definition: costsize.c:120
#define lfirst_node(type, lc)
Definition: pg_list.h:193
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: pathnodes.h:669
Expr * clause
Definition: pathnodes.h:1943
RTEKind rtekind
Definition: pathnodes.h:671
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4105
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
QualCost cost
Definition: pathnodes.h:1046
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
QualCost baserestrictcost
Definition: pathnodes.h:704
double Cost
Definition: nodes.h:659

◆ cost_valuesscan()

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

Definition at line 1448 of file costsize.c.

References Assert, PathTarget::cost, cpu_operator_cost, cpu_tuple_cost, get_restriction_qual_cost(), Path::pathtarget, 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().

1450 {
1451  Cost startup_cost = 0;
1452  Cost run_cost = 0;
1453  QualCost qpqual_cost;
1454  Cost cpu_per_tuple;
1455 
1456  /* Should only be applied to base relations that are values lists */
1457  Assert(baserel->relid > 0);
1458  Assert(baserel->rtekind == RTE_VALUES);
1459 
1460  /* Mark the path with the correct row estimate */
1461  if (param_info)
1462  path->rows = param_info->ppi_rows;
1463  else
1464  path->rows = baserel->rows;
1465 
1466  /*
1467  * For now, estimate list evaluation cost at one operator eval per list
1468  * (probably pretty bogus, but is it worth being smarter?)
1469  */
1470  cpu_per_tuple = cpu_operator_cost;
1471 
1472  /* Add scanning CPU costs */
1473  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1474 
1475  startup_cost += qpqual_cost.startup;
1476  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1477  run_cost += cpu_per_tuple * baserel->tuples;
1478 
1479  /* tlist eval costs are paid per output row, not per tuple scanned */
1480  startup_cost += path->pathtarget->cost.startup;
1481  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1482 
1483  path->startup_cost = startup_cost;
1484  path->total_cost = startup_cost + run_cost;
1485 }
PathTarget * pathtarget
Definition: pathnodes.h:1115
double tuples
Definition: pathnodes.h:681
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1125
double cpu_operator_cost
Definition: costsize.c:114
Index relid
Definition: pathnodes.h:669
RTEKind rtekind
Definition: pathnodes.h:671
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4105
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
QualCost cost
Definition: pathnodes.h:1046
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
double Cost
Definition: nodes.h:659

◆ 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 2272 of file costsize.c.

References add_function_cost(), 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().

2276 {
2277  Cost startup_cost;
2278  Cost total_cost;
2279  ListCell *lc;
2280 
2281  startup_cost = input_startup_cost;
2282  total_cost = input_total_cost;
2283 
2284  /*
2285  * Window functions are assumed to cost their stated execution cost, plus
2286  * the cost of evaluating their input expressions, per tuple. Since they
2287  * may in fact evaluate their inputs at multiple rows during each cycle,
2288  * this could be a drastic underestimate; but without a way to know how
2289  * many rows the window function will fetch, it's hard to do better. In
2290  * any case, it's a good estimate for all the built-in window functions,
2291  * so we'll just do this for now.
2292  */
2293  foreach(lc, windowFuncs)
2294  {
2295  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
2296  Cost wfunccost;
2297  QualCost argcosts;
2298 
2299  argcosts.startup = argcosts.per_tuple = 0;
2300  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
2301  &argcosts);
2302  startup_cost += argcosts.startup;
2303  wfunccost = argcosts.per_tuple;
2304 
2305  /* also add the input expressions' cost to per-input-row costs */
2306  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
2307  startup_cost += argcosts.startup;
2308  wfunccost += argcosts.per_tuple;
2309 
2310  /*
2311  * Add the filter's cost to per-input-row costs. XXX We should reduce
2312  * input expression costs according to filter selectivity.
2313  */
2314  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
2315  startup_cost += argcosts.startup;
2316  wfunccost += argcosts.per_tuple;
2317 
2318  total_cost += wfunccost * input_tuples;
2319  }
2320 
2321  /*
2322  * We also charge cpu_operator_cost per grouping column per tuple for
2323  * grouping comparisons, plus cpu_tuple_cost per tuple for general
2324  * overhead.
2325  *
2326  * XXX this neglects costs of spooling the data to disk when it overflows
2327  * work_mem. Sooner or later that should get accounted for.
2328  */
2329  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
2330  total_cost += cpu_tuple_cost * input_tuples;
2331 
2332  path->rows = input_tuples;
2333  path->startup_cost = startup_cost;
2334  path->total_cost = total_cost;
2335 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3845
List * args
Definition: primnodes.h:363
Definition: nodes.h:525
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1906
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1125
#define lfirst_node(type, lc)
Definition: pg_list.h:193
double cpu_operator_cost
Definition: costsize.c:114
Oid winfnoid
Definition: primnodes.h:359
Cost total_cost
Definition: pathnodes.h:1126
Expr * aggfilter
Definition: primnodes.h:364
double rows
Definition: pathnodes.h:1124
double cpu_tuple_cost
Definition: costsize.c:112
double Cost
Definition: nodes.h:659

◆ extract_nonindex_conditions()

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

Definition at line 767 of file costsize.c.

References is_redundant_with_indexclauses(), lappend(), lfirst_node, NIL, and RestrictInfo::pseudoconstant.

Referenced by cost_index().

768 {
769  List *result = NIL;
770  ListCell *lc;
771 
772  foreach(lc, qual_clauses)
773  {
774  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
775 
776  if (rinfo->pseudoconstant)
777  continue; /* we may drop pseudoconstants here */
778  if (is_redundant_with_indexclauses(rinfo, indexclauses))
779  continue; /* dup or derived from same EquivalenceClass */
780  /* ... skip the predicate proof attempt createplan.c will try ... */
781  result = lappend(result, rinfo);
782  }
783  return result;
784 }
#define NIL
Definition: pg_list.h:65
bool pseudoconstant
Definition: pathnodes.h:1951
bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
Definition: equivclass.c:2688
#define lfirst_node(type, lc)
Definition: pg_list.h:193
List * lappend(List *list, void *datum)
Definition: list.c:322
Definition: pg_list.h:50

◆ final_cost_hashjoin()

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

Definition at line 3364 of file costsize.c.

References approx_tuple_count(), Assert, bms_is_subset(), clamp_row_est(), RestrictInfo::clause, PathTarget::cost, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_hashjoin, estimate_hash_bucket_stats(), 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, RestrictInfo::left_bucketsize, RestrictInfo::left_mcvfreq, RestrictInfo::left_relids, lfirst_node, SemiAntiJoinFactors::match_count, HashPath::num_batches, JoinCostWorkspace::numbatches, JoinCostWorkspace::numbuckets, SemiAntiJoinFactors::outer_match_frac, JoinPath::outerjoinpath, Path::parallel_workers, Path::param_info, Path::parent, JoinPath::path, HashPath::path_hashclauses, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, relation_byte_size(), RelOptInfo::relids, RestrictInfo::right_bucketsize, RestrictInfo::right_mcvfreq, RestrictInfo::right_relids, rint(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, PathTarget::width, and work_mem.

Referenced by create_hashjoin_path().

3367 {
3368  Path *outer_path = path->jpath.outerjoinpath;
3369  Path *inner_path = path->jpath.innerjoinpath;
3370  double outer_path_rows = outer_path->rows;
3371  double inner_path_rows = inner_path->rows;
3372  double inner_path_rows_total = workspace->inner_rows_total;
3373  List *hashclauses = path->path_hashclauses;
3374  Cost startup_cost = workspace->startup_cost;
3375  Cost run_cost = workspace->run_cost;
3376  int numbuckets = workspace->numbuckets;
3377  int numbatches = workspace->numbatches;
3378  Cost cpu_per_tuple;
3379  QualCost hash_qual_cost;
3380  QualCost qp_qual_cost;
3381  double hashjointuples;
3382  double virtualbuckets;
3383  Selectivity innerbucketsize;
3384  Selectivity innermcvfreq;
3385  ListCell *hcl;
3386 
3387  /* Mark the path with the correct row estimate */
3388  if (path->jpath.path.param_info)
3389  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3390  else
3391  path->jpath.path.rows = path->jpath.path.parent->rows;
3392 
3393  /* For partial paths, scale row estimate. */
3394  if (path->jpath.path.parallel_workers > 0)
3395  {
3396  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3397 
3398  path->jpath.path.rows =
3399  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3400  }
3401 
3402  /*
3403  * We could include disable_cost in the preliminary estimate, but that
3404  * would amount to optimizing for the case where the join method is
3405  * disabled, which doesn't seem like the way to bet.
3406  */
3407  if (!enable_hashjoin)
3408  startup_cost += disable_cost;
3409 
3410  /* mark the path with estimated # of batches */
3411  path->num_batches = numbatches;
3412 
3413  /* store the total number of tuples (sum of partial row estimates) */
3414  path->inner_rows_total = inner_path_rows_total;
3415 
3416  /* and compute the number of "virtual" buckets in the whole join */
3417  virtualbuckets = (double) numbuckets * (double) numbatches;
3418 
3419  /*
3420  * Determine bucketsize fraction and MCV frequency for the inner relation.
3421  * We use the smallest bucketsize or MCV frequency estimated for any
3422  * individual hashclause; this is undoubtedly conservative.
3423  *
3424  * BUT: if inner relation has been unique-ified, we can assume it's good
3425  * for hashing. This is important both because it's the right answer, and
3426  * because we avoid contaminating the cache with a value that's wrong for
3427  * non-unique-ified paths.
3428  */
3429  if (IsA(inner_path, UniquePath))
3430  {
3431  innerbucketsize = 1.0 / virtualbuckets;
3432  innermcvfreq = 0.0;
3433  }
3434  else
3435  {
3436  innerbucketsize = 1.0;
3437  innermcvfreq = 1.0;
3438  foreach(hcl, hashclauses)
3439  {
3440  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
3441  Selectivity thisbucketsize;
3442  Selectivity thismcvfreq;
3443 
3444  /*
3445  * First we have to figure out which side of the hashjoin clause
3446  * is the inner side.
3447  *
3448  * Since we tend to visit the same clauses over and over when
3449  * planning a large query, we cache the bucket stats estimates in
3450  * the RestrictInfo node to avoid repeated lookups of statistics.
3451  */
3452  if (bms_is_subset(restrictinfo->right_relids,
3453  inner_path->parent->relids))
3454  {
3455  /* righthand side is inner */
3456  thisbucketsize = restrictinfo->right_bucketsize;
3457  if (thisbucketsize < 0)
3458  {
3459  /* not cached yet */
3461  get_rightop(restrictinfo->clause),
3462  virtualbuckets,
3463  &restrictinfo->right_mcvfreq,
3464  &restrictinfo->right_bucketsize);
3465  thisbucketsize = restrictinfo->right_bucketsize;
3466  }
3467  thismcvfreq = restrictinfo->right_mcvfreq;
3468  }
3469  else
3470  {
3471  Assert(bms_is_subset(restrictinfo->left_relids,
3472  inner_path->parent->relids));
3473  /* lefthand side is inner */
3474  thisbucketsize = restrictinfo->left_bucketsize;
3475  if (thisbucketsize < 0)
3476  {
3477  /* not cached yet */
3479  get_leftop(restrictinfo->clause),
3480  virtualbuckets,
3481  &restrictinfo->left_mcvfreq,
3482  &restrictinfo->left_bucketsize);
3483  thisbucketsize = restrictinfo->left_bucketsize;
3484  }
3485  thismcvfreq = restrictinfo->left_mcvfreq;
3486  }
3487 
3488  if (innerbucketsize > thisbucketsize)
3489  innerbucketsize = thisbucketsize;
3490  if (innermcvfreq > thismcvfreq)
3491  innermcvfreq = thismcvfreq;
3492  }
3493  }
3494 
3495  /*
3496  * If the bucket holding the inner MCV would exceed work_mem, we don't
3497  * want to hash unless there is really no other alternative, so apply
3498  * disable_cost. (The executor normally copes with excessive memory usage
3499  * by splitting batches, but obviously it cannot separate equal values
3500  * that way, so it will be unable to drive the batch size below work_mem
3501  * when this is true.)
3502  */
3503  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
3504  inner_path->pathtarget->width) >
3505  (work_mem * 1024L))
3506  startup_cost += disable_cost;
3507 
3508  /*
3509  * Compute cost of the hashquals and qpquals (other restriction clauses)
3510  * separately.
3511  */
3512  cost_qual_eval(&hash_qual_cost, hashclauses, root);
3513  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3514  qp_qual_cost.startup -= hash_qual_cost.startup;
3515  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
3516 
3517  /* CPU costs */
3518 
3519  if (path->jpath.jointype == JOIN_SEMI ||
3520  path->jpath.jointype == JOIN_ANTI ||
3521  extra->inner_unique)
3522  {
3523  double outer_matched_rows;
3524  Selectivity inner_scan_frac;
3525 
3526  /*
3527  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3528  * executor will stop after the first match.
3529  *
3530  * For an outer-rel row that has at least one match, we can expect the
3531  * bucket scan to stop after a fraction 1/(match_count+1) of the
3532  * bucket's rows, if the matches are evenly distributed. Since they
3533  * probably aren't quite evenly distributed, we apply a fuzz factor of
3534  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
3535  * to clamp inner_scan_frac to at most 1.0; but since match_count is
3536  * at least 1, no such clamp is needed now.)
3537  */
3538  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3539  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3540 
3541  startup_cost += hash_qual_cost.startup;
3542  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
3543  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
3544 
3545  /*
3546  * For unmatched outer-rel rows, the picture is quite a lot different.
3547  * In the first place, there is no reason to assume that these rows
3548  * preferentially hit heavily-populated buckets; instead assume they
3549  * are uncorrelated with the inner distribution and so they see an
3550  * average bucket size of inner_path_rows / virtualbuckets. In the
3551  * second place, it seems likely that they will have few if any exact
3552  * hash-code matches and so very few of the tuples in the bucket will
3553  * actually require eval of the hash quals. We don't have any good
3554  * way to estimate how many will, but for the moment assume that the
3555  * effective cost per bucket entry is one-tenth what it is for
3556  * matchable tuples.
3557  */
3558  run_cost += hash_qual_cost.per_tuple *
3559  (outer_path_rows - outer_matched_rows) *
3560  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
3561 
3562  /* Get # of tuples that will pass the basic join */
3563  if (path->jpath.jointype == JOIN_ANTI)
3564  hashjointuples = outer_path_rows - outer_matched_rows;
3565  else
3566  hashjointuples = outer_matched_rows;
3567  }
3568  else
3569  {
3570  /*
3571  * The number of tuple comparisons needed is the number of outer
3572  * tuples times the typical number of tuples in a hash bucket, which
3573  * is the inner relation size times its bucketsize fraction. At each
3574  * one, we need to evaluate the hashjoin quals. But actually,
3575  * charging the full qual eval cost at each tuple is pessimistic,
3576  * since we don't evaluate the quals unless the hash values match
3577  * exactly. For lack of a better idea, halve the cost estimate to
3578  * allow for that.
3579  */
3580  startup_cost += hash_qual_cost.startup;
3581  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
3582  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
3583 
3584  /*
3585  * Get approx # tuples passing the hashquals. We use
3586  * approx_tuple_count here because we need an estimate done with
3587  * JOIN_INNER semantics.
3588  */
3589  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
3590  }
3591 
3592  /*
3593  * For each tuple that gets through the hashjoin proper, we charge
3594  * cpu_tuple_cost plus the cost of evaluating additional restriction
3595  * clauses that are to be applied at the join. (This is pessimistic since
3596  * not all of the quals may get evaluated at each tuple.)
3597  */
3598  startup_cost += qp_qual_cost.startup;
3599  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3600  run_cost += cpu_per_tuple * hashjointuples;
3601 
3602  /* tlist eval costs are paid per output row, not per tuple scanned */
3603  startup_cost += path->jpath.path.pathtarget->cost.startup;
3604  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3605 
3606  path->jpath.path.startup_cost = startup_cost;
3607  path->jpath.path.total_cost = startup_cost + run_cost;
3608 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
JoinPath jpath
Definition: pathnodes.h:1569
PathTarget * pathtarget
Definition: pathnodes.h:1115
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:2381
int num_batches
Definition: pathnodes.h:1571
Selectivity right_mcvfreq
Definition: pathnodes.h:2007
Selectivity outer_match_frac
Definition: pathnodes.h:2358
Path * innerjoinpath
Definition: pathnodes.h:1496
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4348
int parallel_workers
Definition: pathnodes.h:1121
ParamPathInfo * param_info
Definition: pathnodes.h:1117
Relids left_relids
Definition: pathnodes.h:1970
double Selectivity
Definition: nodes.h:658
double inner_rows_total
Definition: pathnodes.h:1572
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3819
Cost startup_cost
Definition: pathnodes.h:1125
Cost disable_cost
Definition: costsize.c:120
List * joinrestrictinfo
Definition: pathnodes.h:1498
RelOptInfo * parent
Definition: pathnodes.h:1114
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
#define lfirst_node(type, lc)
Definition: pg_list.h:193
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5475
Relids relids
Definition: pathnodes.h:641
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:70
double rint(double x)
Definition: rint.c:21
Expr * clause
Definition: pathnodes.h:1943
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5454
Path * outerjoinpath
Definition: pathnodes.h:1495
double inner_rows_total
Definition: pathnodes.h:2502
int work_mem
Definition: globals.c:121
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:82
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
Selectivity left_bucketsize
Definition: pathnodes.h:2004
Relids right_relids
Definition: pathnodes.h:1971
Path path
Definition: pathnodes.h:1488
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1124
Selectivity left_mcvfreq
Definition: pathnodes.h:2006
QualCost cost
Definition: pathnodes.h:1046
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
bool enable_hashjoin
Definition: costsize.c:134
Selectivity match_count
Definition: pathnodes.h:2359
Selectivity right_bucketsize
Definition: pathnodes.h:2005
JoinType jointype
Definition: pathnodes.h:1490
void estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
Definition: selfuncs.c:3406
List * path_hashclauses
Definition: pathnodes.h:1570
double clamp_row_est(double nrows)
Definition: costsize.c:187
Definition: pg_list.h:50
double Cost
Definition: nodes.h:659

◆ final_cost_mergejoin()

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

Definition at line 2928 of file costsize.c.

References approx_tuple_count(), clamp_row_est(), PathTarget::cost, cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, disable_cost, enable_material, enable_mergejoin, ExecSupportsMarkRestore(), get_parallel_divisor(), 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, Path::parallel_workers, Path::param_info, Path::parent, JoinPath::path, MergePath::path_mergeclauses, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, relation_byte_size(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, MergePath::skip_mark_restore, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, PathTarget::width, and work_mem.

Referenced by create_mergejoin_path().

2931 {
2932  Path *outer_path = path->jpath.outerjoinpath;
2933  Path *inner_path = path->jpath.innerjoinpath;
2934  double inner_path_rows = inner_path->rows;
2935  List *mergeclauses = path->path_mergeclauses;
2936  List *innersortkeys = path->innersortkeys;
2937  Cost startup_cost = workspace->startup_cost;
2938  Cost run_cost = workspace->run_cost;
2939  Cost inner_run_cost = workspace->inner_run_cost;
2940  double outer_rows = workspace->outer_rows;
2941  double inner_rows = workspace->inner_rows;
2942  double outer_skip_rows = workspace->outer_skip_rows;
2943  double inner_skip_rows = workspace->inner_skip_rows;
2944  Cost cpu_per_tuple,
2945  bare_inner_cost,
2946  mat_inner_cost;
2947  QualCost merge_qual_cost;
2948  QualCost qp_qual_cost;
2949  double mergejointuples,
2950  rescannedtuples;
2951  double rescanratio;
2952 
2953  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2954  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2955  inner_path_rows = 1;
2956 
2957  /* Mark the path with the correct row estimate */
2958  if (path->jpath.path.param_info)
2959  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2960  else
2961  path->jpath.path.rows = path->jpath.path.parent->rows;
2962 
2963  /* For partial paths, scale row estimate. */
2964  if (path->jpath.path.parallel_workers > 0)
2965  {
2966  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
2967 
2968  path->jpath.path.rows =
2969  clamp_row_est(path->jpath.path.rows / parallel_divisor);
2970  }
2971 
2972  /*
2973  * We could include disable_cost in the preliminary estimate, but that
2974  * would amount to optimizing for the case where the join method is
2975  * disabled, which doesn't seem like the way to bet.
2976  */
2977  if (!enable_mergejoin)
2978  startup_cost += disable_cost;
2979 
2980  /*
2981  * Compute cost of the mergequals and qpquals (other restriction clauses)
2982  * separately.
2983  */
2984  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
2985  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2986  qp_qual_cost.startup -= merge_qual_cost.startup;
2987  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
2988 
2989  /*
2990  * With a SEMI or ANTI join, or if the innerrel is known unique, the
2991  * executor will stop scanning for matches after the first match. When
2992  * all the joinclauses are merge clauses, this means we don't ever need to
2993  * back up the merge, and so we can skip mark/restore overhead.
2994  */
2995  if ((path->jpath.jointype == JOIN_SEMI ||
2996  path->jpath.jointype == JOIN_ANTI ||
2997  extra->inner_unique) &&
3000  path->skip_mark_restore = true;
3001  else
3002  path->skip_mark_restore = false;
3003 
3004  /*
3005  * Get approx # tuples passing the mergequals. We use approx_tuple_count
3006  * here because we need an estimate done with JOIN_INNER semantics.
3007  */
3008  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
3009 
3010  /*
3011  * When there are equal merge keys in the outer relation, the mergejoin
3012  * must rescan any matching tuples in the inner relation. This means
3013  * re-fetching inner tuples; we have to estimate how often that happens.
3014  *
3015  * For regular inner and outer joins, the number of re-fetches can be
3016  * estimated approximately as size of merge join output minus size of
3017  * inner relation. Assume that the distinct key values are 1, 2, ..., and
3018  * denote the number of values of each key in the outer relation as m1,
3019  * m2, ...; in the inner relation, n1, n2, ... Then we have
3020  *
3021  * size of join = m1 * n1 + m2 * n2 + ...
3022  *
3023  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
3024  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
3025  * relation
3026  *
3027  * This equation works correctly for outer tuples having no inner match
3028  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
3029  * are effectively subtracting those from the number of rescanned tuples,
3030  * when we should not. Can we do better without expensive selectivity
3031  * computations?
3032  *
3033  * The whole issue is moot if we are working from a unique-ified outer
3034  * input, or if we know we don't need to mark/restore at all.
3035  */
3036  if (IsA(outer_path, UniquePath) ||path->skip_mark_restore)
3037  rescannedtuples = 0;
3038  else
3039  {
3040  rescannedtuples = mergejointuples - inner_path_rows;
3041  /* Must clamp because of possible underestimate */
3042  if (rescannedtuples < 0)
3043  rescannedtuples = 0;
3044  }
3045 
3046  /*
3047  * We'll inflate various costs this much to account for rescanning. Note
3048  * that this is to be multiplied by something involving inner_rows, or
3049  * another number related to the portion of the inner rel we'll scan.
3050  */
3051  rescanratio = 1.0 + (rescannedtuples / inner_rows);
3052 
3053  /*
3054  * Decide whether we want to materialize the inner input to shield it from
3055  * mark/restore and performing re-fetches. Our cost model for regular
3056  * re-fetches is that a re-fetch costs the same as an original fetch,
3057  * which is probably an overestimate; but on the other hand we ignore the
3058  * bookkeeping costs of mark/restore. Not clear if it's worth developing
3059  * a more refined model. So we just need to inflate the inner run cost by
3060  * rescanratio.
3061  */
3062  bare_inner_cost = inner_run_cost * rescanratio;
3063 
3064  /*
3065  * When we interpose a Material node the re-fetch cost is assumed to be
3066  * just cpu_operator_cost per tuple, independently of the underlying
3067  * plan's cost; and we charge an extra cpu_operator_cost per original
3068  * fetch as well. Note that we're assuming the materialize node will
3069  * never spill to disk, since it only has to remember tuples back to the
3070  * last mark. (If there are a huge number of duplicates, our other cost
3071  * factors will make the path so expensive that it probably won't get
3072  * chosen anyway.) So we don't use cost_rescan here.
3073  *
3074  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3075  * of the generated Material node.
3076  */
3077  mat_inner_cost = inner_run_cost +
3078  cpu_operator_cost * inner_rows * rescanratio;
3079 
3080  /*
3081  * If we don't need mark/restore at all, we don't need materialization.
3082  */
3083  if (path->skip_mark_restore)
3084  path->materialize_inner = false;
3085 
3086  /*
3087  * Prefer materializing if it looks cheaper, unless the user has asked to
3088  * suppress materialization.
3089  */
3090  else if (enable_material && mat_inner_cost < bare_inner_cost)
3091  path->materialize_inner = true;
3092 
3093  /*
3094  * Even if materializing doesn't look cheaper, we *must* do it if the
3095  * inner path is to be used directly (without sorting) and it doesn't
3096  * support mark/restore.
3097  *
3098  * Since the inner side must be ordered, and only Sorts and IndexScans can
3099  * create order to begin with, and they both support mark/restore, you
3100  * might think there's no problem --- but you'd be wrong. Nestloop and
3101  * merge joins can *preserve* the order of their inputs, so they can be
3102  * selected as the input of a mergejoin, and they don't support
3103  * mark/restore at present.
3104  *
3105  * We don't test the value of enable_material here, because
3106  * materialization is required for correctness in this case, and turning
3107  * it off does not entitle us to deliver an invalid plan.
3108  */
3109  else if (innersortkeys == NIL &&
3110  !ExecSupportsMarkRestore(inner_path))
3111  path->materialize_inner = true;
3112 
3113  /*
3114  * Also, force materializing if the inner path is to be sorted and the
3115  * sort is expected to spill to disk. This is because the final merge
3116  * pass can be done on-the-fly if it doesn't have to support mark/restore.
3117  * We don't try to adjust the cost estimates for this consideration,
3118  * though.
3119  *
3120  * Since materialization is a performance optimization in this case,
3121  * rather than necessary for correctness, we skip it if enable_material is
3122  * off.
3123  */
3124  else if (enable_material && innersortkeys != NIL &&
3125  relation_byte_size(inner_path_rows,
3126  inner_path->pathtarget->width) >
3127  (work_mem * 1024L))
3128  path->materialize_inner = true;
3129  else
3130  path->materialize_inner = false;
3131 
3132  /* Charge the right incremental cost for the chosen case */
3133  if (path->materialize_inner)
3134  run_cost += mat_inner_cost;
3135  else
3136  run_cost += bare_inner_cost;
3137 
3138  /* CPU costs */
3139 
3140  /*
3141  * The number of tuple comparisons needed is approximately number of outer
3142  * rows plus number of inner rows plus number of rescanned tuples (can we
3143  * refine this?). At each one, we need to evaluate the mergejoin quals.
3144  */
3145  startup_cost += merge_qual_cost.startup;
3146  startup_cost += merge_qual_cost.per_tuple *
3147  (outer_skip_rows + inner_skip_rows * rescanratio);
3148  run_cost += merge_qual_cost.per_tuple *
3149  ((outer_rows - outer_skip_rows) +
3150  (inner_rows - inner_skip_rows) * rescanratio);
3151 
3152  /*
3153  * For each tuple that gets through the mergejoin proper, we charge
3154  * cpu_tuple_cost plus the cost of evaluating additional restriction
3155  * clauses that are to be applied at the join. (This is pessimistic since
3156  * not all of the quals may get evaluated at each tuple.)
3157  *
3158  * Note: we could adjust for SEMI/ANTI joins skipping some qual
3159  * evaluations here, but it's probably not worth the trouble.
3160  */
3161  startup_cost += qp_qual_cost.startup;
3162  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3163  run_cost += cpu_per_tuple * mergejointuples;
3164 
3165  /* tlist eval costs are paid per output row, not per tuple scanned */
3166  startup_cost += path->jpath.path.pathtarget->cost.startup;
3167  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3168 
3169  path->jpath.path.startup_cost = startup_cost;
3170  path->jpath.path.total_cost = startup_cost + run_cost;
3171 }
#define NIL
Definition: pg_list.h:65
List * path_mergeclauses
Definition: pathnodes.h:1551
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
PathTarget * pathtarget
Definition: pathnodes.h:1115
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:406
bool materialize_inner
Definition: pathnodes.h:1555
Path * innerjoinpath
Definition: pathnodes.h:1496
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4348
int parallel_workers
Definition: pathnodes.h:1121
ParamPathInfo * param_info
Definition: pathnodes.h:1117
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
bool skip_mark_restore
Definition: pathnodes.h:1554
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3819
Cost startup_cost
Definition: pathnodes.h:1125
Cost disable_cost
Definition: costsize.c:120
List * joinrestrictinfo
Definition: pathnodes.h:1498
RelOptInfo * parent
Definition: pathnodes.h:1114
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5475
double cpu_operator_cost
Definition: costsize.c:114
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5454
Path * outerjoinpath
Definition: pathnodes.h:1495
int work_mem
Definition: globals.c:121
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
double outer_skip_rows
Definition: pathnodes.h:2496
bool enable_mergejoin
Definition: costsize.c:133
Path path
Definition: pathnodes.h:1488
double rows
Definition: pathnodes.h:1124
QualCost cost
Definition: pathnodes.h:1046
static int list_length(const List *l)
Definition: pg_list.h:169
List * innersortkeys
Definition: pathnodes.h:1553
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
JoinType jointype
Definition: pathnodes.h:1490
JoinPath jpath
Definition: pathnodes.h:1550
double inner_skip_rows
Definition: pathnodes.h:2497
double clamp_row_est(double nrows)
Definition: costsize.c:187
Definition: pg_list.h:50
double Cost
Definition: nodes.h:659
bool enable_material
Definition: costsize.c:132

◆ final_cost_nestloop()

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

Definition at line 2491 of file costsize.c.

References clamp_row_est(), PathTarget::cost, 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, SemiAntiJoinFactors::match_count, SemiAntiJoinFactors::outer_match_frac, JoinPath::outerjoinpath, Path::parallel_workers, Path::param_info, Path::parent, JoinPath::path, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, rint(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, and Path::total_cost.

Referenced by create_nestloop_path().

2494 {
2495  Path *outer_path = path->outerjoinpath;
2496  Path *inner_path = path->innerjoinpath;
2497  double outer_path_rows = outer_path->rows;
2498  double inner_path_rows = inner_path->rows;
2499  Cost startup_cost = workspace->startup_cost;
2500  Cost run_cost = workspace->run_cost;
2501  Cost cpu_per_tuple;
2502  QualCost restrict_qual_cost;
2503  double ntuples;
2504 
2505  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2506  if (outer_path_rows <= 0 || isnan(outer_path_rows))
2507  outer_path_rows = 1;
2508  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2509  inner_path_rows = 1;
2510 
2511  /* Mark the path with the correct row estimate */
2512  if (path->path.param_info)
2513  path->path.rows = path->path.param_info->ppi_rows;
2514  else
2515  path->path.rows = path->path.parent->rows;
2516 
2517  /* For partial paths, scale row estimate. */
2518  if (path->path.parallel_workers > 0)
2519  {
2520  double parallel_divisor = get_parallel_divisor(&path->path);
2521 
2522  path->path.rows =
2523  clamp_row_est(path->path.rows / parallel_divisor);
2524  }
2525 
2526  /*
2527  * We could include disable_cost in the preliminary estimate, but that
2528  * would amount to optimizing for the case where the join method is
2529  * disabled, which doesn't seem like the way to bet.
2530  */
2531  if (!enable_nestloop)
2532  startup_cost += disable_cost;
2533 
2534  /* cost of inner-relation source data (we already dealt with outer rel) */
2535 
2536  if (path->jointype == JOIN_SEMI || path->jointype == JOIN_ANTI ||
2537  extra->inner_unique)
2538  {
2539  /*
2540  * With a SEMI or ANTI join, or if the innerrel is known unique, the
2541  * executor will stop after the first match.
2542  */
2543  Cost inner_run_cost = workspace->inner_run_cost;
2544  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
2545  double outer_matched_rows;
2546  double outer_unmatched_rows;
2547  Selectivity inner_scan_frac;
2548 
2549  /*
2550  * For an outer-rel row that has at least one match, we can expect the
2551  * inner scan to stop after a fraction 1/(match_count+1) of the inner
2552  * rows, if the matches are evenly distributed. Since they probably
2553  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
2554  * that fraction. (If we used a larger fuzz factor, we'd have to
2555  * clamp inner_scan_frac to at most 1.0; but since match_count is at
2556  * least 1, no such clamp is needed now.)
2557  */
2558  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
2559  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
2560  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
2561 
2562  /*
2563  * Compute number of tuples processed (not number emitted!). First,
2564  * account for succe