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 relevants 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, 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 Min(x, y)
Definition: c.h:890
Cost total_cost
Definition: pathnodes.h:1112
#define lfirst(lc)
Definition: pg_list.h:106
#define for_each_cell(cell, initcell)
Definition: pg_list.h:169
void * palloc(Size size)
Definition: mcxt.c:924
int i
double Cost
Definition: nodes.h:658
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 4289 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().

4290 {
4291  double tuples;
4292  double outer_tuples = path->outerjoinpath->rows;
4293  double inner_tuples = path->innerjoinpath->rows;
4294  SpecialJoinInfo sjinfo;
4295  Selectivity selec = 1.0;
4296  ListCell *l;
4297 
4298  /*
4299  * Make up a SpecialJoinInfo for JOIN_INNER semantics.
4300  */
4301  sjinfo.type = T_SpecialJoinInfo;
4302  sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
4303  sjinfo.min_righthand = path->innerjoinpath->parent->relids;
4304  sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
4305  sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
4306  sjinfo.jointype = JOIN_INNER;
4307  /* we don't bother trying to make the remaining fields valid */
4308  sjinfo.lhs_strict = false;
4309  sjinfo.delay_upper_joins = false;
4310  sjinfo.semi_can_btree = false;
4311  sjinfo.semi_can_hash = false;
4312  sjinfo.semi_operators = NIL;
4313  sjinfo.semi_rhs_exprs = NIL;
4314 
4315  /* Get the approximate selectivity */
4316  foreach(l, quals)
4317  {
4318  Node *qual = (Node *) lfirst(l);
4319 
4320  /* Note that clause_selectivity will be able to cache its result */
4321  selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
4322  }
4323 
4324  /* Apply it to the input relation sizes */
4325  tuples = selec * outer_tuples * inner_tuples;
4326 
4327  return clamp_row_est(tuples);
4328 }
#define NIL
Definition: pg_list.h:69
Relids min_righthand
Definition: pathnodes.h:2121
Path * innerjoinpath
Definition: pathnodes.h:1483
Definition: nodes.h:524
double Selectivity
Definition: nodes.h:657
Relids syn_lefthand
Definition: pathnodes.h:2122
Relids syn_righthand
Definition: pathnodes.h:2123
List * semi_rhs_exprs
Definition: pathnodes.h:2131
RelOptInfo * parent
Definition: pathnodes.h:1100
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:576
Relids relids
Definition: pathnodes.h:629
Path * outerjoinpath
Definition: pathnodes.h:1482
bool delay_upper_joins
Definition: pathnodes.h:2126
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: pathnodes.h:1110
JoinType jointype
Definition: pathnodes.h:2124
List * semi_operators
Definition: pathnodes.h:2130
double clamp_row_est(double nrows)
Definition: costsize.c:187
Relids min_lefthand
Definition: pathnodes.h:2120

◆ cached_scansel()

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

Definition at line 3118 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().

3119 {
3120  MergeScanSelCache *cache;
3121  ListCell *lc;
3122  Selectivity leftstartsel,
3123  leftendsel,
3124  rightstartsel,
3125  rightendsel;
3126  MemoryContext oldcontext;
3127 
3128  /* Do we have this result already? */
3129  foreach(lc, rinfo->scansel_cache)
3130  {
3131  cache = (MergeScanSelCache *) lfirst(lc);
3132  if (cache->opfamily == pathkey->pk_opfamily &&
3133  cache->collation == pathkey->pk_eclass->ec_collation &&
3134  cache->strategy == pathkey->pk_strategy &&
3135  cache->nulls_first == pathkey->pk_nulls_first)
3136  return cache;
3137  }
3138 
3139  /* Nope, do the computation */
3140  mergejoinscansel(root,
3141  (Node *) rinfo->clause,
3142  pathkey->pk_opfamily,
3143  pathkey->pk_strategy,
3144  pathkey->pk_nulls_first,
3145  &leftstartsel,
3146  &leftendsel,
3147  &rightstartsel,
3148  &rightendsel);
3149 
3150  /* Cache the result in suitably long-lived workspace */
3151  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
3152 
3153  cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
3154  cache->opfamily = pathkey->pk_opfamily;
3155  cache->collation = pathkey->pk_eclass->ec_collation;
3156  cache->strategy = pathkey->pk_strategy;
3157  cache->nulls_first = pathkey->pk_nulls_first;
3158  cache->leftstartsel = leftstartsel;
3159  cache->leftendsel = leftendsel;
3160  cache->rightstartsel = rightstartsel;
3161  cache->rightendsel = rightendsel;
3162 
3163  rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
3164 
3165  MemoryContextSwitchTo(oldcontext);
3166 
3167  return cache;
3168 }
Selectivity leftendsel
Definition: pathnodes.h:2027
void mergejoinscansel(PlannerInfo *root, Node *clause, Oid opfamily, int strategy, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
Definition: selfuncs.c:2541
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:524
double Selectivity
Definition: nodes.h:657
int pk_strategy
Definition: pathnodes.h:999
bool pk_nulls_first
Definition: pathnodes.h:1000
Selectivity rightstartsel
Definition: pathnodes.h:2028
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: pathnodes.h:1930
#define lfirst(lc)
Definition: pg_list.h:106
EquivalenceClass * pk_eclass
Definition: pathnodes.h:997
Oid pk_opfamily
Definition: pathnodes.h:998
void * palloc(Size size)
Definition: mcxt.c:924
MemoryContext planner_cxt
Definition: pathnodes.h:319
Selectivity rightendsel
Definition: pathnodes.h:2029
List * scansel_cache
Definition: pathnodes.h:1982
Selectivity leftstartsel
Definition: pathnodes.h:2026

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

4506 {
4507  /* This apparently-useless variable dodges a compiler bug in VS2013: */
4508  List *restrictlist = restrictlist_in;
4509  JoinType jointype = sjinfo->jointype;
4510  Selectivity fkselec;
4511  Selectivity jselec;
4512  Selectivity pselec;
4513  double nrows;
4514 
4515  /*
4516  * Compute joinclause selectivity. Note that we are only considering
4517  * clauses that become restriction clauses at this join level; we are not
4518  * double-counting them because they were not considered in estimating the
4519  * sizes of the component rels.
4520  *
4521  * First, see whether any of the joinclauses can be matched to known FK
4522  * constraints. If so, drop those clauses from the restrictlist, and
4523  * instead estimate their selectivity using FK semantics. (We do this
4524  * without regard to whether said clauses are local or "pushed down".
4525  * Probably, an FK-matching clause could never be seen as pushed down at
4526  * an outer join, since it would be strict and hence would be grounds for
4527  * join strength reduction.) fkselec gets the net selectivity for
4528  * FK-matching clauses, or 1.0 if there are none.
4529  */
4530  fkselec = get_foreign_key_join_selectivity(root,
4531  outer_rel->relids,
4532  inner_rel->relids,
4533  sjinfo,
4534  &restrictlist);
4535 
4536  /*
4537  * For an outer join, we have to distinguish the selectivity of the join's
4538  * own clauses (JOIN/ON conditions) from any clauses that were "pushed
4539  * down". For inner joins we just count them all as joinclauses.
4540  */
4541  if (IS_OUTER_JOIN(jointype))
4542  {
4543  List *joinquals = NIL;
4544  List *pushedquals = NIL;
4545  ListCell *l;
4546 
4547  /* Grovel through the clauses to separate into two lists */
4548  foreach(l, restrictlist)
4549  {
4550  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4551 
4552  if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
4553  pushedquals = lappend(pushedquals, rinfo);
4554  else
4555  joinquals = lappend(joinquals, rinfo);
4556  }
4557 
4558  /* Get the separate selectivities */
4559  jselec = clauselist_selectivity(root,
4560  joinquals,
4561  0,
4562  jointype,
4563  sjinfo);
4564  pselec = clauselist_selectivity(root,
4565  pushedquals,
4566  0,
4567  jointype,
4568  sjinfo);
4569 
4570  /* Avoid leaking a lot of ListCells */
4571  list_free(joinquals);
4572  list_free(pushedquals);
4573  }
4574  else
4575  {
4576  jselec = clauselist_selectivity(root,
4577  restrictlist,
4578  0,
4579  jointype,
4580  sjinfo);
4581  pselec = 0.0; /* not used, keep compiler quiet */
4582  }
4583 
4584  /*
4585  * Basically, we multiply size of Cartesian product by selectivity.
4586  *
4587  * If we are doing an outer join, take that into account: the joinqual
4588  * selectivity has to be clamped using the knowledge that the output must
4589  * be at least as large as the non-nullable input. However, any
4590  * pushed-down quals are applied after the outer join, so their
4591  * selectivity applies fully.
4592  *
4593  * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
4594  * of LHS rows that have matches, and we apply that straightforwardly.
4595  */
4596  switch (jointype)
4597  {
4598  case JOIN_INNER:
4599  nrows = outer_rows * inner_rows * fkselec * jselec;
4600  /* pselec not used */
4601  break;
4602  case JOIN_LEFT:
4603  nrows = outer_rows * inner_rows * fkselec * jselec;
4604  if (nrows < outer_rows)
4605  nrows = outer_rows;
4606  nrows *= pselec;
4607  break;
4608  case JOIN_FULL:
4609  nrows = outer_rows * inner_rows * fkselec * jselec;
4610  if (nrows < outer_rows)
4611  nrows = outer_rows;
4612  if (nrows < inner_rows)
4613  nrows = inner_rows;
4614  nrows *= pselec;
4615  break;
4616  case JOIN_SEMI:
4617  nrows = outer_rows * fkselec * jselec;
4618  /* pselec not used */
4619  break;
4620  case JOIN_ANTI:
4621  nrows = outer_rows * (1.0 - fkselec * jselec);
4622  nrows *= pselec;
4623  break;
4624  default:
4625  /* other values not expected here */
4626  elog(ERROR, "unrecognized join type: %d", (int) jointype);
4627  nrows = 0; /* keep compiler quiet */
4628  break;
4629  }
4630 
4631  return clamp_row_est(nrows);
4632 }
#define NIL
Definition: pg_list.h:69
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:740
double Selectivity
Definition: nodes.h:657
JoinType
Definition: nodes.h:691
static Selectivity get_foreign_key_join_selectivity(PlannerInfo *root, Relids outer_relids, Relids inner_relids, SpecialJoinInfo *sjinfo, List **restrictlist)
Definition: costsize.c:4650
#define ERROR
Definition: elog.h:43
#define lfirst_node(type, lc)
Definition: pg_list.h:109
Relids relids
Definition: pathnodes.h:629
List * lappend(List *list, void *datum)
Definition: list.c:128
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2007
JoinType jointype
Definition: pathnodes.h:2124
void list_free(List *list)
Definition: list.c:1136
#define elog(elevel,...)
Definition: elog.h:226
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:101
double clamp_row_est(double nrows)
Definition: costsize.c:187
Definition: pg_list.h:45

◆ clamp_row_est()

double clamp_row_est ( double  nrows)

Definition at line 187 of file costsize.c.

References rint().

Referenced by 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(), create_limit_path(), 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 5456 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().

5458 {
5459  Cost indexTotalCost;
5460  Selectivity indexSelectivity;
5461  double T;
5462  double pages_fetched;
5463  double tuples_fetched;
5464  double heap_pages;
5465  long maxentries;
5466 
5467  /*
5468  * Fetch total cost of obtaining the bitmap, as well as its total
5469  * selectivity.
5470  */
5471  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
5472 
5473  /*
5474  * Estimate number of main-table pages fetched.
5475  */
5476  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
5477 
5478  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
5479 
5480  /*
5481  * For a single scan, the number of heap pages that need to be fetched is
5482  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
5483  * re-reads needed).
5484  */
5485  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
5486 
5487  /*
5488  * Calculate the number of pages fetched from the heap. Then based on
5489  * current work_mem estimate get the estimated maxentries in the bitmap.
5490  * (Note that we always do this calculation based on the number of pages
5491  * that would be fetched in a single iteration, even if loop_count > 1.
5492  * That's correct, because only that number of entries will be stored in
5493  * the bitmap at one time.)
5494  */
5495  heap_pages = Min(pages_fetched, baserel->pages);
5496  maxentries = tbm_calculate_entries(work_mem * 1024L);
5497 
5498  if (loop_count > 1)
5499  {
5500  /*
5501  * For repeated bitmap scans, scale up the number of tuples fetched in
5502  * the Mackert and Lohman formula by the number of scans, so that we
5503  * estimate the number of pages fetched by all the scans. Then
5504  * pro-rate for one scan.
5505  */
5506  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
5507  baserel->pages,
5508  get_indexpath_pages(bitmapqual),
5509  root);
5510  pages_fetched /= loop_count;
5511  }
5512 
5513  if (pages_fetched >= T)
5514  pages_fetched = T;
5515  else
5516  pages_fetched = ceil(pages_fetched);
5517 
5518  if (maxentries < heap_pages)
5519  {
5520  double exact_pages;
5521  double lossy_pages;
5522 
5523  /*
5524  * Crude approximation of the number of lossy pages. Because of the
5525  * way tbm_lossify() is coded, the number of lossy pages increases
5526  * very sharply as soon as we run short of memory; this formula has
5527  * that property and seems to perform adequately in testing, but it's
5528  * possible we could do better somehow.
5529  */
5530  lossy_pages = Max(0, heap_pages - maxentries / 2);
5531  exact_pages = heap_pages - lossy_pages;
5532 
5533  /*
5534  * If there are lossy pages then recompute the number of tuples
5535  * processed by the bitmap heap node. We assume here that the chance
5536  * of a given tuple coming from an exact page is the same as the
5537  * chance that a given page is exact. This might not be true, but
5538  * it's not clear how we can do any better.
5539  */
5540  if (lossy_pages > 0)
5541  tuples_fetched =
5542  clamp_row_est(indexSelectivity *
5543  (exact_pages / heap_pages) * baserel->tuples +
5544  (lossy_pages / heap_pages) * baserel->tuples);
5545  }
5546 
5547  if (cost)
5548  *cost = indexTotalCost;
5549  if (tuple)
5550  *tuple = tuples_fetched;
5551 
5552  return pages_fetched;
5553 }
double tuples
Definition: pathnodes.h:669
#define Min(x, y)
Definition: c.h:890
double Selectivity
Definition: nodes.h:657
static const uint32 T[65]
Definition: md5.c:101
int work_mem
Definition: globals.c:121
#define Max(x, y)
Definition: c.h:884
BlockNumber pages
Definition: pathnodes.h:668
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:658
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 4088 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().

4096 {
4097  Selectivity jselec;
4098  Selectivity nselec;
4099  Selectivity avgmatch;
4100  SpecialJoinInfo norm_sjinfo;
4101  List *joinquals;
4102  ListCell *l;
4103 
4104  /*
4105  * In an ANTI join, we must ignore clauses that are "pushed down", since
4106  * those won't affect the match logic. In a SEMI join, we do not
4107  * distinguish joinquals from "pushed down" quals, so just use the whole
4108  * restrictinfo list. For other outer join types, we should consider only
4109  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
4110  */
4111  if (IS_OUTER_JOIN(jointype))
4112  {
4113  joinquals = NIL;
4114  foreach(l, restrictlist)
4115  {
4116  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4117 
4118  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
4119  joinquals = lappend(joinquals, rinfo);
4120  }
4121  }
4122  else
4123  joinquals = restrictlist;
4124 
4125  /*
4126  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
4127  */
4128  jselec = clauselist_selectivity(root,
4129  joinquals,
4130  0,
4131  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
4132  sjinfo);
4133 
4134  /*
4135  * Also get the normal inner-join selectivity of the join clauses.
4136  */
4137  norm_sjinfo.type = T_SpecialJoinInfo;
4138  norm_sjinfo.min_lefthand = outerrel->relids;
4139  norm_sjinfo.min_righthand = innerrel->relids;
4140  norm_sjinfo.syn_lefthand = outerrel->relids;
4141  norm_sjinfo.syn_righthand = innerrel->relids;
4142  norm_sjinfo.jointype = JOIN_INNER;
4143  /* we don't bother trying to make the remaining fields valid */
4144  norm_sjinfo.lhs_strict = false;
4145  norm_sjinfo.delay_upper_joins = false;
4146  norm_sjinfo.semi_can_btree = false;
4147  norm_sjinfo.semi_can_hash = false;
4148  norm_sjinfo.semi_operators = NIL;
4149  norm_sjinfo.semi_rhs_exprs = NIL;
4150 
4151  nselec = clauselist_selectivity(root,
4152  joinquals,
4153  0,
4154  JOIN_INNER,
4155  &norm_sjinfo);
4156 
4157  /* Avoid leaking a lot of ListCells */
4158  if (IS_OUTER_JOIN(jointype))
4159  list_free(joinquals);
4160 
4161  /*
4162  * jselec can be interpreted as the fraction of outer-rel rows that have
4163  * any matches (this is true for both SEMI and ANTI cases). And nselec is
4164  * the fraction of the Cartesian product that matches. So, the average
4165  * number of matches for each outer-rel row that has at least one match is
4166  * nselec * inner_rows / jselec.
4167  *
4168  * Note: it is correct to use the inner rel's "rows" count here, even
4169  * though we might later be considering a parameterized inner path with
4170  * fewer rows. This is because we have included all the join clauses in
4171  * the selectivity estimate.
4172  */
4173  if (jselec > 0) /* protect against zero divide */
4174  {
4175  avgmatch = nselec * innerrel->rows / jselec;
4176  /* Clamp to sane range */
4177  avgmatch = Max(1.0, avgmatch);
4178  }
4179  else
4180  avgmatch = 1.0;
4181 
4182  semifactors->outer_match_frac = jselec;
4183  semifactors->match_count = avgmatch;
4184 }
#define NIL
Definition: pg_list.h:69
Relids min_righthand
Definition: pathnodes.h:2121
Selectivity outer_match_frac
Definition: pathnodes.h:2345
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:740
double Selectivity
Definition: nodes.h:657
Relids syn_lefthand
Definition: pathnodes.h:2122
Relids syn_righthand
Definition: pathnodes.h:2123
List * semi_rhs_exprs
Definition: pathnodes.h:2131
#define lfirst_node(type, lc)
Definition: pg_list.h:109
Relids relids
Definition: pathnodes.h:629
List * lappend(List *list, void *datum)
Definition: list.c:128
bool delay_upper_joins
Definition: pathnodes.h:2126
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2007
double rows
Definition: pathnodes.h:632
#define Max(x, y)
Definition: c.h:884
JoinType jointype
Definition: pathnodes.h:2124
Selectivity match_count
Definition: pathnodes.h:2346
List * semi_operators
Definition: pathnodes.h:2130
void list_free(List *list)
Definition: list.c:1136
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:101
Definition: pg_list.h:45
Relids min_lefthand
Definition: pathnodes.h:2120

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

2098 {
2099  double output_tuples;
2100  Cost startup_cost;
2101  Cost total_cost;
2102  AggClauseCosts dummy_aggcosts;
2103 
2104  /* Use all-zero per-aggregate costs if NULL is passed */
2105  if (aggcosts == NULL)
2106  {
2107  Assert(aggstrategy == AGG_HASHED);
2108  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
2109  aggcosts = &dummy_aggcosts;
2110  }
2111 
2112  /*
2113  * The transCost.per_tuple component of aggcosts should be charged once
2114  * per input tuple, corresponding to the costs of evaluating the aggregate
2115  * transfns and their input expressions. The finalCost.per_tuple component
2116  * is charged once per output tuple, corresponding to the costs of
2117  * evaluating the finalfns. Startup costs are of course charged but once.
2118  *
2119  * If we are grouping, we charge an additional cpu_operator_cost per
2120  * grouping column per input tuple for grouping comparisons.
2121  *
2122  * We will produce a single output tuple if not grouping, and a tuple per
2123  * group otherwise. We charge cpu_tuple_cost for each output tuple.
2124  *
2125  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2126  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2127  * input path is already sorted appropriately, AGG_SORTED should be
2128  * preferred (since it has no risk of memory overflow). This will happen
2129  * as long as the computed total costs are indeed exactly equal --- but if
2130  * there's roundoff error we might do the wrong thing. So be sure that
2131  * the computations below form the same intermediate values in the same
2132  * order.
2133  */
2134  if (aggstrategy == AGG_PLAIN)
2135  {
2136  startup_cost = input_total_cost;
2137  startup_cost += aggcosts->transCost.startup;
2138  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2139  startup_cost += aggcosts->finalCost.startup;
2140  startup_cost += aggcosts->finalCost.per_tuple;
2141  /* we aren't grouping */
2142  total_cost = startup_cost + cpu_tuple_cost;
2143  output_tuples = 1;
2144  }
2145  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2146  {
2147  /* Here we are able to deliver output on-the-fly */
2148  startup_cost = input_startup_cost;
2149  total_cost = input_total_cost;
2150  if (aggstrategy == AGG_MIXED && !enable_hashagg)
2151  {
2152  startup_cost += disable_cost;
2153  total_cost += disable_cost;
2154  }
2155  /* calcs phrased this way to match HASHED case, see note above */
2156  total_cost += aggcosts->transCost.startup;
2157  total_cost += aggcosts->transCost.per_tuple * input_tuples;
2158  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2159  total_cost += aggcosts->finalCost.startup;
2160  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2161  total_cost += cpu_tuple_cost * numGroups;
2162  output_tuples = numGroups;
2163  }
2164  else
2165  {
2166  /* must be AGG_HASHED */
2167  startup_cost = input_total_cost;
2168  if (!enable_hashagg)
2169  startup_cost += disable_cost;
2170  startup_cost += aggcosts->transCost.startup;
2171  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2172  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2173  startup_cost += aggcosts->finalCost.startup;
2174  total_cost = startup_cost;
2175  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2176  total_cost += cpu_tuple_cost * numGroups;
2177  output_tuples = numGroups;
2178  }
2179 
2180  /*
2181  * If there are quals (HAVING quals), account for their cost and
2182  * selectivity.
2183  */
2184  if (quals)
2185  {
2186  QualCost qual_cost;
2187 
2188  cost_qual_eval(&qual_cost, quals, root);
2189  startup_cost += qual_cost.startup;
2190  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2191 
2192  output_tuples = clamp_row_est(output_tuples *
2194  quals,
2195  0,
2196  JOIN_INNER,
2197  NULL));
2198  }
2199 
2200  path->rows = output_tuples;
2201  path->startup_cost = startup_cost;
2202  path->total_cost = total_cost;
2203 }
QualCost finalCost
Definition: pathnodes.h:64
#define MemSet(start, val, len)
Definition: c.h:941
QualCost transCost
Definition: pathnodes.h:63
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3760
Cost startup_cost
Definition: pathnodes.h:1111
Cost disable_cost
Definition: costsize.c:120
double cpu_operator_cost
Definition: costsize.c:114
Cost total_cost
Definition: pathnodes.h:1112
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
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:101
double clamp_row_est(double nrows)
Definition: costsize.c:187
double Cost
Definition: nodes.h:658

◆ cost_append()

void cost_append ( AppendPath apath)

Definition at line 1875 of file costsize.c.

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

Referenced by create_append_path().

1876 {
1877  ListCell *l;
1878 
1879  apath->path.startup_cost = 0;
1880  apath->path.total_cost = 0;
1881 
1882  if (apath->subpaths == NIL)
1883  return;
1884 
1885  if (!apath->path.parallel_aware)
1886  {
1887  Path *subpath = (Path *) linitial(apath->subpaths);
1888 
1889  /*
1890  * Startup cost of non-parallel-aware Append is the startup cost of
1891  * first subpath.
1892  */
1893  apath->path.startup_cost = subpath->startup_cost;
1894 
1895  /* Compute rows and costs as sums of subplan rows and costs. */
1896  foreach(l, apath->subpaths)
1897  {
1898  Path *subpath = (Path *) lfirst(l);
1899 
1900  apath->path.rows += subpath->rows;
1901  apath->path.total_cost += subpath->total_cost;
1902  }
1903  }
1904  else /* parallel-aware */
1905  {
1906  int i = 0;
1907  double parallel_divisor = get_parallel_divisor(&apath->path);
1908 
1909  /* Calculate startup cost. */
1910  foreach(l, apath->subpaths)
1911  {
1912  Path *subpath = (Path *) lfirst(l);
1913 
1914  /*
1915  * Append will start returning tuples when the child node having
1916  * lowest startup cost is done setting up. We consider only the
1917  * first few subplans that immediately get a worker assigned.
1918  */
1919  if (i == 0)
1920  apath->path.startup_cost = subpath->startup_cost;
1921  else if (i < apath->path.parallel_workers)
1922  apath->path.startup_cost = Min(apath->path.startup_cost,
1923  subpath->startup_cost);
1924 
1925  /*
1926  * Apply parallel divisor to subpaths. Scale the number of rows
1927  * for each partial subpath based on the ratio of the parallel
1928  * divisor originally used for the subpath to the one we adopted.
1929  * Also add the cost of partial paths to the total cost, but
1930  * ignore non-partial paths for now.
1931  */
1932  if (i < apath->first_partial_path)
1933  apath->path.rows += subpath->rows / parallel_divisor;
1934  else
1935  {
1936  double subpath_parallel_divisor;
1937 
1938  subpath_parallel_divisor = get_parallel_divisor(subpath);
1939  apath->path.rows += subpath->rows * (subpath_parallel_divisor /
1940  parallel_divisor);
1941  apath->path.total_cost += subpath->total_cost;
1942  }
1943 
1944  apath->path.rows = clamp_row_est(apath->path.rows);
1945 
1946  i++;
1947  }
1948 
1949  /* Add cost for non-partial subpaths. */
1950  apath->path.total_cost +=
1952  apath->first_partial_path,
1953  apath->path.parallel_workers);
1954  }
1955 
1956  /*
1957  * Although Append does not do any selection or projection, it's not free;
1958  * add a small per-tuple overhead.
1959  */
1960  apath->path.total_cost +=
1962 }
#define NIL
Definition: pg_list.h:69
#define Min(x, y)
Definition: c.h:890
int parallel_workers
Definition: pathnodes.h:1107
static Cost append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
Definition: costsize.c:1799
int first_partial_path
Definition: pathnodes.h:1363
List * subpaths
Definition: pathnodes.h:1360
#define linitial(l)
Definition: pg_list.h:111
Cost startup_cost
Definition: pathnodes.h:1111
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5423
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:107
Cost total_cost
Definition: pathnodes.h:1112
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: pathnodes.h:1110
double cpu_tuple_cost
Definition: costsize.c:112
int i
bool parallel_aware
Definition: pathnodes.h:1105
double clamp_row_est(double nrows)
Definition: costsize.c:187
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:657
Selectivity bitmapselectivity
Definition: pathnodes.h:1249
List * bitmapquals
Definition: pathnodes.h:1248
Cost startup_cost
Definition: pathnodes.h:1111
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
double cpu_operator_cost
Definition: costsize.c:114
Cost total_cost
Definition: pathnodes.h:1112
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: pathnodes.h:1110
double Cost
Definition: nodes.h:658
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:575
PathTarget * pathtarget
Definition: pathnodes.h:1101
Oid reltablespace
Definition: pathnodes.h:658
int parallel_workers
Definition: pathnodes.h:1107
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
Cost startup_cost
Definition: pathnodes.h:1111
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:5423
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:657
bool enable_bitmapscan
Definition: costsize.c:127
RTEKind rtekind
Definition: pathnodes.h:659
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4046
BlockNumber pages
Definition: pathnodes.h:668
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
QualCost cost
Definition: pathnodes.h:1032
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
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:5456
double Cost
Definition: nodes.h:658

◆ 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:575
#define Min(x, y)
Definition: c.h:890
double Selectivity
Definition: nodes.h:657
List * bitmapquals
Definition: pathnodes.h:1261
Cost startup_cost
Definition: pathnodes.h:1111
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
double cpu_operator_cost
Definition: costsize.c:114
Selectivity bitmapselectivity
Definition: pathnodes.h:1262
Cost total_cost
Definition: pathnodes.h:1112
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: pathnodes.h:1110
double Cost
Definition: nodes.h:658
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:575
#define ERROR
Definition: elog.h:43
double cpu_operator_cost
Definition: costsize.c:114
Cost total_cost
Definition: pathnodes.h:1112
double rows
Definition: pathnodes.h:1110
#define nodeTag(nodeptr)
Definition: nodes.h:529
#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:1101
double tuples
Definition: pathnodes.h:669
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
Cost startup_cost
Definition: pathnodes.h:1111
Index relid
Definition: pathnodes.h:657
RTEKind rtekind
Definition: pathnodes.h:659
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4046
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
QualCost cost
Definition: pathnodes.h:1032
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
double Cost
Definition: nodes.h:658

◆ 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:3786
PathTarget * pathtarget
Definition: pathnodes.h:1101
double tuples
Definition: pathnodes.h:669
Definition: nodes.h:524
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
Cost startup_cost
Definition: pathnodes.h:1111
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:361
Index relid
Definition: pathnodes.h:657
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4046
#define Assert(condition)
Definition: c.h:732
List * functions
Definition: parsenodes.h:1029
double rows
Definition: pathnodes.h:1110
QualCost cost
Definition: pathnodes.h:1032
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
RTEKind rtekind
Definition: parsenodes.h:963
double Cost
Definition: nodes.h:658

◆ 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:1111
Path * subpath
Definition: pathnodes.h:1451
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
double rows
Definition: pathnodes.h:1110
double ppi_rows
Definition: pathnodes.h:1060
double Cost
Definition: nodes.h:658
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:1111
Cost disable_cost
Definition: costsize.c:120
double cpu_operator_cost
Definition: costsize.c:114
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
#define LOG2(x)
Definition: costsize.c:100
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
double ppi_rows
Definition: pathnodes.h:1060
bool enable_gathermerge
Definition: costsize.c:135
double Cost
Definition: nodes.h:658
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 2287 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().

2292 {
2293  double output_tuples;
2294  Cost startup_cost;
2295  Cost total_cost;
2296 
2297  output_tuples = numGroups;
2298  startup_cost = input_startup_cost;
2299  total_cost = input_total_cost;
2300 
2301  /*
2302  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2303  * all columns get compared at most of the tuples.
2304  */
2305  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2306 
2307  /*
2308  * If there are quals (HAVING quals), account for their cost and
2309  * selectivity.
2310  */
2311  if (quals)
2312  {
2313  QualCost qual_cost;
2314 
2315  cost_qual_eval(&qual_cost, quals, root);
2316  startup_cost += qual_cost.startup;
2317  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2318 
2319  output_tuples = clamp_row_est(output_tuples *
2321  quals,
2322  0,
2323  JOIN_INNER,
2324  NULL));
2325  }
2326 
2327  path->rows = output_tuples;
2328  path->startup_cost = startup_cost;
2329  path->total_cost = total_cost;
2330 }
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3760
Cost startup_cost
Definition: pathnodes.h:1111
double cpu_operator_cost
Definition: costsize.c:114
Cost total_cost
Definition: pathnodes.h:1112
double rows
Definition: pathnodes.h:1110
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:101
double clamp_row_est(double nrows)
Definition: costsize.c:187
double Cost
Definition: nodes.h:658

◆ 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:575
PathTarget * pathtarget
Definition: pathnodes.h:1101
Path path
Definition: pathnodes.h:1162
IndexOptInfo * indexinfo
Definition: pathnodes.h:1163
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:3418
double tuples
Definition: pathnodes.h:669
Oid reltablespace
Definition: pathnodes.h:658
int parallel_workers
Definition: pathnodes.h:1107
ParamPathInfo * param_info
Definition: pathnodes.h:1103
List * list_concat(List *list1, List *list2)
Definition: list.c:321
List * indexclauses
Definition: pathnodes.h:1164
double Selectivity
Definition: nodes.h:657
Cost startup
Definition: pathnodes.h:46
double allvisfrac
Definition: pathnodes.h:670
Definition: type.h:89
BlockNumber pages
Definition: pathnodes.h:780
NodeTag pathtype
Definition: pathnodes.h:1098
Cost per_tuple
Definition: pathnodes.h:47
RelOptInfo * rel
Definition: pathnodes.h:777
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3760
Cost startup_cost
Definition: pathnodes.h:1111
Cost indextotalcost
Definition: pathnodes.h:1168
Cost disable_cost
Definition: costsize.c:120
Selectivity indexselectivity
Definition: pathnodes.h:1169
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5423
void(* amcostestimate)()
Definition: pathnodes.h:824
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:657
List * indrestrictinfo
Definition: pathnodes.h:804
RTEKind rtekind
Definition: pathnodes.h:659
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
BlockNumber pages
Definition: pathnodes.h:668
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
List * ppi_clauses
Definition: pathnodes.h:1061
QualCost cost
Definition: pathnodes.h:1032
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
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:1105
double clamp_row_est(double nrows)
Definition: costsize.c:187
int max_parallel_workers_per_gather
Definition: costsize.c:122
Definition: pg_list.h:45
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:658

◆ cost_material()

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

Definition at line 2038 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().

2041 {
2042  Cost startup_cost = input_startup_cost;
2043  Cost run_cost = input_total_cost - input_startup_cost;
2044  double nbytes = relation_byte_size(tuples, width);
2045  long work_mem_bytes = work_mem * 1024L;
2046 
2047  path->rows = tuples;
2048 
2049  /*
2050  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2051  * reflect bookkeeping overhead. (This rate must be more than what
2052  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2053  * if it is exactly the same then there will be a cost tie between
2054  * nestloop with A outer, materialized B inner and nestloop with B outer,
2055  * materialized A inner. The extra cost ensures we'll prefer
2056  * materializing the smaller rel.) Note that this is normally a good deal
2057  * less than cpu_tuple_cost; which is OK because a Material plan node
2058  * doesn't do qual-checking or projection, so it's got less overhead than
2059  * most plan nodes.
2060  */
2061  run_cost += 2 * cpu_operator_cost * tuples;
2062 
2063  /*
2064  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2065  * This cost is assumed to be evenly spread through the plan run phase,
2066  * which isn't exactly accurate but our cost model doesn't allow for
2067  * nonuniform costs within the run phase.
2068  */
2069  if (nbytes > work_mem_bytes)
2070  {
2071  double npages = ceil(nbytes / BLCKSZ);
2072 
2073  run_cost += seq_page_cost * npages;
2074  }
2075 
2076  path->startup_cost = startup_cost;
2077  path->total_cost = startup_cost + run_cost;
2078 }
Cost startup_cost
Definition: pathnodes.h:1111
double cpu_operator_cost
Definition: costsize.c:114
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5402
int work_mem
Definition: globals.c:121
Cost total_cost
Definition: pathnodes.h:1112
double rows
Definition: pathnodes.h:1110
double seq_page_cost
Definition: costsize.c:110
double Cost
Definition: nodes.h:658

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

1993 {
1994  Cost startup_cost = 0;
1995  Cost run_cost = 0;
1996  Cost comparison_cost;
1997  double N;
1998  double logN;
1999 
2000  /*
2001  * Avoid log(0)...
2002  */
2003  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2004  logN = LOG2(N);
2005 
2006  /* Assumed cost per tuple comparison */
2007  comparison_cost = 2.0 * cpu_operator_cost;
2008 
2009  /* Heap creation cost */
2010  startup_cost += comparison_cost * N * logN;
2011 
2012  /* Per-tuple heap maintenance cost */
2013  run_cost += tuples * comparison_cost * logN;
2014 
2015  /*
2016  * Although MergeAppend does not do any selection or projection, it's not
2017  * free; add a small per-tuple overhead.
2018  */
2019  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2020 
2021  path->startup_cost = startup_cost + input_startup_cost;
2022  path->total_cost = startup_cost + run_cost + input_total_cost;
2023 }
Cost startup_cost
Definition: pathnodes.h:1111
double cpu_operator_cost
Definition: costsize.c:114
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:107
Cost total_cost
Definition: pathnodes.h:1112
#define LOG2(x)
Definition: costsize.c:100
double cpu_tuple_cost
Definition: costsize.c:112
double Cost
Definition: nodes.h:658

◆ 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:669
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
Cost startup_cost
Definition: pathnodes.h:1111
Index relid
Definition: pathnodes.h:657
RTEKind rtekind
Definition: pathnodes.h:659
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4046
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
double Cost
Definition: nodes.h:658

◆ cost_qual_eval()

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

Definition at line 3760 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().

3761 {
3762  cost_qual_eval_context context;
3763  ListCell *l;
3764 
3765  context.root = root;
3766  context.total.startup = 0;
3767  context.total.per_tuple = 0;
3768 
3769  /* We don't charge any cost for the implicit ANDing at top level ... */
3770 
3771  foreach(l, quals)
3772  {
3773  Node *qual = (Node *) lfirst(l);
3774 
3775  cost_qual_eval_walker(qual, &context);
3776  }
3777 
3778  *cost = context.total;
3779 }
PlannerInfo * root
Definition: costsize.c:144
Definition: nodes.h:524
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:3800
#define lfirst(lc)
Definition: pg_list.h:106

◆ cost_qual_eval_node()

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

Definition at line 3786 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().

3787 {
3788  cost_qual_eval_context context;
3789 
3790  context.root = root;
3791  context.total.startup = 0;
3792  context.total.per_tuple = 0;
3793 
3794  cost_qual_eval_walker(qual, &context);
3795 
3796  *cost = context.total;
3797 }
PlannerInfo * root
Definition: costsize.c:144
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:3800

◆ cost_qual_eval_walker()

static bool cost_qual_eval_walker ( Node node,
cost_qual_eval_context context 
)
static

Definition at line 3800 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().

3801 {
3802  if (node == NULL)
3803  return false;
3804 
3805  /*
3806  * RestrictInfo nodes contain an eval_cost field reserved for this
3807  * routine's use, so that it's not necessary to evaluate the qual clause's
3808  * cost more than once. If the clause's cost hasn't been computed yet,
3809  * the field's startup value will contain -1.
3810  */
3811  if (IsA(node, RestrictInfo))
3812  {
3813  RestrictInfo *rinfo = (RestrictInfo *) node;
3814 
3815  if (rinfo->eval_cost.startup < 0)
3816  {
3817  cost_qual_eval_context locContext;
3818 
3819  locContext.root = context->root;
3820  locContext.total.startup = 0;
3821  locContext.total.per_tuple = 0;
3822 
3823  /*
3824  * For an OR clause, recurse into the marked-up tree so that we
3825  * set the eval_cost for contained RestrictInfos too.
3826  */
3827  if (rinfo->orclause)
3828  cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
3829  else
3830  cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
3831 
3832  /*
3833  * If the RestrictInfo is marked pseudoconstant, it will be tested
3834  * only once, so treat its cost as all startup cost.
3835  */
3836  if (rinfo->pseudoconstant)
3837  {
3838  /* count one execution during startup */
3839  locContext.total.startup += locContext.total.per_tuple;
3840  locContext.total.per_tuple = 0;
3841  }
3842  rinfo->eval_cost = locContext.total;
3843  }
3844  context->total.startup += rinfo->eval_cost.startup;
3845  context->total.per_tuple += rinfo->eval_cost.per_tuple;
3846  /* do NOT recurse into children */
3847  return false;
3848  }
3849 
3850  /*
3851  * For each operator or function node in the given tree, we charge the
3852  * estimated execution cost given by pg_proc.procost (remember to multiply
3853  * this by cpu_operator_cost).
3854  *
3855  * Vars and Consts are charged zero, and so are boolean operators (AND,
3856  * OR, NOT). Simplistic, but a lot better than no model at all.
3857  *
3858  * Should we try to account for the possibility of short-circuit
3859  * evaluation of AND/OR? Probably *not*, because that would make the
3860  * results depend on the clause ordering, and we are not in any position
3861  * to expect that the current ordering of the clauses is the one that's
3862  * going to end up being used. The above per-RestrictInfo caching would
3863  * not mix well with trying to re-order clauses anyway.
3864  *
3865  * Another issue that is entirely ignored here is that if a set-returning
3866  * function is below top level in the tree, the functions/operators above
3867  * it will need to be evaluated multiple times. In practical use, such
3868  * cases arise so seldom as to not be worth the added complexity needed;
3869  * moreover, since our rowcount estimates for functions tend to be pretty
3870  * phony, the results would also be pretty phony.
3871  */
3872  if (IsA(node, FuncExpr))
3873  {
3874  add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
3875  &context->total);
3876  }
3877  else if (IsA(node, OpExpr) ||
3878  IsA(node, DistinctExpr) ||
3879  IsA(node, NullIfExpr))
3880  {
3881  /* rely on struct equivalence to treat these all alike */
3882  set_opfuncid((OpExpr *) node);
3883  add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
3884  &context->total);
3885  }
3886  else if (IsA(node, ScalarArrayOpExpr))
3887  {
3888  /*
3889  * Estimate that the operator will be applied to about half of the
3890  * array elements before the answer is determined.
3891  */
3892  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
3893  Node *arraynode = (Node *) lsecond(saop->args);
3894  QualCost sacosts;
3895 
3896  set_sa_opfuncid(saop);
3897  sacosts.startup = sacosts.per_tuple = 0;
3898  add_function_cost(context->root, saop->opfuncid, NULL,
3899  &sacosts);
3900  context->total.startup += sacosts.startup;
3901  context->total.per_tuple += sacosts.per_tuple *
3902  estimate_array_length(arraynode) * 0.5;
3903  }
3904  else if (IsA(node, Aggref) ||
3905  IsA(node, WindowFunc))
3906  {
3907  /*
3908  * Aggref and WindowFunc nodes are (and should be) treated like Vars,
3909  * ie, zero execution cost in the current model, because they behave
3910  * essentially like Vars at execution. We disregard the costs of
3911  * their input expressions for the same reason. The actual execution
3912  * costs of the aggregate/window functions and their arguments have to
3913  * be factored into plan-node-specific costing of the Agg or WindowAgg
3914  * plan node.
3915  */
3916  return false; /* don't recurse into children */
3917  }
3918  else if (IsA(node, CoerceViaIO))
3919  {
3920  CoerceViaIO *iocoerce = (CoerceViaIO *) node;
3921  Oid iofunc;
3922  Oid typioparam;
3923  bool typisvarlena;
3924 
3925  /* check the result type's input function */
3926  getTypeInputInfo(iocoerce->resulttype,
3927  &iofunc, &typioparam);
3928  add_function_cost(context->root, iofunc, NULL,
3929  &context->total);
3930  /* check the input type's output function */
3931  getTypeOutputInfo(exprType((Node *) iocoerce->arg),
3932  &iofunc, &typisvarlena);
3933  add_function_cost(context->root, iofunc, NULL,
3934  &context->total);
3935  }
3936  else if (IsA(node, ArrayCoerceExpr))
3937  {
3938  ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
3939  QualCost perelemcost;
3940 
3941  cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
3942  context->root);
3943  context->total.startup += perelemcost.startup;
3944  if (perelemcost.per_tuple > 0)
3945  context->total.per_tuple += perelemcost.per_tuple *
3946  estimate_array_length((Node *) acoerce->arg);
3947  }
3948  else if (IsA(node, RowCompareExpr))
3949  {
3950  /* Conservatively assume we will check all the columns */
3951  RowCompareExpr *rcexpr = (RowCompareExpr *) node;
3952  ListCell *lc;
3953 
3954  foreach(lc, rcexpr->opnos)
3955  {
3956  Oid opid = lfirst_oid(lc);
3957 
3958  add_function_cost(context->root, get_opcode(opid), NULL,
3959  &context->total);
3960  }
3961  }
3962  else if (IsA(node, MinMaxExpr) ||
3963  IsA(node, SQLValueFunction) ||
3964  IsA(node, XmlExpr) ||
3965  IsA(node, CoerceToDomain) ||
3966  IsA(node, NextValueExpr))
3967  {
3968  /* Treat all these as having cost 1 */
3969  context->total.per_tuple += cpu_operator_cost;
3970  }
3971  else if (IsA(node, CurrentOfExpr))
3972  {
3973  /* Report high cost to prevent selection of anything but TID scan */
3974  context->total.startup += disable_cost;
3975  }
3976  else if (IsA(node, SubLink))
3977  {
3978  /* This routine should not be applied to un-planned expressions */
3979  elog(ERROR, "cannot handle unplanned sub-select");
3980  }
3981  else if (IsA(node, SubPlan))
3982  {
3983  /*
3984  * A subplan node in an expression typically indicates that the
3985  * subplan will be executed on each evaluation, so charge accordingly.
3986  * (Sub-selects that can be executed as InitPlans have already been
3987  * removed from the expression.)
3988  */
3989  SubPlan *subplan = (SubPlan *) node;
3990 
3991  context->total.startup += subplan->startup_cost;
3992  context->total.per_tuple += subplan->per_call_cost;
3993 
3994  /*
3995  * We don't want to recurse into the testexpr, because it was already
3996  * counted in the SubPlan node's costs. So we're done.
3997  */
3998  return false;
3999  }
4000  else if (IsA(node, AlternativeSubPlan))
4001  {
4002  /*
4003  * Arbitrarily use the first alternative plan for costing. (We should
4004  * certainly only include one alternative, and we don't yet have
4005  * enough information to know which one the executor is most likely to
4006  * use.)
4007  */
4008  AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
4009 
4010  return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
4011  context);
4012  }
4013  else if (IsA(node, PlaceHolderVar))
4014  {
4015  /*
4016  * A PlaceHolderVar should be given cost zero when considering general
4017  * expression evaluation costs. The expense of doing the contained
4018  * expression is charged as part of the tlist eval costs of the scan
4019  * or join where the PHV is first computed (see set_rel_width and
4020  * add_placeholders_to_joinrel). If we charged it again here, we'd be
4021  * double-counting the cost for each level of plan that the PHV
4022  * bubbles up through. Hence, return without recursing into the
4023  * phexpr.
4024  */
4025  return false;
4026  }
4027 
4028  /* recurse into children */
4030  (void *) context);
4031 }
QualCost eval_cost
Definition: pathnodes.h:1967
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3786
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
PlannerInfo * root
Definition: costsize.c:144
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2644
Expr * orclause
Definition: pathnodes.h:1961
Oid resulttype
Definition: primnodes.h:823
bool pseudoconstant
Definition: pathnodes.h:1938
Definition: nodes.h:524
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1883
unsigned int Oid
Definition: postgres_ext.h:31
#define lsecond(l)
Definition: pg_list.h:116
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:1807
#define linitial(l)
Definition: pg_list.h:111
#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:822
Expr * elemexpr
Definition: primnodes.h:847
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2611
Expr * clause
Definition: pathnodes.h:1930
Cost per_call_cost
Definition: primnodes.h:721
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1062
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:3800
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:720
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1630
#define lfirst_oid(lc)
Definition: pg_list.h:108

◆ 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:1101
Cost startup_cost
Definition: pathnodes.h:1111
Cost total_cost
Definition: pathnodes.h:1112
#define Max(x, y)
Definition: c.h:884
double rows
Definition: pathnodes.h:1110
double cpu_tuple_cost
Definition: costsize.c:112
double Cost
Definition: nodes.h:658

◆ cost_rescan()

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

Definition at line 3653 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().

3656 {
3657  switch (path->pathtype)
3658  {
3659  case T_FunctionScan:
3660 
3661  /*
3662  * Currently, nodeFunctionscan.c always executes the function to
3663  * completion before returning any rows, and caches the results in
3664  * a tuplestore. So the function eval cost is all startup cost
3665  * and isn't paid over again on rescans. However, all run costs
3666  * will be paid over again.
3667  */
3668  *rescan_startup_cost = 0;
3669  *rescan_total_cost = path->total_cost - path->startup_cost;
3670  break;
3671  case T_HashJoin:
3672 
3673  /*
3674  * If it's a single-batch join, we don't need to rebuild the hash
3675  * table during a rescan.
3676  */
3677  if (((HashPath *) path)->num_batches == 1)
3678  {
3679  /* Startup cost is exactly the cost of hash table building */
3680  *rescan_startup_cost = 0;
3681  *rescan_total_cost = path->total_cost - path->startup_cost;
3682  }
3683  else
3684  {
3685  /* Otherwise, no special treatment */
3686  *rescan_startup_cost = path->startup_cost;
3687  *rescan_total_cost = path->total_cost;
3688  }
3689  break;
3690  case T_CteScan:
3691  case T_WorkTableScan:
3692  {
3693  /*
3694  * These plan types materialize their final result in a
3695  * tuplestore or tuplesort object. So the rescan cost is only
3696  * cpu_tuple_cost per tuple, unless the result is large enough
3697  * to spill to disk.
3698  */
3699  Cost run_cost = cpu_tuple_cost * path->rows;
3700  double nbytes = relation_byte_size(path->rows,
3701  path->pathtarget->width);
3702  long work_mem_bytes = work_mem * 1024L;
3703 
3704  if (nbytes > work_mem_bytes)
3705  {
3706  /* It will spill, so account for re-read cost */
3707  double npages = ceil(nbytes / BLCKSZ);
3708 
3709  run_cost += seq_page_cost * npages;
3710  }
3711  *rescan_startup_cost = 0;
3712  *rescan_total_cost = run_cost;
3713  }
3714  break;
3715  case T_Material:
3716  case T_Sort:
3717  {
3718  /*
3719  * These plan types not only materialize their results, but do
3720  * not implement qual filtering or projection. So they are
3721  * even cheaper to rescan than the ones above. We charge only
3722  * cpu_operator_cost per tuple. (Note: keep that in sync with
3723  * the run_cost charge in cost_sort, and also see comments in
3724  * cost_material before you change it.)
3725  */
3726  Cost run_cost = cpu_operator_cost * path->rows;
3727  double nbytes = relation_byte_size(path->rows,
3728  path->pathtarget->width);
3729  long work_mem_bytes = work_mem * 1024L;
3730 
3731  if (nbytes > work_mem_bytes)
3732  {
3733  /* It will spill, so account for re-read cost */
3734  double npages = ceil(nbytes / BLCKSZ);
3735 
3736  run_cost += seq_page_cost * npages;
3737  }
3738  *rescan_startup_cost = 0;
3739  *rescan_total_cost = run_cost;
3740  }
3741  break;
3742  default:
3743  *rescan_startup_cost = path->startup_cost;
3744  *rescan_total_cost = path->total_cost;
3745  break;
3746  }
3747 }
Definition: nodes.h:76
NodeTag pathtype
Definition: pathnodes.h:1098
Cost startup_cost
Definition: pathnodes.h:1111
double cpu_operator_cost
Definition: costsize.c:114
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5402
int work_mem
Definition: globals.c:121
Cost total_cost
Definition: pathnodes.h:1112
double cpu_tuple_cost
Definition: costsize.c:112
double seq_page_cost
Definition: costsize.c:110
double Cost
Definition: nodes.h:658

◆ 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:669
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
Cost startup_cost
Definition: pathnodes.h:1111
Index relid
Definition: pathnodes.h:657
RTEKind rtekind
Definition: pathnodes.h:659
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4046
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
double Cost
Definition: nodes.h:658

◆ 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:1101
double tuples
Definition: pathnodes.h:669
Oid reltablespace
Definition: pathnodes.h:658
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
Cost startup_cost
Definition: pathnodes.h:1111
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:361
NextSampleBlock_function NextSampleBlock
Definition: tsmapi.h:72
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:657
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4046
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
BlockNumber pages
Definition: pathnodes.h:668
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
QualCost cost
Definition: pathnodes.h:1032
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
RTEKind rtekind
Definition: parsenodes.h:963
struct TableSampleClause * tablesample
Definition: parsenodes.h:993
double Cost
Definition: nodes.h:658

◆ 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:1101
double tuples
Definition: pathnodes.h:669
Oid reltablespace
Definition: pathnodes.h:658
int parallel_workers
Definition: pathnodes.h:1107
bool enable_seqscan
Definition: costsize.c:124
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
Cost startup_cost
Definition: pathnodes.h:1111
Cost disable_cost
Definition: costsize.c:120
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5423
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:657
RTEKind rtekind
Definition: pathnodes.h:659
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4046
BlockNumber pages
Definition: pathnodes.h:668
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
QualCost cost
Definition: pathnodes.h:1032
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
double clamp_row_est(double nrows)
Definition: costsize.c:187
double Cost
Definition: nodes.h:658

◆ 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 choose_hashed_setop(), 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:1111
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:5402
Cost total_cost
Definition: pathnodes.h:1112
#define LOG2(x)
Definition: costsize.c:100
double rows
Definition: pathnodes.h:1110
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:2352
double seq_page_cost
Definition: costsize.c:110
double Cost
Definition: nodes.h:658

◆ cost_subplan()

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

Definition at line 3560 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().

3561 {
3562  QualCost sp_cost;
3563 
3564  /* Figure any cost for evaluating the testexpr */
3565  cost_qual_eval(&sp_cost,
3566  make_ands_implicit((Expr *) subplan->testexpr),
3567  root);
3568 
3569  if (subplan->useHashTable)
3570  {
3571  /*
3572  * If we are using a hash table for the subquery outputs, then the
3573  * cost of evaluating the query is a one-time cost. We charge one
3574  * cpu_operator_cost per tuple for the work of loading the hashtable,
3575  * too.
3576  */
3577  sp_cost.startup += plan->total_cost +
3578  cpu_operator_cost * plan->plan_rows;
3579 
3580  /*
3581  * The per-tuple costs include the cost of evaluating the lefthand
3582  * expressions, plus the cost of probing the hashtable. We already
3583  * accounted for the lefthand expressions as part of the testexpr, and
3584  * will also have counted one cpu_operator_cost for each comparison
3585  * operator. That is probably too low for the probing cost, but it's
3586  * hard to make a better estimate, so live with it for now.
3587  */
3588  }
3589  else
3590  {
3591  /*
3592  * Otherwise we will be rescanning the subplan output on each
3593  * evaluation. We need to estimate how much of the output we will
3594  * actually need to scan. NOTE: this logic should agree with the
3595  * tuple_fraction estimates used by make_subplan() in
3596  * plan/subselect.c.
3597  */
3598  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
3599 
3600  if (subplan->subLinkType == EXISTS_SUBLINK)
3601  {
3602  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
3603  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
3604  }
3605  else if (subplan->subLinkType == ALL_SUBLINK ||
3606  subplan->subLinkType == ANY_SUBLINK)
3607  {
3608  /* assume we need 50% of the tuples */
3609  sp_cost.per_tuple += 0.50 * plan_run_cost;
3610  /* also charge a cpu_operator_cost per row examined */
3611  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
3612  }
3613  else
3614  {
3615  /* assume we need all tuples */
3616  sp_cost.per_tuple += plan_run_cost;
3617  }
3618 
3619  /*
3620  * Also account for subplan's startup cost. If the subplan is
3621  * uncorrelated or undirect correlated, AND its topmost node is one
3622  * that materializes its output, assume that we'll only need to pay
3623  * its startup cost once; otherwise assume we pay the startup cost
3624  * every time.
3625  */
3626  if (subplan->parParam == NIL &&
3628  sp_cost.startup += plan->startup_cost;
3629  else
3630  sp_cost.per_tuple += plan->startup_cost;
3631  }
3632 
3633  subplan->startup_cost = sp_cost.startup;
3634  subplan->per_call_cost = sp_cost.per_tuple;
3635 }
#define NIL
Definition: pg_list.h:69
double plan_rows
Definition: plannodes.h:127
SubLinkType subLinkType
Definition: primnodes.h:692
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3760
Cost startup_cost
Definition: plannodes.h:121
double cpu_operator_cost
Definition: costsize.c:114
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:717
Node * testexpr
Definition: primnodes.h:694
Cost per_call_cost
Definition: primnodes.h:721
List * parParam
Definition: primnodes.h:717
#define nodeTag(nodeptr)
Definition: nodes.h:529
Cost total_cost
Definition: plannodes.h:122
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:581
bool useHashTable
Definition: primnodes.h:706
Cost startup_cost
Definition: primnodes.h:720
double clamp_row_est(double nrows)
Definition: costsize.c:187
double Cost
Definition: nodes.h:658

◆ 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:1101
double tuples
Definition: pathnodes.h:669
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
Cost startup_cost
Definition: pathnodes.h:1111
Index relid
Definition: pathnodes.h:657
RTEKind rtekind
Definition: pathnodes.h:659
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4046
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
QualCost cost
Definition: pathnodes.h:1032
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
double Cost
Definition: nodes.h:658

◆ 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:3786
PathTarget * pathtarget
Definition: pathnodes.h:1101
double tuples
Definition: pathnodes.h:669
Definition: nodes.h:524
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
TableFunc * tablefunc
Definition: parsenodes.h:1035
Cost startup_cost
Definition: pathnodes.h:1111
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:361
Index relid
Definition: pathnodes.h:657
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4046
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
QualCost cost
Definition: pathnodes.h:1032
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
RTEKind rtekind
Definition: parsenodes.h:963
double Cost
Definition: nodes.h:658

◆ 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:575
PathTarget * pathtarget
Definition: pathnodes.h:1101
bool enable_tidscan
Definition: costsize.c:128
Oid reltablespace
Definition: pathnodes.h:658
Definition: nodes.h:524
#define lsecond(l)
Definition: pg_list.h:116
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:1807
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3760
Cost startup_cost
Definition: pathnodes.h:1111
Cost disable_cost
Definition: costsize.c:120
#define lfirst_node(type, lc)
Definition: pg_list.h:109
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:657
Expr * clause
Definition: pathnodes.h:1930
RTEKind rtekind
Definition: pathnodes.h:659
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4046
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
QualCost cost
Definition: pathnodes.h:1032
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
QualCost baserestrictcost
Definition: pathnodes.h:690
double Cost
Definition: nodes.h:658

◆ 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:1101
double tuples
Definition: pathnodes.h:669
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
Cost startup_cost
Definition: pathnodes.h:1111
double cpu_operator_cost
Definition: costsize.c:114
Index relid
Definition: pathnodes.h:657
RTEKind rtekind
Definition: pathnodes.h:659
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4046
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
QualCost cost
Definition: pathnodes.h:1032
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
double Cost
Definition: nodes.h:658

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

2217 {
2218  Cost startup_cost;
2219  Cost total_cost;
2220  ListCell *lc;
2221 
2222  startup_cost = input_startup_cost;
2223  total_cost = input_total_cost;
2224 
2225  /*
2226  * Window functions are assumed to cost their stated execution cost, plus
2227  * the cost of evaluating their input expressions, per tuple. Since they
2228  * may in fact evaluate their inputs at multiple rows during each cycle,
2229  * this could be a drastic underestimate; but without a way to know how
2230  * many rows the window function will fetch, it's hard to do better. In
2231  * any case, it's a good estimate for all the built-in window functions,
2232  * so we'll just do this for now.
2233  */
2234  foreach(lc, windowFuncs)
2235  {
2236  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
2237  Cost wfunccost;
2238  QualCost argcosts;
2239 
2240  argcosts.startup = argcosts.per_tuple = 0;
2241  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
2242  &argcosts);
2243  startup_cost += argcosts.startup;
2244  wfunccost = argcosts.per_tuple;
2245 
2246  /* also add the input expressions' cost to per-input-row costs */
2247  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
2248  startup_cost += argcosts.startup;
2249  wfunccost += argcosts.per_tuple;
2250 
2251  /*
2252  * Add the filter's cost to per-input-row costs. XXX We should reduce
2253  * input expression costs according to filter selectivity.
2254  */
2255  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
2256  startup_cost += argcosts.startup;
2257  wfunccost += argcosts.per_tuple;
2258 
2259  total_cost += wfunccost * input_tuples;
2260  }
2261 
2262  /*
2263  * We also charge cpu_operator_cost per grouping column per tuple for
2264  * grouping comparisons, plus cpu_tuple_cost per tuple for general
2265  * overhead.
2266  *
2267  * XXX this neglects costs of spooling the data to disk when it overflows
2268  * work_mem. Sooner or later that should get accounted for.
2269  */
2270  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
2271  total_cost += cpu_tuple_cost * input_tuples;
2272 
2273  path->rows = input_tuples;
2274  path->startup_cost = startup_cost;
2275  path->total_cost = total_cost;
2276 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3786
List * args
Definition: primnodes.h:363
Definition: nodes.h:524
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1883
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
Cost startup_cost
Definition: pathnodes.h:1111
#define lfirst_node(type, lc)
Definition: pg_list.h:109
double cpu_operator_cost
Definition: costsize.c:114
Oid winfnoid
Definition: primnodes.h:359
Cost total_cost
Definition: pathnodes.h:1112
Expr * aggfilter
Definition: primnodes.h:364
double rows
Definition: pathnodes.h:1110
double cpu_tuple_cost
Definition: costsize.c:112
double Cost
Definition: nodes.h:658

◆ 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:69
bool pseudoconstant
Definition: pathnodes.h:1938
bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
Definition: equivclass.c:2530
#define lfirst_node(type, lc)
Definition: pg_list.h:109
List * lappend(List *list, void *datum)
Definition: list.c:128
Definition: pg_list.h:45

◆ final_cost_hashjoin()

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

Definition at line 3305 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().

3308 {
3309  Path *outer_path = path->jpath.outerjoinpath;
3310  Path *inner_path = path->jpath.innerjoinpath;
3311  double outer_path_rows = outer_path->rows;
3312  double inner_path_rows = inner_path->rows;
3313  double inner_path_rows_total = workspace->inner_rows_total;
3314  List *hashclauses = path->path_hashclauses;
3315  Cost startup_cost = workspace->startup_cost;
3316  Cost run_cost = workspace->run_cost;
3317  int numbuckets = workspace->numbuckets;
3318  int numbatches = workspace->numbatches;
3319  Cost cpu_per_tuple;
3320  QualCost hash_qual_cost;
3321  QualCost qp_qual_cost;
3322  double hashjointuples;
3323  double virtualbuckets;
3324  Selectivity innerbucketsize;
3325  Selectivity innermcvfreq;
3326  ListCell *hcl;
3327 
3328  /* Mark the path with the correct row estimate */
3329  if (path->jpath.path.param_info)
3330  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3331  else
3332  path->jpath.path.rows = path->jpath.path.parent->rows;
3333 
3334  /* For partial paths, scale row estimate. */
3335  if (path->jpath.path.parallel_workers > 0)
3336  {
3337  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3338 
3339  path->jpath.path.rows =
3340  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3341  }
3342 
3343  /*
3344  * We could include disable_cost in the preliminary estimate, but that
3345  * would amount to optimizing for the case where the join method is
3346  * disabled, which doesn't seem like the way to bet.
3347  */
3348  if (!enable_hashjoin)
3349  startup_cost += disable_cost;
3350 
3351  /* mark the path with estimated # of batches */
3352  path->num_batches = numbatches;
3353 
3354  /* store the total number of tuples (sum of partial row estimates) */
3355  path->inner_rows_total = inner_path_rows_total;
3356 
3357  /* and compute the number of "virtual" buckets in the whole join */
3358  virtualbuckets = (double) numbuckets * (double) numbatches;
3359 
3360  /*
3361  * Determine bucketsize fraction and MCV frequency for the inner relation.
3362  * We use the smallest bucketsize or MCV frequency estimated for any
3363  * individual hashclause; this is undoubtedly conservative.
3364  *
3365  * BUT: if inner relation has been unique-ified, we can assume it's good
3366  * for hashing. This is important both because it's the right answer, and
3367  * because we avoid contaminating the cache with a value that's wrong for
3368  * non-unique-ified paths.
3369  */
3370  if (IsA(inner_path, UniquePath))
3371  {
3372  innerbucketsize = 1.0 / virtualbuckets;
3373  innermcvfreq = 0.0;
3374  }
3375  else
3376  {
3377  innerbucketsize = 1.0;
3378  innermcvfreq = 1.0;
3379  foreach(hcl, hashclauses)
3380  {
3381  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
3382  Selectivity thisbucketsize;
3383  Selectivity thismcvfreq;
3384 
3385  /*
3386  * First we have to figure out which side of the hashjoin clause
3387  * is the inner side.
3388  *
3389  * Since we tend to visit the same clauses over and over when
3390  * planning a large query, we cache the bucket stats estimates in
3391  * the RestrictInfo node to avoid repeated lookups of statistics.
3392  */
3393  if (bms_is_subset(restrictinfo->right_relids,
3394  inner_path->parent->relids))
3395  {
3396  /* righthand side is inner */
3397  thisbucketsize = restrictinfo->right_bucketsize;
3398  if (thisbucketsize < 0)
3399  {
3400  /* not cached yet */
3402  get_rightop(restrictinfo->clause),
3403  virtualbuckets,
3404  &restrictinfo->right_mcvfreq,
3405  &restrictinfo->right_bucketsize);
3406  thisbucketsize = restrictinfo->right_bucketsize;
3407  }
3408  thismcvfreq = restrictinfo->right_mcvfreq;
3409  }
3410  else
3411  {
3412  Assert(bms_is_subset(restrictinfo->left_relids,
3413  inner_path->parent->relids));
3414  /* lefthand side is inner */
3415  thisbucketsize = restrictinfo->left_bucketsize;
3416  if (thisbucketsize < 0)
3417  {
3418  /* not cached yet */
3420  get_leftop(restrictinfo->clause),
3421  virtualbuckets,
3422  &restrictinfo->left_mcvfreq,
3423  &restrictinfo->left_bucketsize);
3424  thisbucketsize = restrictinfo->left_bucketsize;
3425  }
3426  thismcvfreq = restrictinfo->left_mcvfreq;
3427  }
3428 
3429  if (innerbucketsize > thisbucketsize)
3430  innerbucketsize = thisbucketsize;
3431  if (innermcvfreq > thismcvfreq)
3432  innermcvfreq = thismcvfreq;
3433  }
3434  }
3435 
3436  /*
3437  * If the bucket holding the inner MCV would exceed work_mem, we don't
3438  * want to hash unless there is really no other alternative, so apply
3439  * disable_cost. (The executor normally copes with excessive memory usage
3440  * by splitting batches, but obviously it cannot separate equal values
3441  * that way, so it will be unable to drive the batch size below work_mem
3442  * when this is true.)
3443  */
3444  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
3445  inner_path->pathtarget->width) >
3446  (work_mem * 1024L))
3447  startup_cost += disable_cost;
3448 
3449  /*
3450  * Compute cost of the hashquals and qpquals (other restriction clauses)
3451  * separately.
3452  */
3453  cost_qual_eval(&hash_qual_cost, hashclauses, root);
3454  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3455  qp_qual_cost.startup -= hash_qual_cost.startup;
3456  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
3457 
3458  /* CPU costs */
3459 
3460  if (path->jpath.jointype == JOIN_SEMI ||
3461  path->jpath.jointype == JOIN_ANTI ||
3462  extra->inner_unique)
3463  {
3464  double outer_matched_rows;
3465  Selectivity inner_scan_frac;
3466 
3467  /*
3468  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3469  * executor will stop after the first match.
3470  *
3471  * For an outer-rel row that has at least one match, we can expect the
3472  * bucket scan to stop after a fraction 1/(match_count+1) of the
3473  * bucket's rows, if the matches are evenly distributed. Since they
3474  * probably aren't quite evenly distributed, we apply a fuzz factor of
3475  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
3476  * to clamp inner_scan_frac to at most 1.0; but since match_count is
3477  * at least 1, no such clamp is needed now.)
3478  */
3479  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3480  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3481 
3482  startup_cost += hash_qual_cost.startup;
3483  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
3484  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
3485 
3486  /*
3487  * For unmatched outer-rel rows, the picture is quite a lot different.
3488  * In the first place, there is no reason to assume that these rows
3489  * preferentially hit heavily-populated buckets; instead assume they
3490  * are uncorrelated with the inner distribution and so they see an
3491  * average bucket size of inner_path_rows / virtualbuckets. In the
3492  * second place, it seems likely that they will have few if any exact
3493  * hash-code matches and so very few of the tuples in the bucket will
3494  * actually require eval of the hash quals. We don't have any good
3495  * way to estimate how many will, but for the moment assume that the
3496  * effective cost per bucket entry is one-tenth what it is for
3497  * matchable tuples.
3498  */
3499  run_cost += hash_qual_cost.per_tuple *
3500  (outer_path_rows - outer_matched_rows) *
3501  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
3502 
3503  /* Get # of tuples that will pass the basic join */
3504  if (path->jpath.jointype == JOIN_ANTI)
3505  hashjointuples = outer_path_rows - outer_matched_rows;
3506  else
3507  hashjointuples = outer_matched_rows;
3508  }
3509  else
3510  {
3511  /*
3512  * The number of tuple comparisons needed is the number of outer
3513  * tuples times the typical number of tuples in a hash bucket, which
3514  * is the inner relation size times its bucketsize fraction. At each
3515  * one, we need to evaluate the hashjoin quals. But actually,
3516  * charging the full qual eval cost at each tuple is pessimistic,
3517  * since we don't evaluate the quals unless the hash values match
3518  * exactly. For lack of a better idea, halve the cost estimate to
3519  * allow for that.
3520  */
3521  startup_cost += hash_qual_cost.startup;
3522  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
3523  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
3524 
3525  /*
3526  * Get approx # tuples passing the hashquals. We use
3527  * approx_tuple_count here because we need an estimate done with
3528  * JOIN_INNER semantics.
3529  */
3530  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
3531  }
3532 
3533  /*
3534  * For each tuple that gets through the hashjoin proper, we charge
3535  * cpu_tuple_cost plus the cost of evaluating additional restriction
3536  * clauses that are to be applied at the join. (This is pessimistic since
3537  * not all of the quals may get evaluated at each tuple.)
3538  */
3539  startup_cost += qp_qual_cost.startup;
3540  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3541  run_cost += cpu_per_tuple * hashjointuples;
3542 
3543  /* tlist eval costs are paid per output row, not per tuple scanned */
3544  startup_cost += path->jpath.path.pathtarget->cost.startup;
3545  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3546 
3547  path->jpath.path.startup_cost = startup_cost;
3548  path->jpath.path.total_cost = startup_cost + run_cost;
3549 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
JoinPath jpath
Definition: pathnodes.h:1556
PathTarget * pathtarget
Definition: pathnodes.h:1101
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:2368
int num_batches
Definition: pathnodes.h:1558
Selectivity right_mcvfreq
Definition: pathnodes.h:1994
Selectivity outer_match_frac
Definition: pathnodes.h:2345
Path * innerjoinpath
Definition: pathnodes.h:1483
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4289
int parallel_workers
Definition: pathnodes.h:1107
ParamPathInfo * param_info
Definition: pathnodes.h:1103
Relids left_relids
Definition: pathnodes.h:1957
double Selectivity
Definition: nodes.h:657
double inner_rows_total
Definition: pathnodes.h:1559
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3760
Cost startup_cost
Definition: pathnodes.h:1111
Cost disable_cost
Definition: costsize.c:120
List * joinrestrictinfo
Definition: pathnodes.h:1485
RelOptInfo * parent
Definition: pathnodes.h:1100
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
#define lfirst_node(type, lc)
Definition: pg_list.h:109
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5423
Relids relids
Definition: pathnodes.h:629
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:69
double rint(double x)
Definition: rint.c:21
Expr * clause
Definition: pathnodes.h:1930
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5402
Path * outerjoinpath
Definition: pathnodes.h:1482
double inner_rows_total
Definition: pathnodes.h:2471
int work_mem
Definition: globals.c:121
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:81
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
Selectivity left_bucketsize
Definition: pathnodes.h:1991
Relids right_relids
Definition: pathnodes.h:1958
Path path
Definition: pathnodes.h:1475
#define Assert(condition)
Definition: c.h:732
double rows
Definition: pathnodes.h:1110
Selectivity left_mcvfreq
Definition: pathnodes.h:1993
QualCost cost
Definition: pathnodes.h:1032
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
bool enable_hashjoin
Definition: costsize.c:134
Selectivity match_count
Definition: pathnodes.h:2346
Selectivity right_bucketsize
Definition: pathnodes.h:1992
JoinType jointype
Definition: pathnodes.h:1477
void estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
Definition: selfuncs.c:3328
List * path_hashclauses
Definition: pathnodes.h:1557
double clamp_row_est(double nrows)
Definition: costsize.c:187
Definition: pg_list.h:45
double Cost
Definition: nodes.h:658

◆ final_cost_mergejoin()

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

Definition at line 2869 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().

2872 {
2873  Path *outer_path = path->jpath.outerjoinpath;
2874  Path *inner_path = path->jpath.innerjoinpath;
2875  double inner_path_rows = inner_path->rows;
2876  List *mergeclauses = path->path_mergeclauses;
2877  List *innersortkeys = path->innersortkeys;
2878  Cost startup_cost = workspace->startup_cost;
2879  Cost run_cost = workspace->run_cost;
2880  Cost inner_run_cost = workspace->inner_run_cost;
2881  double outer_rows = workspace->outer_rows;
2882  double inner_rows = workspace->inner_rows;
2883  double outer_skip_rows = workspace->outer_skip_rows;
2884  double inner_skip_rows = workspace->inner_skip_rows;
2885  Cost cpu_per_tuple,
2886  bare_inner_cost,
2887  mat_inner_cost;
2888  QualCost merge_qual_cost;
2889  QualCost qp_qual_cost;
2890  double mergejointuples,
2891  rescannedtuples;
2892  double rescanratio;
2893 
2894  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2895  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2896  inner_path_rows = 1;
2897 
2898  /* Mark the path with the correct row estimate */
2899  if (path->jpath.path.param_info)
2900  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2901  else
2902  path->jpath.path.rows = path->jpath.path.parent->rows;
2903 
2904  /* For partial paths, scale row estimate. */
2905  if (path->jpath.path.parallel_workers > 0)
2906  {
2907  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
2908 
2909  path->jpath.path.rows =
2910  clamp_row_est(path->jpath.path.rows / parallel_divisor);
2911  }
2912 
2913  /*
2914  * We could include disable_cost in the preliminary estimate, but that
2915  * would amount to optimizing for the case where the join method is
2916  * disabled, which doesn't seem like the way to bet.
2917  */
2918  if (!enable_mergejoin)
2919  startup_cost += disable_cost;
2920 
2921  /*
2922  * Compute cost of the mergequals and qpquals (other restriction clauses)
2923  * separately.
2924  */
2925  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
2926  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2927  qp_qual_cost.startup -= merge_qual_cost.startup;
2928  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
2929 
2930  /*
2931  * With a SEMI or ANTI join, or if the innerrel is known unique, the
2932  * executor will stop scanning for matches after the first match. When
2933  * all the joinclauses are merge clauses, this means we don't ever need to
2934  * back up the merge, and so we can skip mark/restore overhead.
2935  */
2936  if ((path->jpath.jointype == JOIN_SEMI ||
2937  path->jpath.jointype == JOIN_ANTI ||
2938  extra->inner_unique) &&
2941  path->skip_mark_restore = true;
2942  else
2943  path->skip_mark_restore = false;
2944 
2945  /*
2946  * Get approx # tuples passing the mergequals. We use approx_tuple_count
2947  * here because we need an estimate done with JOIN_INNER semantics.
2948  */
2949  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
2950 
2951  /*
2952  * When there are equal merge keys in the outer relation, the mergejoin
2953  * must rescan any matching tuples in the inner relation. This means
2954  * re-fetching inner tuples; we have to estimate how often that happens.
2955  *
2956  * For regular inner and outer joins, the number of re-fetches can be
2957  * estimated approximately as size of merge join output minus size of
2958  * inner relation. Assume that the distinct key values are 1, 2, ..., and
2959  * denote the number of values of each key in the outer relation as m1,
2960  * m2, ...; in the inner relation, n1, n2, ... Then we have
2961  *
2962  * size of join = m1 * n1 + m2 * n2 + ...
2963  *
2964  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
2965  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
2966  * relation
2967  *
2968  * This equation works correctly for outer tuples having no inner match
2969  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
2970  * are effectively subtracting those from the number of rescanned tuples,
2971  * when we should not. Can we do better without expensive selectivity
2972  * computations?
2973  *
2974  * The whole issue is moot if we are working from a unique-ified outer
2975  * input, or if we know we don't need to mark/restore at all.
2976  */
2977  if (IsA(outer_path, UniquePath) ||path->skip_mark_restore)
2978  rescannedtuples = 0;
2979  else
2980  {
2981  rescannedtuples = mergejointuples - inner_path_rows;
2982  /* Must clamp because of possible underestimate */
2983  if (rescannedtuples < 0)
2984  rescannedtuples = 0;
2985  }
2986 
2987  /*
2988  * We'll inflate various costs this much to account for rescanning. Note
2989  * that this is to be multiplied by something involving inner_rows, or
2990  * another number related to the portion of the inner rel we'll scan.
2991  */
2992  rescanratio = 1.0 + (rescannedtuples / inner_rows);
2993 
2994  /*
2995  * Decide whether we want to materialize the inner input to shield it from
2996  * mark/restore and performing re-fetches. Our cost model for regular
2997  * re-fetches is that a re-fetch costs the same as an original fetch,
2998  * which is probably an overestimate; but on the other hand we ignore the
2999  * bookkeeping costs of mark/restore. Not clear if it's worth developing
3000  * a more refined model. So we just need to inflate the inner run cost by
3001  * rescanratio.
3002  */
3003  bare_inner_cost = inner_run_cost * rescanratio;
3004 
3005  /*
3006  * When we interpose a Material node the re-fetch cost is assumed to be
3007  * just cpu_operator_cost per tuple, independently of the underlying
3008  * plan's cost; and we charge an extra cpu_operator_cost per original
3009  * fetch as well. Note that we're assuming the materialize node will
3010  * never spill to disk, since it only has to remember tuples back to the
3011  * last mark. (If there are a huge number of duplicates, our other cost
3012  * factors will make the path so expensive that it probably won't get
3013  * chosen anyway.) So we don't use cost_rescan here.
3014  *
3015  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3016  * of the generated Material node.
3017  */
3018  mat_inner_cost = inner_run_cost +
3019  cpu_operator_cost * inner_rows * rescanratio;
3020 
3021  /*
3022  * If we don't need mark/restore at all, we don't need materialization.
3023  */
3024  if (path->skip_mark_restore)
3025  path->materialize_inner = false;
3026 
3027  /*
3028  * Prefer materializing if it looks cheaper, unless the user has asked to
3029  * suppress materialization.
3030  */
3031  else if (enable_material && mat_inner_cost < bare_inner_cost)
3032  path->materialize_inner = true;
3033 
3034  /*
3035  * Even if materializing doesn't look cheaper, we *must* do it if the
3036  * inner path is to be used directly (without sorting) and it doesn't
3037  * support mark/restore.
3038  *
3039  * Since the inner side must be ordered, and only Sorts and IndexScans can
3040  * create order to begin with, and they both support mark/restore, you
3041  * might think there's no problem --- but you'd be wrong. Nestloop and
3042  * merge joins can *preserve* the order of their inputs, so they can be
3043  * selected as the input of a mergejoin, and they don't support
3044  * mark/restore at present.
3045  *
3046  * We don't test the value of enable_material here, because
3047  * materialization is required for correctness in this case, and turning
3048  * it off does not entitle us to deliver an invalid plan.
3049  */
3050  else if (innersortkeys == NIL &&
3051  !ExecSupportsMarkRestore(inner_path))
3052  path->materialize_inner = true;
3053 
3054  /*
3055  * Also, force materializing if the inner path is to be sorted and the
3056  * sort is expected to spill to disk. This is because the final merge
3057  * pass can be done on-the-fly if it doesn't have to support mark/restore.
3058  * We don't try to adjust the cost estimates for this consideration,
3059  * though.
3060  *
3061  * Since materialization is a performance optimization in this case,
3062  * rather than necessary for correctness, we skip it if enable_material is
3063  * off.
3064  */
3065  else if (enable_material && innersortkeys != NIL &&
3066  relation_byte_size(inner_path_rows,
3067  inner_path->pathtarget->width) >
3068  (work_mem * 1024L))
3069  path->materialize_inner = true;
3070  else
3071  path->materialize_inner = false;
3072 
3073  /* Charge the right incremental cost for the chosen case */
3074  if (path->materialize_inner)
3075  run_cost += mat_inner_cost;
3076  else
3077  run_cost += bare_inner_cost;
3078 
3079  /* CPU costs */
3080 
3081  /*
3082  * The number of tuple comparisons needed is approximately number of outer
3083  * rows plus number of inner rows plus number of rescanned tuples (can we
3084  * refine this?). At each one, we need to evaluate the mergejoin quals.
3085  */
3086  startup_cost += merge_qual_cost.startup;
3087  startup_cost += merge_qual_cost.per_tuple *
3088  (outer_skip_rows + inner_skip_rows * rescanratio);
3089  run_cost += merge_qual_cost.per_tuple *
3090  ((outer_rows - outer_skip_rows) +
3091  (inner_rows - inner_skip_rows) * rescanratio);
3092 
3093  /*
3094  * For each tuple that gets through the mergejoin proper, we charge
3095  * cpu_tuple_cost plus the cost of evaluating additional restriction
3096  * clauses that are to be applied at the join. (This is pessimistic since
3097  * not all of the quals may get evaluated at each tuple.)
3098  *
3099  * Note: we could adjust for SEMI/ANTI joins skipping some qual
3100  * evaluations here, but it's probably not worth the trouble.
3101  */
3102  startup_cost += qp_qual_cost.startup;
3103  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3104  run_cost += cpu_per_tuple * mergejointuples;
3105 
3106  /* tlist eval costs are paid per output row, not per tuple scanned */
3107  startup_cost += path->jpath.path.pathtarget->cost.startup;
3108  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3109 
3110  path->jpath.path.startup_cost = startup_cost;
3111  path->jpath.path.total_cost = startup_cost + run_cost;
3112 }
#define NIL
Definition: pg_list.h:69
List * path_mergeclauses
Definition: pathnodes.h:1538
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
PathTarget * pathtarget
Definition: pathnodes.h:1101
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:406
bool materialize_inner
Definition: pathnodes.h:1542
Path * innerjoinpath
Definition: pathnodes.h:1483
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4289
int parallel_workers
Definition: pathnodes.h:1107
ParamPathInfo * param_info
Definition: pathnodes.h:1103
Cost startup
Definition: pathnodes.h:46
Cost per_tuple
Definition: pathnodes.h:47
bool skip_mark_restore
Definition: pathnodes.h:1541
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3760
Cost startup_cost
Definition: pathnodes.h:1111
Cost disable_cost
Definition: costsize.c:120
List * joinrestrictinfo
Definition: pathnodes.h:1485
RelOptInfo * parent
Definition: pathnodes.h:1100
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5423
double cpu_operator_cost
Definition: costsize.c:114
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5402
Path * outerjoinpath
Definition: pathnodes.h:1482
int work_mem
Definition: globals.c:121
double rows
Definition: pathnodes.h:632
Cost total_cost
Definition: pathnodes.h:1112
double outer_skip_rows
Definition: pathnodes.h:2465
bool enable_mergejoin
Definition: costsize.c:133
Path path
Definition: pathnodes.h:1475
double rows
Definition: pathnodes.h:1110
QualCost cost
Definition: pathnodes.h:1032
static int list_length(const List *l)
Definition: pg_list.h:89
List * innersortkeys
Definition: pathnodes.h:1540
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1060
JoinType jointype
Definition: pathnodes.h:1477
JoinPath jpath
Definition: pathnodes.h:1537
double inner_skip_rows
Definition: pathnodes.h:2466
double clamp_row_est(double nrows)
Definition: costsize.c:187
Definition: pg_list.h:45
double Cost
Definition: nodes.h:658
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 2432 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().

2435 {
2436  Path *outer_path = path->outerjoinpath;
2437  Path *inner_path = path->innerjoinpath;
2438  double outer_path_rows = outer_path->rows;
2439  double inner_path_rows = inner_path->rows;
2440  Cost startup_cost = workspace->startup_cost;
2441  Cost run_cost = workspace->run_cost;
2442  Cost cpu_per_tuple;
2443  QualCost restrict_qual_cost;
2444  double ntuples;
2445 
2446  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2447  if (outer_path_rows <= 0 || isnan(outer_path_rows))
2448  outer_path_rows = 1;
2449  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2450  inner_path_rows = 1;
2451 
2452  /* Mark the path with the correct row estimate */
2453  if (path->path.param_info)
2454  path->path.rows = path->path.param_info->ppi_rows;
2455  else
2456  path->path.rows = path->path.parent->rows;
2457 
2458  /* For partial paths, scale row estimate. */
2459  if (path->path.parallel_workers > 0)
2460  {
2461  double parallel_divisor = get_parallel_divisor(&path->path);
2462 
2463  path->path.rows =
2464  clamp_row_est(path->path.rows / parallel_divisor);
2465  }
2466 
2467  /*
2468  * We could include disable_cost in the preliminary estimate, but that
2469  * would amount to optimizing for the case where the join method is
2470  * disabled, which doesn't seem like the way to bet.
2471  */
2472  if (!enable_nestloop)
2473  startup_cost += disable_cost;
2474 
2475  /* cost of inner-relation source data (we already dealt with outer rel) */
2476 
2477  if (path->jointype == JOIN_SEMI || path->jointype == JOIN_ANTI ||
2478  extra->inner_unique)
2479  {
2480  /*
2481  * With a SEMI or ANTI join, or if the innerrel is known unique, the
2482  * executor will stop after the first match.
2483  */
2484  Cost inner_run_cost = workspace->inner_run_cost;
2485  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
2486  double outer_matched_rows;
2487  double outer_unmatched_rows;
2488  Selectivity inner_scan_frac;
2489 
2490  /*
2491  * For an outer-rel row that has at least one match, we can expect the
2492  * inner scan to stop after a fraction 1/(match_count+1) of the inner
2493  * rows, if the matches are evenly distributed. Since they probably
2494  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
2495  * that fraction. (If we used a larger fuzz factor, we'd have to
2496  * clamp inner_scan_frac to at most 1.0; but since match_count is at
2497  * least 1, no such clamp is needed now.)
2498  */
2499  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
2500  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
2501  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
2502 
2503  /*
2504  * Compute number of tuples processed (not number emitted!). First,
2505  * account for successfully-matched outer rows.
2506  */
2507  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
2508 
2509  /*
2510  * Now we need to estimate the actual costs of scanning the inner
2511  * relation, which may be quite a bit less than N times inner_run_cost
2512  * due to early scan stops. We consider two cases. If the inner path
2513  * is an indexscan using all the joinquals as indexquals, then an
2514  * unmatched outer row results in an indexscan returning no rows,
2515  * which is probably quite cheap. Otherwise, the executor will have
2516  * to scan the whole inner rel for an unmatched row; not so cheap.
2517  */
2518  if (has_indexed_join_quals(path))
2519  {
2520  /*
2521  * Successfully-matched outer rows will only require scanning
2522  * inner_scan_frac of the inner relation. In this case, we don't
2523  * need to charge the full inner_run_cost even when that's more
2524  * than inner_rescan_run_cost, because we can assume that none of
2525  * the inner scans ever scan the whole inner relation. So it's
2526  * okay to assume that all the inner scan executions can be
2527  * fractions of the full cost, even if materialization is reducing
2528  * the rescan cost. At this writing, it's impossible to get here
2529  * for a materialized inner scan, so inner_run_cost and
2530  * inner_rescan_run_cost will be the same anyway; but just in
2531  * case, use inner_run_cost for the first matched tuple and
2532  * inner_rescan_run_cost for additional ones.
2533  */
2534  run_cost += inner_run_cost * inner_scan_frac;
2535  if (outer_matched_rows > 1)
2536  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
2537 
2538  /*
2539  * Add the cost of inner-scan executions for unmatched outer rows.
2540  * We estimate this as the same cost as returning the first tuple
2541  * of a nonempty scan. We consider that these are all rescans,
2542  * since we used inner_run_cost once already.
2543  */
2544  run_cost += outer_unmatched_rows *
2545  inner_rescan_run_cost / inner_path_rows;
2546 
2547  /*
2548  * We won't be evaluating any quals at all for unmatched rows, so
2549  * don't add them to ntuples.
2550  */
2551  }
2552  else
2553  {
2554  /*
2555  * Here, a complicating factor is that rescans may be cheaper than
2556  * first scans. If we never scan all the way to the end of the
2557  * inner rel, it might be (depending on the plan type) that we'd
2558  * never pay the whole inner first-scan run cost. However it is
2559  * difficult to estimate whether that will happen (and it could
2560  * not happen if there are any unmatched outer rows!), so be
2561  * conservative and always charge the whole first-scan cost once.
2562  * We consider this charge to correspond to the first unmatched
2563  * outer row, unless there isn't one in our estimate, in which
2564  * case blame it on the first matched row.
2565  */
2566 
2567  /* First, count all unmatched join tuples as being processed */
2568  ntuples += outer_unmatched_rows * inner_path_rows;
2569 
2570  /* Now add the forced full scan, and decrement appropriate count */
2571  run_cost += inner_run_cost;
2572  if (outer_unmatched_rows >= 1)
2573  outer_unmatched_rows -= 1;
2574  else
2575  outer_matched_rows -= 1;
2576 
2577  /* Add inner run cost for additional outer tuples having matches */
2578  if (outer_matched_rows > 0)
2579  run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
2580 
2581  /* Add inner run cost for additional unmatched outer tuples */
2582  if (outer_unmatched_rows > 0)
2583  run_cost += outer_unmatched_rows * inner_rescan_run_cost;
2584  }
2585  }
2586  else
2587  {
2588  /* Normal-case source costs were included in preliminary estimate */
2589 
2590  /* Compute number of tuples processed (not number emitted!) */
2591  ntuples = outer_path_rows * inner_path_rows;
2592  }
2593 
2594  /* CPU costs */
2595  cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
2596  startup_cost += restrict_qual_cost.startup;
2597  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
2598  run_cost += cpu_per_tuple * ntuples;
2599 
2600  /* tlist eval costs are paid per output row, not per tuple scanned */