PostgreSQL Source Code  git master
cost.h File Reference
#include "nodes/pathnodes.h"
#include "nodes/plannodes.h"
Include dependency graph for cost.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define DEFAULT_SEQ_PAGE_COST   1.0
 
#define DEFAULT_RANDOM_PAGE_COST   4.0
 
#define DEFAULT_CPU_TUPLE_COST   0.01
 
#define DEFAULT_CPU_INDEX_TUPLE_COST   0.005
 
#define DEFAULT_CPU_OPERATOR_COST   0.0025
 
#define DEFAULT_PARALLEL_TUPLE_COST   0.1
 
#define DEFAULT_PARALLEL_SETUP_COST   1000.0
 
#define DEFAULT_EFFECTIVE_CACHE_SIZE   524288 /* measured in pages */
 

Enumerations

enum  ConstraintExclusionType { CONSTRAINT_EXCLUSION_OFF, CONSTRAINT_EXCLUSION_ON, CONSTRAINT_EXCLUSION_PARTITION }
 

Functions

double index_pages_fetched (double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
 
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_index (IndexPath *path, PlannerInfo *root, double loop_count, bool partial_path)
 
void cost_bitmap_heap_scan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, Path *bitmapqual, double loop_count)
 
void cost_bitmap_and_node (BitmapAndPath *path, PlannerInfo *root)
 
void cost_bitmap_or_node (BitmapOrPath *path, PlannerInfo *root)
 
void cost_bitmap_tree_node (Path *path, Cost *cost, Selectivity *selec)
 
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_valuesscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_tablefuncscan (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 *path)
 
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_gather (GatherPath *path, PlannerInfo *root, RelOptInfo *baserel, 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_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)
 
double get_parameterized_joinrel_size (PlannerInfo *root, RelOptInfo *rel, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, List *restrict_clauses)
 
void set_joinrel_size_estimates (PlannerInfo *root, RelOptInfo *rel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo, List *restrictlist)
 
void set_subquery_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_function_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_tablefunc_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
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

PGDLLIMPORT Cost disable_cost
 
PGDLLIMPORT int max_parallel_workers_per_gather
 
PGDLLIMPORT bool enable_seqscan
 
PGDLLIMPORT bool enable_indexscan
 
PGDLLIMPORT bool enable_indexonlyscan
 
PGDLLIMPORT bool enable_bitmapscan
 
PGDLLIMPORT bool enable_tidscan
 
PGDLLIMPORT bool enable_sort
 
PGDLLIMPORT bool enable_hashagg
 
PGDLLIMPORT bool enable_nestloop
 
PGDLLIMPORT bool enable_material
 
PGDLLIMPORT bool enable_mergejoin
 
PGDLLIMPORT bool enable_hashjoin
 
PGDLLIMPORT bool enable_gathermerge
 
PGDLLIMPORT bool enable_partitionwise_join
 
PGDLLIMPORT bool enable_partitionwise_aggregate
 
PGDLLIMPORT bool enable_parallel_append
 
PGDLLIMPORT bool enable_parallel_hash
 
PGDLLIMPORT bool enable_partition_pruning
 
PGDLLIMPORT int constraint_exclusion
 

Macro Definition Documentation

◆ DEFAULT_CPU_INDEX_TUPLE_COST

#define DEFAULT_CPU_INDEX_TUPLE_COST   0.005

Definition at line 27 of file cost.h.

◆ DEFAULT_CPU_OPERATOR_COST

#define DEFAULT_CPU_OPERATOR_COST   0.0025

Definition at line 28 of file cost.h.

◆ DEFAULT_CPU_TUPLE_COST

#define DEFAULT_CPU_TUPLE_COST   0.01

Definition at line 26 of file cost.h.

◆ DEFAULT_EFFECTIVE_CACHE_SIZE

#define DEFAULT_EFFECTIVE_CACHE_SIZE   524288 /* measured in pages */

Definition at line 32 of file cost.h.

◆ DEFAULT_PARALLEL_SETUP_COST

#define DEFAULT_PARALLEL_SETUP_COST   1000.0

Definition at line 30 of file cost.h.

◆ DEFAULT_PARALLEL_TUPLE_COST

#define DEFAULT_PARALLEL_TUPLE_COST   0.1

Definition at line 29 of file cost.h.

◆ DEFAULT_RANDOM_PAGE_COST

#define DEFAULT_RANDOM_PAGE_COST   4.0

Definition at line 25 of file cost.h.

◆ DEFAULT_SEQ_PAGE_COST

#define DEFAULT_SEQ_PAGE_COST   1.0

Definition at line 24 of file cost.h.

Enumeration Type Documentation

◆ ConstraintExclusionType

Enumerator
CONSTRAINT_EXCLUSION_OFF 
CONSTRAINT_EXCLUSION_ON 
CONSTRAINT_EXCLUSION_PARTITION 

Definition at line 34 of file cost.h.

35 {
36  CONSTRAINT_EXCLUSION_OFF, /* do not use c_e */
37  CONSTRAINT_EXCLUSION_ON, /* apply c_e to all rels */
38  CONSTRAINT_EXCLUSION_PARTITION /* apply c_e to otherrels only */
ConstraintExclusionType
Definition: cost.h:34

Function Documentation

◆ compute_bitmap_pages()

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

Definition at line 5508 of file costsize.c.

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

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

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

◆ compute_semi_anti_join_factors()

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

Definition at line 4147 of file costsize.c.

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

Referenced by add_paths_to_joinrel().

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

◆ cost_agg()

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

Definition at line 2151 of file costsize.c.

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

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

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

◆ cost_append()

void cost_append ( AppendPath path)

Definition at line 1875 of file costsize.c.

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

Referenced by create_append_path().

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

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1084 of file costsize.c.

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

Referenced by bitmap_and_cost_est(), and create_bitmap_and_path().

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

◆ cost_bitmap_heap_scan()

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

Definition at line 940 of file costsize.c.

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

Referenced by bitmap_and_cost_est(), bitmap_scan_cost_est(), and create_bitmap_heap_path().

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

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1128 of file costsize.c.

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

Referenced by create_bitmap_or_path().

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

◆ cost_bitmap_tree_node()

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

Definition at line 1041 of file costsize.c.

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

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

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

◆ cost_ctescan()

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

Definition at line 1498 of file costsize.c.

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

Referenced by create_ctescan_path(), and create_worktablescan_path().

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

◆ cost_functionscan()

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

Definition at line 1331 of file costsize.c.

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

Referenced by create_functionscan_path().

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

◆ cost_gather()

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

Definition at line 363 of file costsize.c.

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

Referenced by create_gather_path().

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

◆ cost_gather_merge()

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

Definition at line 401 of file costsize.c.

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

Referenced by create_gather_merge_path().

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

◆ cost_group()

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

Definition at line 2346 of file costsize.c.

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

Referenced by choose_hashed_setop(), and create_group_path().

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

◆ cost_index()

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

Definition at line 476 of file costsize.c.

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

Referenced by create_index_path(), and reparameterize_path().

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

◆ cost_material()

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

Definition at line 2097 of file costsize.c.

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

Referenced by create_material_path(), and materialize_finished_plan().

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

◆ cost_merge_append()

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

Definition at line 2048 of file costsize.c.

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

Referenced by create_merge_append_path().

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

◆ cost_namedtuplestorescan()

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

Definition at line 1539 of file costsize.c.

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

Referenced by create_namedtuplestorescan_path().

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

◆ cost_qual_eval()

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

Definition at line 3819 of file costsize.c.

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

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

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

◆ cost_qual_eval_node()

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

Definition at line 3845 of file costsize.c.

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

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

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

◆ cost_recursive_union()

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

Definition at line 1613 of file costsize.c.

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

Referenced by create_recursiveunion_path().

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

◆ cost_resultscan()

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

Definition at line 1576 of file costsize.c.

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

Referenced by create_resultscan_path().

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

◆ cost_samplescan()

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

Definition at line 288 of file costsize.c.

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

Referenced by create_samplescan_path().

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

◆ cost_seqscan()

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

Definition at line 211 of file costsize.c.

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

Referenced by create_seqscan_path().

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

◆ cost_sort()

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

Definition at line 1693 of file costsize.c.

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

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

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

◆ cost_subplan()

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

Definition at line 3619 of file costsize.c.

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

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

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

◆ cost_subqueryscan()

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

Definition at line 1282 of file costsize.c.

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

Referenced by create_subqueryscan_path().

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

◆ cost_tablefuncscan()

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

Definition at line 1392 of file costsize.c.

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

Referenced by create_tablefuncscan_path().

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

◆ cost_tidscan()

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

Definition at line 1176 of file costsize.c.

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

Referenced by create_tidscan_path().

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

◆ cost_valuesscan()

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

Definition at line 1448 of file costsize.c.

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

Referenced by create_valuesscan_path().

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

◆ cost_windowagg()

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

Definition at line 2272 of file costsize.c.

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

Referenced by create_windowagg_path().

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

◆ final_cost_hashjoin()

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

Definition at line 3364 of file costsize.c.

References approx_tuple_count(), Assert, bms_is_subset(), clamp_row_est(), RestrictInfo::clause, PathTarget::cost, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_hashjoin, estimate_hash_bucket_stats(), get_leftop(), get_parallel_divisor(), get_rightop(), HashPath::inner_rows_total, JoinCostWorkspace::inner_rows_total, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, IsA, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, HashPath::jpath, RestrictInfo::left_bucketsize, RestrictInfo::left_mcvfreq, RestrictInfo::left_relids, lfirst_node, SemiAntiJoinFactors::match_count, HashPath::num_batches, JoinCostWorkspace::numbatches, JoinCostWorkspace::numbuckets, SemiAntiJoinFactors::outer_match_frac, JoinPath::outerjoinpath, Path::parallel_workers, Path::param_info, Path::parent, JoinPath::path, HashPath::path_hashclauses, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, relation_byte_size(), RelOptInfo::relids, RestrictInfo::right_bucketsize, RestrictInfo::right_mcvfreq, RestrictInfo::right_relids, rint(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, PathTarget::width, and work_mem.

Referenced by create_hashjoin_path().

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

◆ final_cost_mergejoin()

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

Definition at line 2928 of file costsize.c.

References approx_tuple_count(), clamp_row_est(), PathTarget::cost, cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, disable_cost, enable_material, enable_mergejoin, ExecSupportsMarkRestore(), get_parallel_divisor(), JoinCostWorkspace::inner_rows, JoinCostWorkspace::inner_run_cost, JoinCostWorkspace::inner_skip_rows, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, MergePath::innersortkeys, IsA, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, MergePath::jpath, list_length(), MergePath::materialize_inner, NIL, JoinCostWorkspace::outer_rows, JoinCostWorkspace::outer_skip_rows, JoinPath::outerjoinpath, Path::parallel_workers, Path::param_info, Path::parent, JoinPath::path, MergePath::path_mergeclauses, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, relation_byte_size(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, MergePath::skip_mark_restore, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, PathTarget::width, and work_mem.

Referenced by create_mergejoin_path().

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

◆ final_cost_nestloop()

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

Definition at line 2491 of file costsize.c.

References clamp_row_est(), PathTarget::cost, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_nestloop, get_parallel_divisor(), has_indexed_join_quals(), JoinCostWorkspace::inner_rescan_run_cost, JoinCostWorkspace::inner_run_cost, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, SemiAntiJoinFactors::match_count, SemiAntiJoinFactors::outer_match_frac, JoinPath::outerjoinpath, Path::parallel_workers, Path::param_info, Path::parent, JoinPath::path, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, rint(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, and Path::total_cost.

Referenced by create_nestloop_path().

2494 {
2495  Path *outer_path = path->outerjoinpath;
2496  Path *inner_path = path->innerjoinpath;
2497  double outer_path_rows = outer_path->rows;
2498  double inner_path_rows = inner_path->rows;
2499  Cost startup_cost = workspace->startup_cost;
2500  Cost run_cost = workspace->run_cost;
2501  Cost cpu_per_tuple;
2502  QualCost restrict_qual_cost;
2503  double ntuples;
2504 
2505  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2506  if (outer_path_rows <= 0 || isnan(outer_path_rows))
2507  outer_path_rows = 1;
2508  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2509  inner_path_rows = 1;
2510 
2511  /* Mark the path with the correct row estimate */
2512  if (path->path.param_info)
2513  path->path.rows = path->path.param_info->ppi_rows;
2514  else
2515  path->path.rows = path->path.parent->rows;
2516 
2517  /* For partial paths, scale row estimate. */
2518  if (path->path.parallel_workers > 0)
2519  {
2520  double parallel_divisor = get_parallel_divisor(&path->path);
2521 
2522  path->path.rows =
2523  clamp_row_est(path->path.rows / parallel_divisor);
2524  }
2525 
2526  /*
2527  * We could include disable_cost in the preliminary estimate, but that
2528  * would amount to optimizing for the case where the join method is
2529  * disabled, which doesn't seem like the way to bet.
2530  */
2531  if (!enable_nestloop)
2532  startup_cost += disable_cost;
2533 
2534  /* cost of inner-relation source data (we already dealt with outer rel) */
2535 
2536  if (path->jointype == JOIN_SEMI || path->jointype == JOIN_ANTI ||
2537  extra->inner_unique)
2538  {
2539  /*
2540  * With a SEMI or ANTI join, or if the innerrel is known unique, the
2541  * executor will stop after the first match.
2542  */
2543  Cost inner_run_cost = workspace->inner_run_cost;
2544  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
2545  double outer_matched_rows;
2546  double outer_unmatched_rows;
2547  Selectivity inner_scan_frac;
2548 
2549  /*
2550  * For an outer-rel row that has at least one match, we can expect the
2551  * inner scan to stop after a fraction 1/(match_count+1) of the inner
2552  * rows, if the matches are evenly distributed. Since they probably
2553  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
2554  * that fraction. (If we used a larger fuzz factor, we'd have to
2555  * clamp inner_scan_frac to at most 1.0; but since match_count is at
2556  * least 1, no such clamp is needed now.)
2557  */
2558  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
2559  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
2560  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
2561 
2562  /*
2563  * Compute number of tuples processed (not number emitted!). First,
2564  * account for successfully-matched outer rows.
2565  */
2566  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
2567 
2568  /*
2569  * Now we need to estimate the actual costs of scanning the inner
2570  * relation, which may be quite a bit less than N times inner_run_cost
2571  * due to early scan stops. We consider two cases. If the inner path
2572  * is an indexscan using all the joinquals as indexquals, then an
2573  * unmatched outer row results in an indexscan returning no rows,
2574  * which is probably quite cheap. Otherwise, the executor will have
2575  * to scan the whole inner rel for an unmatched row; not so cheap.
2576  */
2577  if (has_indexed_join_quals(path))
2578  {
2579  /*
2580  * Successfully-matched outer rows will only require scanning
2581  * inner_scan_frac of the inner relation. In this case, we don't
2582  * need to charge the full inner_run_cost even when that's more
2583  * than inner_rescan_run_cost, because we can assume that none of
2584  * the inner scans ever scan the whole inner relation. So it's
2585  * okay to assume that all the inner scan executions can be
2586  * fractions of the full cost, even if materialization is reducing
2587  * the rescan cost. At this writing, it's impossible to get here
2588  * for a materialized inner scan, so inner_run_cost and
2589  * inner_rescan_run_cost will be the same anyway; but just in
2590  * case, use inner_run_cost for the first matched tuple and
2591  * inner_rescan_run_cost for additional ones.
2592  */
2593  run_cost += inner_run_cost * inner_scan_frac;
2594  if (outer_matched_rows > 1)
2595  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
2596 
2597  /*
2598  * Add the cost of inner-scan executions for unmatched outer rows.
2599  * We estimate this as the same cost as returning the first tuple
2600  * of a nonempty scan. We consider that these are all rescans,
2601  * since we used inner_run_cost once already.
2602  */
2603  run_cost += outer_unmatched_rows *
2604  inner_rescan_run_cost / inner_path_rows;
2605 
2606  /*
2607  * We won't be evaluating any quals at all for unmatched rows, so
2608  * don't add them to ntuples.
2609  */
2610  }
2611  else
2612  {
2613  /*
2614  * Here, a complicating factor is that rescans may be cheaper than
2615  * first scans. If we never scan all the way to the end of the
2616  * inner rel, it might be (depending on the plan type) that we'd
2617  * never pay the whole inner first-scan run cost. However it is
2618  * difficult to estimate whether that will happen (and it could
2619  * not happen if there are any unmatched outer rows!), so be
2620  * conservative and always charge the whole first-scan cost once.
2621  * We consider this charge to correspond to the first unmatched
2622  * outer row, unless there isn't one in our estimate, in which
2623  * case blame it on the first matched row.
2624  */
2625 
2626  /* First, count all unmatched join tuples as being processed */
2627  ntuples += outer_unmatched_rows * inner_path_rows;
2628 
2629  /* Now add the forced full scan, and decrement appropriate count */
2630  run_cost += inner_run_cost;
2631  if (outer_unmatched_rows >= 1)
2632  outer_unmatched_rows -= 1;
2633  else
2634  outer_matched_rows -= 1;
2635 
2636  /* Add inner run cost for additional outer tuples having matches */
2637  if (outer_matched_rows > 0)
2638  run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
2639 
2640  /* Add inner run cost for additional unmatched outer tuples */
2641  if (outer_unmatched_rows > 0)
2642  run_cost += outer_unmatched_rows * inner_rescan_run_cost;
2643  }
2644  }
2645  else
2646  {
2647  /* Normal-case source costs were included in preliminary estimate */
2648 
2649  /* Compute number of tuples processed (not number emitted!) */
2650  ntuples = outer_path_rows * inner_path_rows;
2651  }
2652 
2653  /* CPU costs */
2654  cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
2655  startup_cost += restrict_qual_cost.startup;
2656  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
2657  run_cost += cpu_per_tuple * ntuples;
2658 
2659  /* tlist eval costs are paid per output row, not per tuple scanned */
2660  startup_cost += path->path.pathtarget->cost.startup;
2661  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
2662 
2663  path->path.startup_cost = startup_cost;
2664  path->path.total_cost = startup_cost + run_cost;
2665 }
PathTarget * pathtarget
Definition: pathnodes.h:1115
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:2386
bool enable_nestloop
Definition: costsize.c:131
Selectivity outer_match_frac
Definition: pathnodes.h:2363
Path * innerjoinpath
Definition: pathnodes.h:1496
int parallel_workers
Definition: pathnodes.h:1121
ParamPathInfo * param_info
Definition: pathnodes.h:1117
double Selectivity
Definition: nodes.h:658
Cost inner_rescan_run_cost
Definition: pathnodes.h:2496
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3819
Cost startup_cost
Definition: pathnodes.h:1125
Cost disable_cost
Definition: costsize.c:120
List * joinrestrictinfo
Definition: pathnodes.h:1498
RelOptInfo * parent
Definition: pathnodes.h:1114
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5475
double rint(double x)
Definition: rint.c:21
Path * outerjoinpath
Definition: pathnodes.h:1495
double rows
Definition: pathnodes.h:644
Cost total_cost
Definition: pathnodes.h:1126
Path path
Definition: pathnodes.h:1488
static bool has_indexed_join_quals(NestPath *joinpath)
Definition: costsize.c:4256
double rows
Definition: pathnodes.h:1124
QualCost cost
Definition: pathnodes.h:1046
double cpu_tuple_cost
Definition: costsize.c:112
double ppi_rows
Definition: pathnodes.h:1074
Selectivity match_count
Definition: pathnodes.h:2364
JoinType jointype
Definition: pathnodes.h:1490
double clamp_row_est(double nrows)
Definition: costsize.c:187
double Cost
Definition: nodes.h:659

◆ get_parameterized_baserel_size()

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

Definition at line 4434 of file costsize.c.

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

Referenced by get_baserel_parampathinfo().

4436 {
4437  List *allclauses;
4438  double nrows;
4439 
4440  /*
4441  * Estimate the number of rows returned by the parameterized scan, knowing
4442  * that it will apply all the extra join clauses as well as the rel's own
4443  * restriction clauses. Note that we force the clauses to be treated as
4444  * non-join clauses during selectivity estimation.
4445  */
4446  allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
4447  nrows = rel->tuples *
4449  allclauses,
4450  rel->relid, /* do not use 0! */
4451  JOIN_INNER,
4452  NULL);
4453  nrows = clamp_row_est(nrows);
4454  /* For safety, make sure result is not more than the base estimate */
4455  if (nrows > rel->rows)
4456  nrows = rel->rows;
4457  return nrows;
4458 }
double tuples
Definition: pathnodes.h:681
List * baserestrictinfo
Definition: pathnodes.h:703
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:553
Index relid
Definition: pathnodes.h:669
double rows
Definition: pathnodes.h:644
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
double clamp_row_est(double nrows)
Definition: costsize.c:187
Definition: pg_list.h:50

◆ get_parameterized_joinrel_size()

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

Definition at line 4515 of file costsize.c.

References calc_joinrel_size_estimate(), Path::parent, RelOptInfo::rows, and Path::rows.

Referenced by get_joinrel_parampathinfo().

4520 {
4521  double nrows;
4522 
4523  /*
4524  * Estimate the number of rows returned by the parameterized join as the
4525  * sizes of the input paths times the selectivity of the clauses that have
4526  * ended up at this join node.
4527  *
4528  * As with set_joinrel_size_estimates, the rowcount estimate could depend
4529  * on the pair of input paths provided, though ideally we'd get the same
4530  * estimate for any pair with the same parameterization.
4531  */
4532  nrows = calc_joinrel_size_estimate(root,
4533  rel,
4534  outer_path->parent,
4535  inner_path->parent,
4536  outer_path->rows,
4537  inner_path->rows,
4538  sjinfo,
4539  restrict_clauses);
4540  /* For safety, make sure result is not more than the base estimate */
4541  if (nrows > rel->rows)
4542  nrows = rel->rows;
4543  return nrows;
4544 }
RelOptInfo * parent
Definition: pathnodes.h:1114
double rows
Definition: pathnodes.h:644
double rows
Definition: pathnodes.h:1124
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)
Definition: costsize.c:4556

◆ index_pages_fetched()

double index_pages_fetched ( double  tuples_fetched,
BlockNumber  pages,
double  index_pages,
PlannerInfo root 
)

Definition at line 825 of file costsize.c.

References Assert, effective_cache_size, Max, T, and PlannerInfo::total_table_pages.

Referenced by compute_bitmap_pages(), cost_index(), genericcostestimate(), and gincostestimate().

827 {
828  double pages_fetched;
829  double total_pages;
830  double T,
831  b;
832 
833  /* T is # pages in table, but don't allow it to be zero */
834  T = (pages > 1) ? (double) pages : 1.0;
835 
836  /* Compute number of pages assumed to be competing for cache space */
837  total_pages = root->total_table_pages + index_pages;
838  total_pages = Max(total_pages, 1.0);
839  Assert(T <= total_pages);
840 
841  /* b is pro-rated share of effective_cache_size */
842  b = (double) effective_cache_size * T / total_pages;
843 
844  /* force it positive and integral */
845  if (b <= 1.0)
846  b = 1.0;
847  else
848  b = ceil(b);
849 
850  /* This part is the Mackert and Lohman formula */
851  if (T <= b)
852  {
853  pages_fetched =
854  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
855  if (pages_fetched >= T)
856  pages_fetched = T;
857  else
858  pages_fetched = ceil(pages_fetched);
859  }
860  else
861  {
862  double lim;
863 
864  lim = (2.0 * T * b) / (2.0 * T - b);
865  if (tuples_fetched <= lim)
866  {
867  pages_fetched =
868  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
869  }
870  else
871  {
872  pages_fetched =
873  b + (tuples_fetched - lim) * (T - b) / T;
874  }
875  pages_fetched = ceil(pages_fetched);
876  }
877  return pages_fetched;
878 }
int effective_cache_size
Definition: costsize.c:118
static const uint32 T[65]
Definition: md5.c:101
double total_table_pages
Definition: pathnodes.h:331
#define Max(x, y)
Definition: c.h:905
#define Assert(condition)
Definition: c.h:739

◆ initial_cost_hashjoin()

void initial_cost_hashjoin ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
List hashclauses,
Path outer_path,
Path inner_path,
JoinPathExtraData extra,
bool  parallel_hash 
)

Definition at line 3256 of file costsize.c.

References cpu_operator_cost, cpu_tuple_cost, ExecChooseHashTableSize(), get_parallel_divisor(), JoinCostWorkspace::inner_rows_total, list_length(), JoinCostWorkspace::numbatches, JoinCostWorkspace::numbuckets, page_size(), Path::parallel_workers, Path::pathtarget, Path::rows, JoinCostWorkspace::run_cost, seq_page_cost, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, JoinCostWorkspace::total_cost, and PathTarget::width.

Referenced by try_hashjoin_path(), and try_partial_hashjoin_path().

3262 {
3263  Cost startup_cost = 0;
3264  Cost run_cost = 0;
3265  double outer_path_rows = outer_path->rows;
3266  double inner_path_rows = inner_path->rows;
3267  double inner_path_rows_total = inner_path_rows;
3268  int num_hashclauses = list_length(hashclauses);
3269  int numbuckets;
3270  int numbatches;
3271  int num_skew_mcvs;
3272  size_t space_allowed; /* unused */
3273 
3274  /* cost of source data */
3275  startup_cost += outer_path->startup_cost;
3276  run_cost += outer_path->total_cost - outer_path->startup_cost;
3277  startup_cost += inner_path->total_cost;
3278 
3279  /*
3280  * Cost of computing hash function: must do it once per input tuple. We
3281  * charge one cpu_operator_cost for each column's hash function. Also,
3282  * tack on one cpu_tuple_cost per inner row, to model the costs of
3283  * inserting the row into the hashtable.
3284  *
3285  * XXX when a hashclause is more complex than a single operator, we really
3286  * should charge the extra eval costs of the left or right side, as
3287  * appropriate, here. This seems more work than it's worth at the moment.
3288  */
3289  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
3290  * inner_path_rows;
3291  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
3292 
3293  /*
3294  * If this is a parallel hash build, then the value we have for
3295  * inner_rows_total currently refers only to the rows returned by each
3296  * participant. For shared hash table size estimation, we need the total
3297  * number, so we need to undo the division.
3298  */
3299  if (parallel_hash)
3300  inner_path_rows_total *= get_parallel_divisor(inner_path);
3301 
3302  /*
3303  * Get hash table size that executor would use for inner relation.
3304  *
3305  * XXX for the moment, always assume that skew optimization will be
3306  * performed. As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
3307  * trying to determine that for sure.
3308  *
3309  * XXX at some point it might be interesting to try to account for skew
3310  * optimization in the cost estimate, but for now, we don't.
3311  */
3312  ExecChooseHashTableSize(inner_path_rows_total,
3313  inner_path->pathtarget->width,
3314  true, /* useskew */
3315  parallel_hash, /* try_combined_work_mem */
3316  outer_path->parallel_workers,
3317  &space_allowed,
3318  &numbuckets,
3319  &numbatches,
3320  &num_skew_mcvs);
3321 
3322  /*
3323  * If inner relation is too big then we will need to "batch" the join,
3324  * which implies writing and reading most of the tuples to disk an extra
3325  * time. Charge seq_page_cost per page, since the I/O should be nice and
3326  * sequential. Writing the inner rel counts as startup cost, all the rest
3327  * as run cost.
3328  */
3329  if (numbatches > 1)
3330  {
3331  double outerpages = page_size(outer_path_rows,
3332  outer_path->pathtarget->width);
3333  double innerpages = page_size(inner_path_rows,
3334  inner_path->pathtarget->width);
3335 
3336  startup_cost += seq_page_cost * innerpages;
3337  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
3338  }
3339 
3340  /* CPU costs left for later */
3341 
3342  /* Public result fields */
3343  workspace->startup_cost = startup_cost;
3344  workspace->total_cost = startup_cost + run_cost;
3345  /* Save private data for final_cost_hashjoin */
3346  workspace->run_cost = run_cost;
3347  workspace->numbuckets = numbuckets;
3348  workspace->numbatches = numbatches;
3349  workspace->inner_rows_total = inner_path_rows_total;
3350 }
PathTarget * pathtarget
Definition: pathnodes.h:1115
int parallel_workers
Definition: pathnodes.h:1121
static double page_size(double tuples, int width)
Definition: costsize.c:5465
Cost startup_cost
Definition: pathnodes.h:1125
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5475
double cpu_operator_cost
Definition: costsize.c:114
double inner_rows_total
Definition: pathnodes.h:2507
Cost total_cost
Definition: pathnodes.h:1126
double rows
Definition: pathnodes.h:1124
static int list_length(const List *l)
Definition: pg_list.h:169
double cpu_tuple_cost
Definition: costsize.c:112
double seq_page_cost
Definition: costsize.c:110
void ExecChooseHashTableSize(double ntuples, int tupwidth, bool useskew, bool try_combined_work_mem, int parallel_workers, size_t *space_allowed, int *numbuckets, int *numbatches, int *num_skew_mcvs)
Definition: nodeHash.c:666
double Cost
Definition: nodes.h:659

◆ initial_cost_mergejoin()

void initial_cost_mergejoin ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
List mergeclauses,
Path outer_path,
Path inner_path,
List outersortkeys,
List innersortkeys,
JoinPathExtraData extra 
)

Definition at line 2698 of file costsize.c.

References Assert, bms_is_subset(), cached_scansel(), clamp_row_est(), cost_sort(), EquivalenceClass::ec_collation, elog, ERROR, JoinCostWorkspace::inner_rows, JoinCostWorkspace::inner_run_cost, JoinCostWorkspace::inner_skip_rows, JOIN_ANTI, JOIN_FULL, JOIN_LEFT, JOIN_RIGHT, RestrictInfo::left_relids, MergeScanSelCache::leftendsel, MergeScanSelCache::leftstartsel, linitial, JoinCostWorkspace::outer_rows, JoinCostWorkspace::outer_skip_rows, Path::parent, Path::pathkeys, Path::pathtarget, PathKey::pk_eclass, PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, RelOptInfo::relids, MergeScanSelCache::rightendsel, MergeScanSelCache::rightstartsel, rint(), Path::rows, JoinCostWorkspace::run_cost, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, JoinCostWorkspace::total_cost, PathTarget::width, and work_mem.

Referenced by try_mergejoin_path(), and try_partial_mergejoin_path().

2704 {
2705  Cost startup_cost = 0;
2706  Cost run_cost = 0;
2707  double outer_path_rows = outer_path->rows;
2708  double inner_path_rows = inner_path->rows;
2709  Cost inner_run_cost;
2710  double outer_rows,
2711  inner_rows,
2712  outer_skip_rows,
2713  inner_skip_rows;
2714  Selectivity outerstartsel,
2715  outerendsel,
2716  innerstartsel,
2717  innerendsel;
2718  Path sort_path; /* dummy for result of cost_sort */
2719 
2720  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2721  if (outer_path_rows <= 0 || isnan(outer_path_rows))
2722  outer_path_rows = 1;
2723  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2724  inner_path_rows = 1;
2725 
2726  /*
2727  * A merge join will stop as soon as it exhausts either input stream
2728  * (unless it's an outer join, in which case the outer side has to be
2729  * scanned all the way anyway). Estimate fraction of the left and right
2730  * inputs that will actually need to be scanned. Likewise, we can
2731  * estimate the number of rows that will be skipped before the first join
2732  * pair is found, which should be factored into startup cost. We use only
2733  * the first (most significant) merge clause for this purpose. Since
2734  * mergejoinscansel() is a fairly expensive computation, we cache the
2735  * results in the merge clause RestrictInfo.
2736  */
2737  if (mergeclauses && jointype != JOIN_FULL)
2738  {
2739  RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
2740  List *opathkeys;
2741  List *ipathkeys;
2742  PathKey *opathkey;
2743  PathKey *ipathkey;
2744  MergeScanSelCache *cache;
2745 
2746  /* Get the input pathkeys to determine the sort-order details */
2747  opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
2748  ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
2749  Assert(opathkeys);
2750  Assert(ipathkeys);
2751  opathkey = (PathKey *) linitial(opathkeys);
2752  ipathkey = (PathKey *) linitial(ipathkeys);
2753  /* debugging check */
2754  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
2755  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
2756  opathkey->pk_strategy != ipathkey->pk_strategy ||
2757  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
2758  elog(ERROR, "left and right pathkeys do not match in mergejoin");
2759 
2760  /* Get the selectivity with caching */
2761  cache = cached_scansel(root, firstclause, opathkey);
2762 
2763  if (bms_is_subset(firstclause->left_relids,
2764  outer_path->parent->relids))
2765  {
2766  /* left side of clause is outer */
2767  outerstartsel = cache->leftstartsel;
2768  outerendsel = cache->leftendsel;
2769  innerstartsel = cache->rightstartsel;
2770  innerendsel = cache->rightendsel;
2771  }
2772  else
2773  {
2774  /* left side of clause is inner */
2775  outerstartsel = cache->rightstartsel;
2776  outerendsel = cache->rightendsel;
2777  innerstartsel = cache->leftstartsel;
2778  innerendsel = cache->leftendsel;
2779  }
2780  if (jointype == JOIN_LEFT ||
2781  jointype == JOIN_ANTI)
2782  {
2783  outerstartsel = 0.0;
2784  outerendsel = 1.0;
2785  }
2786  else if (jointype == JOIN_RIGHT)
2787  {
2788  innerstartsel = 0.0;
2789  innerendsel = 1.0;
2790  }
2791  }
2792  else
2793  {
2794  /* cope with clauseless or full mergejoin */
2795  outerstartsel = innerstartsel = 0.0;
2796  outerendsel = innerendsel = 1.0;
2797  }
2798 
2799  /*
2800  * Convert selectivities to row counts. We force outer_rows and
2801  * inner_rows to be at least 1, but the skip_rows estimates can be zero.
2802  */
2803  outer_skip_rows = rint(outer_path_rows * outerstartsel);
2804  inner_skip_rows = rint(inner_path_rows * innerstartsel);
2805  outer_rows = clamp_row_est(outer_path_rows * outerendsel);
2806  inner_rows = clamp_row_est(inner_path_rows * innerendsel);
2807 
2808  Assert(outer_skip_rows <= outer_rows);
2809  Assert(inner_skip_rows <= inner_rows);
2810 
2811  /*
2812  * Readjust scan selectivities to account for above rounding. This is
2813  * normally an insignificant effect, but when there are only a few rows in
2814  * the inputs, failing to do this makes for a large percentage error.
2815  */
2816  outerstartsel = outer_skip_rows / outer_path_rows;
2817  innerstartsel = inner_skip_rows / inner_path_rows;
2818  outerendsel = outer_rows / outer_path_rows;
2819  innerendsel = inner_rows / inner_path_rows;
2820 
2821  Assert(outerstartsel <= outerendsel);
2822  Assert(innerstartsel <= innerendsel);
2823 
2824  /* cost of source data */
2825 
2826  if (outersortkeys) /* do we need to sort outer? */
2827  {
2828  cost_sort(&sort_path,
2829  root,
2830  outersortkeys,
2831  outer_path->total_cost,
2832  outer_path_rows,
2833  outer_path->pathtarget->width,
2834  0.0,
2835  work_mem,
2836  -1.0);
2837  startup_cost += sort_path.startup_cost;
2838  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
2839  * outerstartsel;
2840  run_cost += (sort_path.total_cost - sort_path.startup_cost)
2841  * (outerendsel - outerstartsel);
2842  }
2843  else
2844  {
2845  startup_cost += outer_path->startup_cost;
2846  startup_cost += (outer_path->total_cost - outer_path->startup_cost)
2847  * outerstartsel;
2848  run_cost += (outer_path->total_cost - outer_path->startup_cost)
2849  * (outerendsel - outerstartsel);
2850  }
2851 
2852  if (innersortkeys) /* do we need to sort inner? */
2853  {
2854  cost_sort(&sort_path,
2855  root,
2856  innersortkeys,
2857  inner_path->total_cost,
2858  inner_path_rows,
2859  inner_path->pathtarget->width,
2860  0.0,
2861  work_mem,
2862  -1.0);
2863  startup_cost += sort_path.startup_cost;
2864  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
2865  * innerstartsel;
2866  inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
2867  * (innerendsel - innerstartsel);
2868  }
2869  else
2870  {
2871  startup_cost += inner_path->startup_cost;
2872  startup_cost += (inner_path->total_cost - inner_path->startup_cost)
2873  * innerstartsel;
2874  inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
2875  * (innerendsel - innerstartsel);
2876  }
2877 
2878  /*
2879  * We can't yet determine whether rescanning occurs, or whether
2880  * materialization of the inner input should be done. The minimum
2881  * possible inner input cost, regardless of rescan and materialization
2882  * considerations, is inner_run_cost. We include that in
2883  * workspace->total_cost, but not yet in run_cost.
2884  */
2885 
2886  /* CPU costs left for later */
2887 
2888  /* Public result fields */
2889  workspace->startup_cost = startup_cost;
2890  workspace->total_cost = startup_cost + run_cost + inner_run_cost;
2891  /* Save private data for final_cost_mergejoin */
2892  workspace->run_cost = run_cost;
2893  workspace->inner_run_cost = inner_run_cost;
2894  workspace->outer_rows = outer_rows;
2895  workspace->inner_rows = inner_rows;
2896  workspace->outer_skip_rows = outer_skip_rows;
2897  workspace->inner_skip_rows = inner_skip_rows;
2898 }
Selectivity leftendsel
Definition: pathnodes.h:2040
PathTarget * pathtarget
Definition: pathnodes.h:1115
static MergeScanSelCache * cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
Definition: costsize.c:3177
Relids left_relids
Definition: pathnodes.h:1970
double Selectivity
Definition: nodes.h:658
int pk_strategy
Definition: pathnodes.h:1013
#define linitial(l)
Definition: pg_list.h:195
bool pk_nulls_first
Definition: pathnodes.h:1014
#define ERROR
Definition: elog.h:43
Cost startup_cost
Definition: pathnodes.h:1125
RelOptInfo * parent
Definition: pathnodes.h:1114
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
Selectivity rightstartsel
Definition: pathnodes.h:2041
Relids relids
Definition: pathnodes.h:641
double rint(double x)
Definition: rint.c:21
void cost_sort(Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:1693
int work_mem
Definition: globals.c:121
Cost total_cost
Definition: pathnodes.h:1126
double outer_skip_rows
Definition: pathnodes.h:2501
List * pathkeys
Definition: pathnodes.h:1128
#define Assert(condition)
Definition: c.h:739
double rows
Definition: pathnodes.h:1124
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1011
Oid pk_opfamily
Definition: pathnodes.h:1012
#define elog(elevel,...)
Definition: elog.h:228
double inner_skip_rows
Definition: pathnodes.h:2502
double clamp_row_est(double nrows)
Definition: costsize.c:187
Definition: pg_list.h:50
Selectivity rightendsel
Definition: pathnodes.h:2042
double Cost
Definition: nodes.h:659
Selectivity leftstartsel
Definition: pathnodes.h:2039

◆ initial_cost_nestloop()

void initial_cost_nestloop ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
Path outer_path,
Path inner_path,
JoinPathExtraData extra 
)

Definition at line 2416 of file costsize.c.

References cost_rescan(), JoinCostWorkspace::inner_rescan_run_cost, JoinCostWorkspace::inner_run_cost, JoinPathExtraData::inner_unique, JOIN_ANTI, JOIN_SEMI, Path::rows, JoinCostWorkspace::run_cost, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, and JoinCostWorkspace::total_cost.

Referenced by try_nestloop_path(), and try_partial_nestloop_path().

2420 {
2421  Cost startup_cost = 0;
2422  Cost run_cost = 0;
2423  double outer_path_rows = outer_path->rows;
2424  Cost inner_rescan_start_cost;
2425  Cost inner_rescan_total_cost;
2426  Cost inner_run_cost;
2427  Cost inner_rescan_run_cost;
2428 
2429  /* estimate costs to rescan the inner relation */
2430  cost_rescan(root, inner_path,
2431  &inner_rescan_start_cost,
2432  &inner_rescan_total_cost);
2433 
2434  /* cost of source data */
2435 
2436  /*
2437  * NOTE: clearly, we must pay both outer and inner paths' startup_cost
2438  * before we can start returning tuples, so the join's startup cost is
2439  * their sum. We'll also pay the inner path's rescan startup cost
2440  * multiple times.
2441  */
2442  startup_cost += outer_path->startup_cost + inner_path->startup_cost;
2443  run_cost += outer_path->total_cost - outer_path->startup_cost;
2444  if (outer_path_rows > 1)
2445  run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
2446 
2447  inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
2448  inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
2449 
2450  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
2451  extra->inner_unique)
2452  {
2453  /*
2454  * With a SEMI or ANTI join, or if the innerrel is known unique, the
2455  * executor will stop after the first match.
2456  *
2457  * Getting decent estimates requires inspection of the join quals,
2458  * which we choose to postpone to final_cost_nestloop.
2459  */
2460 
2461  /* Save private data for final_cost_nestloop */
2462  workspace->inner_run_cost = inner_run_cost;
2463  workspace->inner_rescan_run_cost = inner_rescan_run_cost;
2464  }
2465  else
2466  {
2467  /* Normal case; we'll scan whole input rel for each outer row */
2468  run_cost += inner_run_cost;
2469  if (outer_path_rows > 1)
2470  run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
2471  }
2472 
2473  /* CPU costs left for later */
2474 
2475  /* Public result fields */
2476  workspace->startup_cost = startup_cost;
2477  workspace->total_cost = startup_cost + run_cost;
2478  /* Save private data for final_cost_nestloop */
2479  workspace->run_cost = run_cost;
2480 }
static void cost_rescan(PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:3712
Cost inner_rescan_run_cost
Definition: pathnodes.h:2496
Cost startup_cost
Definition: pathnodes.h:1125
Cost total_cost
Definition: pathnodes.h:1126
double rows
Definition: pathnodes.h:1124
double Cost
Definition: nodes.h:659

◆ set_baserel_size_estimates()

void set_baserel_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 4404 of file costsize.c.

References Assert, RelOptInfo::baserestrictcost, RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), JOIN_INNER, RelOptInfo::relid, RelOptInfo::rows, set_rel_width(), and RelOptInfo::tuples.

Referenced by postgresGetForeignRelSize(), set_cte_size_estimates(), set_function_size_estimates(), set_namedtuplestore_size_estimates(), set_plain_rel_size(), set_result_size_estimates(), set_subquery_size_estimates(), set_tablefunc_size_estimates(), set_tablesample_rel_size(), and set_values_size_estimates().

4405 {
4406  double nrows;
4407 
4408  /* Should only be applied to base relations */
4409  Assert(rel->relid > 0);
4410 
4411  nrows = rel->tuples *
4413  rel->baserestrictinfo,
4414  0,
4415  JOIN_INNER,
4416  NULL);
4417 
4418  rel->rows = clamp_row_est(nrows);
4419 
4421 
4422  set_rel_width(root, rel);
4423 }
double tuples
Definition: pathnodes.h:681
List * baserestrictinfo
Definition: pathnodes.h:703
static void set_rel_width(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5218
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3819
Index relid
Definition: pathnodes.h:669
double rows
Definition: pathnodes.h:644
#define Assert(condition)
Definition: c.h:739
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
double clamp_row_est(double nrows)
Definition: costsize.c:187
QualCost baserestrictcost
Definition: pathnodes.h:704

◆ set_cte_size_estimates()

void set_cte_size_estimates ( PlannerInfo root,
RelOptInfo rel,
double  cte_rows 
)

Definition at line 5084 of file costsize.c.

References Assert, planner_rt_fetch, RelOptInfo::relid, RTE_CTE, RangeTblEntry::rtekind, RangeTblEntry::self_reference, set_baserel_size_estimates(), and RelOptInfo::tuples.

Referenced by set_cte_pathlist(), and set_worktable_pathlist().

5085 {
5086  RangeTblEntry *rte;
5087 
5088  /* Should only be applied to base relations that are CTE references */
5089  Assert(rel->relid > 0);
5090  rte = planner_rt_fetch(rel->relid, root);
5091  Assert(rte->rtekind == RTE_CTE);
5092 
5093  if (rte->self_reference)
5094  {
5095  /*
5096  * In a self-reference, arbitrarily assume the average worktable size
5097  * is about 10 times the nonrecursive term's size.
5098  */
5099  rel->tuples = 10 * cte_rows;
5100  }
5101  else
5102  {
5103  /* Otherwise just believe the CTE's rowcount estimate */
5104  rel->tuples = cte_rows;
5105  }
5106 
5107  /* Now estimate number of output rows, etc */
5108  set_baserel_size_estimates(root, rel);
5109 }
double tuples
Definition: pathnodes.h:681
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:371
Index relid
Definition: pathnodes.h:669
bool self_reference
Definition: parsenodes.h:1058
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4404
#define Assert(condition)
Definition: c.h:739
RTEKind rtekind
Definition: parsenodes.h:974

◆ set_foreign_size_estimates()

void set_foreign_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5183 of file costsize.c.

References Assert, RelOptInfo::baserestrictcost, RelOptInfo::baserestrictinfo, cost_qual_eval(), RelOptInfo::relid, RelOptInfo::rows, and set_rel_width().

Referenced by set_foreign_size().

5184 {
5185  /* Should only be applied to base relations */
5186  Assert(rel->relid > 0);
5187 
5188  rel->rows = 1000; /* entirely bogus default estimate */
5189 
5191 
5192  set_rel_width(root, rel);
5193 }
List * baserestrictinfo
Definition: pathnodes.h:703
static void set_rel_width(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5218
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3819
Index relid
Definition: pathnodes.h:669
double rows
Definition: pathnodes.h:644
#define Assert(condition)
Definition: c.h:739
QualCost baserestrictcost
Definition: pathnodes.h:704

◆ set_function_size_estimates()

void set_function_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 4992 of file costsize.c.

References Assert, expression_returns_set_rows(), RangeTblFunction::funcexpr, RangeTblEntry::functions, lfirst, planner_rt_fetch, RelOptInfo::relid, RTE_FUNCTION, RangeTblEntry::rtekind, set_baserel_size_estimates(), and RelOptInfo::tuples.

Referenced by set_rel_size().

4993 {
4994  RangeTblEntry *rte;
4995  ListCell *lc;
4996 
4997  /* Should only be applied to base relations that are functions */
4998  Assert(rel->relid > 0);
4999  rte = planner_rt_fetch(rel->relid, root);
5000  Assert(rte->rtekind == RTE_FUNCTION);
5001 
5002  /*
5003  * Estimate number of rows the functions will return. The rowcount of the
5004  * node is that of the largest function result.
5005  */
5006  rel->tuples = 0;
5007  foreach(lc, rte->functions)
5008  {
5009  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
5010  double ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
5011 
5012  if (ntup > rel->tuples)
5013  rel->tuples = ntup;
5014  }
5015 
5016  /* Now estimate number of output rows, etc */
5017  set_baserel_size_estimates(root, rel);
5018 }
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition: clauses.c:569
double tuples
Definition: pathnodes.h:681
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:371
Index relid
Definition: pathnodes.h:669
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4404
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
List * functions
Definition: parsenodes.h:1040
RTEKind rtekind
Definition: parsenodes.h:974

◆ set_joinrel_size_estimates()

void set_joinrel_size_estimates ( PlannerInfo root,
RelOptInfo rel,
RelOptInfo outer_rel,
RelOptInfo inner_rel,
SpecialJoinInfo sjinfo,
List restrictlist 
)

Definition at line 4483 of file costsize.c.

References calc_joinrel_size_estimate(), and RelOptInfo::rows.

Referenced by build_child_join_rel(), and build_join_rel().

4488 {
4489  rel->rows = calc_joinrel_size_estimate(root,
4490  rel,
4491  outer_rel,
4492  inner_rel,
4493  outer_rel->rows,
4494  inner_rel->rows,
4495  sjinfo,
4496  restrictlist);
4497 }
double rows
Definition: pathnodes.h:644
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)
Definition: costsize.c:4556

◆ set_namedtuplestore_size_estimates()

void set_namedtuplestore_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5121 of file costsize.c.

References Assert, RangeTblEntry::enrtuples, planner_rt_fetch, RelOptInfo::relid, RTE_NAMEDTUPLESTORE, RangeTblEntry::rtekind, set_baserel_size_estimates(), and RelOptInfo::tuples.

Referenced by set_namedtuplestore_pathlist().

5122 {
5123  RangeTblEntry *rte;
5124 
5125  /* Should only be applied to base relations that are tuplestore references */
5126  Assert(rel->relid > 0);
5127  rte = planner_rt_fetch(rel->relid, root);
5129 
5130  /*
5131  * Use the estimate provided by the code which is generating the named
5132  * tuplestore. In some cases, the actual number might be available; in
5133  * others the same plan will be re-used, so a "typical" value might be
5134  * estimated and used.
5135  */
5136  rel->tuples = rte->enrtuples;
5137  if (rel->tuples < 0)
5138  rel->tuples = 1000;
5139 
5140  /* Now estimate number of output rows, etc */
5141  set_baserel_size_estimates(root, rel);
5142 }
double tuples
Definition: pathnodes.h:681
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:371
Index relid
Definition: pathnodes.h:669
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4404
#define Assert(condition)
Definition: c.h:739
RTEKind rtekind
Definition: parsenodes.h:974
double enrtuples
Definition: parsenodes.h:1086

◆ set_pathtarget_cost_width()