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_incremental_sort (Path *path, PlannerInfo *root, List *pathkeys, int presorted_keys, Cost input_startup_cost, Cost input_total_cost, double input_tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_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, double input_width)
 
void cost_windowagg (Path *path, PlannerInfo *root, List *windowFuncs, int numPartCols, int numOrderCols, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_group (Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void initial_cost_nestloop (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, Path *outer_path, Path *inner_path, JoinPathExtraData *extra)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, JoinPathExtraData *extra)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, JoinPathExtraData *extra, bool parallel_hash)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void cost_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_incremental_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 5732 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().

5734 {
5735  Cost indexTotalCost;
5736  Selectivity indexSelectivity;
5737  double T;
5738  double pages_fetched;
5739  double tuples_fetched;
5740  double heap_pages;
5741  long maxentries;
5742 
5743  /*
5744  * Fetch total cost of obtaining the bitmap, as well as its total
5745  * selectivity.
5746  */
5747  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
5748 
5749  /*
5750  * Estimate number of main-table pages fetched.
5751  */
5752  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
5753 
5754  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
5755 
5756  /*
5757  * For a single scan, the number of heap pages that need to be fetched is
5758  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
5759  * re-reads needed).
5760  */
5761  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
5762 
5763  /*
5764  * Calculate the number of pages fetched from the heap. Then based on
5765  * current work_mem estimate get the estimated maxentries in the bitmap.
5766  * (Note that we always do this calculation based on the number of pages
5767  * that would be fetched in a single iteration, even if loop_count > 1.
5768  * That's correct, because only that number of entries will be stored in
5769  * the bitmap at one time.)
5770  */
5771  heap_pages = Min(pages_fetched, baserel->pages);
5772  maxentries = tbm_calculate_entries(work_mem * 1024L);
5773 
5774  if (loop_count > 1)
5775  {
5776  /*
5777  * For repeated bitmap scans, scale up the number of tuples fetched in
5778  * the Mackert and Lohman formula by the number of scans, so that we
5779  * estimate the number of pages fetched by all the scans. Then
5780  * pro-rate for one scan.
5781  */
5782  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
5783  baserel->pages,
5784  get_indexpath_pages(bitmapqual),
5785  root);
5786  pages_fetched /= loop_count;
5787  }
5788 
5789  if (pages_fetched >= T)
5790  pages_fetched = T;
5791  else
5792  pages_fetched = ceil(pages_fetched);
5793 
5794  if (maxentries < heap_pages)
5795  {
5796  double exact_pages;
5797  double lossy_pages;
5798 
5799  /*
5800  * Crude approximation of the number of lossy pages. Because of the
5801  * way tbm_lossify() is coded, the number of lossy pages increases
5802  * very sharply as soon as we run short of memory; this formula has
5803  * that property and seems to perform adequately in testing, but it's
5804  * possible we could do better somehow.
5805  */
5806  lossy_pages = Max(0, heap_pages - maxentries / 2);
5807  exact_pages = heap_pages - lossy_pages;
5808 
5809  /*
5810  * If there are lossy pages then recompute the number of tuples
5811  * processed by the bitmap heap node. We assume here that the chance
5812  * of a given tuple coming from an exact page is the same as the
5813  * chance that a given page is exact. This might not be true, but
5814  * it's not clear how we can do any better.
5815  */
5816  if (lossy_pages > 0)
5817  tuples_fetched =
5818  clamp_row_est(indexSelectivity *
5819  (exact_pages / heap_pages) * baserel->tuples +
5820  (lossy_pages / heap_pages) * baserel->tuples);
5821  }
5822 
5823  if (cost)
5824  *cost = indexTotalCost;
5825  if (tuple)
5826  *tuple = tuples_fetched;
5827 
5828  return pages_fetched;
5829 }
double tuples
Definition: pathnodes.h:705
#define Min(x, y)
Definition: c.h:927
double Selectivity
Definition: nodes.h:662
static const uint32 T[65]
Definition: md5.c:101
int work_mem
Definition: globals.c:121
#define Max(x, y)
Definition: c.h:921
BlockNumber pages
Definition: pathnodes.h:704
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:892
long tbm_calculate_entries(double maxbytes)
Definition: tidbitmap.c:1545
double clamp_row_est(double nrows)
Definition: costsize.c:189
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:827
double Cost
Definition: nodes.h:663
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1043

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

4379 {
4380  Selectivity jselec;
4381  Selectivity nselec;
4382  Selectivity avgmatch;
4383  SpecialJoinInfo norm_sjinfo;
4384  List *joinquals;
4385  ListCell *l;
4386 
4387  /*
4388  * In an ANTI join, we must ignore clauses that are "pushed down", since
4389  * those won't affect the match logic. In a SEMI join, we do not
4390  * distinguish joinquals from "pushed down" quals, so just use the whole
4391  * restrictinfo list. For other outer join types, we should consider only
4392  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
4393  */
4394  if (IS_OUTER_JOIN(jointype))
4395  {
4396  joinquals = NIL;
4397  foreach(l, restrictlist)
4398  {
4399  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4400 
4401  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
4402  joinquals = lappend(joinquals, rinfo);
4403  }
4404  }
4405  else
4406  joinquals = restrictlist;
4407 
4408  /*
4409  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
4410  */
4411  jselec = clauselist_selectivity(root,
4412  joinquals,
4413  0,
4414  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
4415  sjinfo);
4416 
4417  /*
4418  * Also get the normal inner-join selectivity of the join clauses.
4419  */
4420  norm_sjinfo.type = T_SpecialJoinInfo;
4421  norm_sjinfo.min_lefthand = outerrel->relids;
4422  norm_sjinfo.min_righthand = innerrel->relids;
4423  norm_sjinfo.syn_lefthand = outerrel->relids;
4424  norm_sjinfo.syn_righthand = innerrel->relids;
4425  norm_sjinfo.jointype = JOIN_INNER;
4426  /* we don't bother trying to make the remaining fields valid */
4427  norm_sjinfo.lhs_strict = false;
4428  norm_sjinfo.delay_upper_joins = false;
4429  norm_sjinfo.semi_can_btree = false;
4430  norm_sjinfo.semi_can_hash = false;
4431  norm_sjinfo.semi_operators = NIL;
4432  norm_sjinfo.semi_rhs_exprs = NIL;
4433 
4434  nselec = clauselist_selectivity(root,
4435  joinquals,
4436  0,
4437  JOIN_INNER,
4438  &norm_sjinfo);
4439 
4440  /* Avoid leaking a lot of ListCells */
4441  if (IS_OUTER_JOIN(jointype))
4442  list_free(joinquals);
4443 
4444  /*
4445  * jselec can be interpreted as the fraction of outer-rel rows that have
4446  * any matches (this is true for both SEMI and ANTI cases). And nselec is
4447  * the fraction of the Cartesian product that matches. So, the average
4448  * number of matches for each outer-rel row that has at least one match is
4449  * nselec * inner_rows / jselec.
4450  *
4451  * Note: it is correct to use the inner rel's "rows" count here, even
4452  * though we might later be considering a parameterized inner path with
4453  * fewer rows. This is because we have included all the join clauses in
4454  * the selectivity estimate.
4455  */
4456  if (jselec > 0) /* protect against zero divide */
4457  {
4458  avgmatch = nselec * innerrel->rows / jselec;
4459  /* Clamp to sane range */
4460  avgmatch = Max(1.0, avgmatch);
4461  }
4462  else
4463  avgmatch = 1.0;
4464 
4465  semifactors->outer_match_frac = jselec;
4466  semifactors->match_count = avgmatch;
4467 }
#define NIL
Definition: pg_list.h:65
Relids min_righthand
Definition: pathnodes.h:2176
Selectivity outer_match_frac
Definition: pathnodes.h:2405
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:745
double Selectivity
Definition: nodes.h:662
Relids syn_lefthand
Definition: pathnodes.h:2177
Relids syn_righthand
Definition: pathnodes.h:2178
List * semi_rhs_exprs
Definition: pathnodes.h:2186
#define lfirst_node(type, lc)
Definition: pg_list.h:193
Relids relids
Definition: pathnodes.h:665
List * lappend(List *list, void *datum)
Definition: list.c:321
bool delay_upper_joins
Definition: pathnodes.h:2181
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2062
double rows
Definition: pathnodes.h:668
#define Max(x, y)
Definition: c.h:921
JoinType jointype
Definition: pathnodes.h:2179
Selectivity match_count
Definition: pathnodes.h:2406
List * semi_operators
Definition: pathnodes.h:2185
void list_free(List *list)
Definition: list.c:1376
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:2175

◆ cost_agg()

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

Definition at line 2310 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, hash_agg_entry_size(), hash_agg_set_limits(), JOIN_INNER, Max, MemSet, AggClauseCosts::numAggs, QualCost::per_tuple, random_page_cost, relation_byte_size(), Path::rows, seq_page_cost, QualCost::startup, Path::startup_cost, Path::total_cost, AggClauseCosts::transCost, and AggClauseCosts::transitionSpace.

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

2316 {
2317  double output_tuples;
2318  Cost startup_cost;
2319  Cost total_cost;
2320  AggClauseCosts dummy_aggcosts;
2321 
2322  /* Use all-zero per-aggregate costs if NULL is passed */
2323  if (aggcosts == NULL)
2324  {
2325  Assert(aggstrategy == AGG_HASHED);
2326  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
2327  aggcosts = &dummy_aggcosts;
2328  }
2329 
2330  /*
2331  * The transCost.per_tuple component of aggcosts should be charged once
2332  * per input tuple, corresponding to the costs of evaluating the aggregate
2333  * transfns and their input expressions. The finalCost.per_tuple component
2334  * is charged once per output tuple, corresponding to the costs of
2335  * evaluating the finalfns. Startup costs are of course charged but once.
2336  *
2337  * If we are grouping, we charge an additional cpu_operator_cost per
2338  * grouping column per input tuple for grouping comparisons.
2339  *
2340  * We will produce a single output tuple if not grouping, and a tuple per
2341  * group otherwise. We charge cpu_tuple_cost for each output tuple.
2342  *
2343  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2344  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2345  * input path is already sorted appropriately, AGG_SORTED should be
2346  * preferred (since it has no risk of memory overflow). This will happen
2347  * as long as the computed total costs are indeed exactly equal --- but if
2348  * there's roundoff error we might do the wrong thing. So be sure that
2349  * the computations below form the same intermediate values in the same
2350  * order.
2351  */
2352  if (aggstrategy == AGG_PLAIN)
2353  {
2354  startup_cost = input_total_cost;
2355  startup_cost += aggcosts->transCost.startup;
2356  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2357  startup_cost += aggcosts->finalCost.startup;
2358  startup_cost += aggcosts->finalCost.per_tuple;
2359  /* we aren't grouping */
2360  total_cost = startup_cost + cpu_tuple_cost;
2361  output_tuples = 1;
2362  }
2363  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2364  {
2365  /* Here we are able to deliver output on-the-fly */
2366  startup_cost = input_startup_cost;
2367  total_cost = input_total_cost;
2368  if (aggstrategy == AGG_MIXED && !enable_hashagg)
2369  {
2370  startup_cost += disable_cost;
2371  total_cost += disable_cost;
2372  }
2373  /* calcs phrased this way to match HASHED case, see note above */
2374  total_cost += aggcosts->transCost.startup;
2375  total_cost += aggcosts->transCost.per_tuple * input_tuples;
2376  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2377  total_cost += aggcosts->finalCost.startup;
2378  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2379  total_cost += cpu_tuple_cost * numGroups;
2380  output_tuples = numGroups;
2381  }
2382  else
2383  {
2384  /* must be AGG_HASHED */
2385  startup_cost = input_total_cost;
2386  if (!enable_hashagg)
2387  startup_cost += disable_cost;
2388  startup_cost += aggcosts->transCost.startup;
2389  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2390  /* cost of computing hash value */
2391  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2392  startup_cost += aggcosts->finalCost.startup;
2393 
2394  total_cost = startup_cost;
2395  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2396  /* cost of retrieving from hash table */
2397  total_cost += cpu_tuple_cost * numGroups;
2398  output_tuples = numGroups;
2399  }
2400 
2401  /*
2402  * Add the disk costs of hash aggregation that spills to disk.
2403  *
2404  * Groups that go into the hash table stay in memory until finalized, so
2405  * spilling and reprocessing tuples doesn't incur additional invocations
2406  * of transCost or finalCost. Furthermore, the computed hash value is
2407  * stored with the spilled tuples, so we don't incur extra invocations of
2408  * the hash function.
2409  *
2410  * Hash Agg begins returning tuples after the first batch is complete.
2411  * Accrue writes (spilled tuples) to startup_cost and to total_cost;
2412  * accrue reads only to total_cost.
2413  */
2414  if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
2415  {
2416  double pages;
2417  double pages_written = 0.0;
2418  double pages_read = 0.0;
2419  double hashentrysize;
2420  double nbatches;
2421  Size mem_limit;
2422  uint64 ngroups_limit;
2423  int num_partitions;
2424  int depth;
2425 
2426  /*
2427  * Estimate number of batches based on the computed limits. If less
2428  * than or equal to one, all groups are expected to fit in memory;
2429  * otherwise we expect to spill.
2430  */
2431  hashentrysize = hash_agg_entry_size(aggcosts->numAggs, input_width,
2432  aggcosts->transitionSpace);
2433  hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
2434  &ngroups_limit, &num_partitions);
2435 
2436  nbatches = Max((numGroups * hashentrysize) / mem_limit,
2437  numGroups / ngroups_limit);
2438 
2439  nbatches = Max(ceil(nbatches), 1.0);
2440  num_partitions = Max(num_partitions, 2);
2441 
2442  /*
2443  * The number of partitions can change at different levels of
2444  * recursion; but for the purposes of this calculation assume it stays
2445  * constant.
2446  */
2447  depth = ceil(log(nbatches) / log(num_partitions));
2448 
2449  /*
2450  * Estimate number of pages read and written. For each level of
2451  * recursion, a tuple must be written and then later read.
2452  */
2453  pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
2454  pages_written = pages_read = pages * depth;
2455 
2456  startup_cost += pages_written * random_page_cost;
2457  total_cost += pages_written * random_page_cost;
2458  total_cost += pages_read * seq_page_cost;
2459  }
2460 
2461  /*
2462  * If there are quals (HAVING quals), account for their cost and
2463  * selectivity.
2464  */
2465  if (quals)
2466  {
2467  QualCost qual_cost;
2468 
2469  cost_qual_eval(&qual_cost, quals, root);
2470  startup_cost += qual_cost.startup;
2471  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2472 
2473  output_tuples = clamp_row_est(output_tuples *
2475  quals,
2476  0,
2477  JOIN_INNER,
2478  NULL));
2479  }
2480 
2481  path->rows = output_tuples;
2482  path->startup_cost = startup_cost;
2483  path->total_cost = total_cost;
2484 }
QualCost finalCost
Definition: pathnodes.h:63
#define MemSet(start, val, len)
Definition: c.h:949
QualCost transCost
Definition: pathnodes.h:62
Cost startup
Definition: pathnodes.h:45
double random_page_cost
Definition: costsize.c:112
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1695
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4043
Cost startup_cost
Definition: pathnodes.h:1155
Cost disable_cost
Definition: costsize.c:121
double cpu_operator_cost
Definition: costsize.c:115
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5678
Cost total_cost
Definition: pathnodes.h:1156
#define Max(x, y)
Definition: c.h:921
#define Assert(condition)
Definition: c.h:745
double rows
Definition: pathnodes.h:1154
size_t Size
Definition: c.h:473
double cpu_tuple_cost
Definition: costsize.c:113
bool enable_hashagg
Definition: costsize.c:132
void hash_agg_set_limits(double hashentrysize, double input_groups, int used_bits, Size *mem_limit, uint64 *ngroups_limit, int *num_partitions)
Definition: nodeAgg.c:1793
Size transitionSpace
Definition: pathnodes.h:64
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:189
double seq_page_cost
Definition: costsize.c:111
double Cost
Definition: nodes.h:663

◆ cost_append()

void cost_append ( AppendPath path)

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

2035 {
2036  ListCell *l;
2037 
2038  apath->path.startup_cost = 0;
2039  apath->path.total_cost = 0;
2040  apath->path.rows = 0;
2041 
2042  if (apath->subpaths == NIL)
2043  return;
2044 
2045  if (!apath->path.parallel_aware)
2046  {
2047  List *pathkeys = apath->path.pathkeys;
2048 
2049  if (pathkeys == NIL)
2050  {
2051  Path *subpath = (Path *) linitial(apath->subpaths);
2052 
2053  /*
2054  * For an unordered, non-parallel-aware Append we take the startup
2055  * cost as the startup cost of the first subpath.
2056  */
2057  apath->path.startup_cost = subpath->startup_cost;
2058 
2059  /* Compute rows and costs as sums of subplan rows and costs. */
2060  foreach(l, apath->subpaths)
2061  {
2062  Path *subpath = (Path *) lfirst(l);
2063 
2064  apath->path.rows += subpath->rows;
2065  apath->path.total_cost += subpath->total_cost;
2066  }
2067  }
2068  else
2069  {
2070  /*
2071  * For an ordered, non-parallel-aware Append we take the startup
2072  * cost as the sum of the subpath startup costs. This ensures
2073  * that we don't underestimate the startup cost when a query's
2074  * LIMIT is such that several of the children have to be run to
2075  * satisfy it. This might be overkill --- another plausible hack
2076  * would be to take the Append's startup cost as the maximum of
2077  * the child startup costs. But we don't want to risk believing
2078  * that an ORDER BY LIMIT query can be satisfied at small cost
2079  * when the first child has small startup cost but later ones
2080  * don't. (If we had the ability to deal with nonlinear cost
2081  * interpolation for partial retrievals, we would not need to be
2082  * so conservative about this.)
2083  *
2084  * This case is also different from the above in that we have to
2085  * account for possibly injecting sorts into subpaths that aren't
2086  * natively ordered.
2087  */
2088  foreach(l, apath->subpaths)
2089  {
2090  Path *subpath = (Path *) lfirst(l);
2091  Path sort_path; /* dummy for result of cost_sort */
2092 
2093  if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
2094  {
2095  /*
2096  * We'll need to insert a Sort node, so include costs for
2097  * that. We can use the parent's LIMIT if any, since we
2098  * certainly won't pull more than that many tuples from
2099  * any child.
2100  */
2101  cost_sort(&sort_path,
2102  NULL, /* doesn't currently need root */
2103  pathkeys,
2104  subpath->total_cost,
2105  subpath->rows,
2106  subpath->pathtarget->width,
2107  0.0,
2108  work_mem,
2109  apath->limit_tuples);
2110  subpath = &sort_path;
2111  }
2112 
2113  apath->path.rows += subpath->rows;
2114  apath->path.startup_cost += subpath->startup_cost;
2115  apath->path.total_cost += subpath->total_cost;
2116  }
2117  }
2118  }
2119  else /* parallel-aware */
2120  {
2121  int i = 0;
2122  double parallel_divisor = get_parallel_divisor(&apath->path);
2123 
2124  /* Parallel-aware Append never produces ordered output. */
2125  Assert(apath->path.pathkeys == NIL);
2126 
2127  /* Calculate startup cost. */
2128  foreach(l, apath->subpaths)
2129  {
2130  Path *subpath = (Path *) lfirst(l);
2131 
2132  /*
2133  * Append will start returning tuples when the child node having
2134  * lowest startup cost is done setting up. We consider only the
2135  * first few subplans that immediately get a worker assigned.
2136  */
2137  if (i == 0)
2138  apath->path.startup_cost = subpath->startup_cost;
2139  else if (i < apath->path.parallel_workers)
2140  apath->path.startup_cost = Min(apath->path.startup_cost,
2141  subpath->startup_cost);
2142 
2143  /*
2144  * Apply parallel divisor to subpaths. Scale the number of rows
2145  * for each partial subpath based on the ratio of the parallel
2146  * divisor originally used for the subpath to the one we adopted.
2147  * Also add the cost of partial paths to the total cost, but
2148  * ignore non-partial paths for now.
2149  */
2150  if (i < apath->first_partial_path)
2151  apath->path.rows += subpath->rows / parallel_divisor;
2152  else
2153  {
2154  double subpath_parallel_divisor;
2155 
2156  subpath_parallel_divisor = get_parallel_divisor(subpath);
2157  apath->path.rows += subpath->rows * (subpath_parallel_divisor /
2158  parallel_divisor);
2159  apath->path.total_cost += subpath->total_cost;
2160  }
2161 
2162  apath->path.rows = clamp_row_est(apath->path.rows);
2163 
2164  i++;
2165  }
2166 
2167  /* Add cost for non-partial subpaths. */
2168  apath->path.total_cost +=
2169  append_nonpartial_cost(apath->subpaths,
2170  apath->first_partial_path,
2171  apath->path.parallel_workers);
2172  }
2173 
2174  /*
2175  * Although Append does not do any selection or projection, it's not free;
2176  * add a small per-tuple overhead.
2177  */
2178  apath->path.total_cost +=
2179  cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * apath->path.rows;
2180 }
#define NIL
Definition: pg_list.h:65
PathTarget * pathtarget
Definition: pathnodes.h:1145
#define Min(x, y)
Definition: c.h:927
static Cost append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
Definition: costsize.c:1958
#define linitial(l)
Definition: pg_list.h:195
Cost startup_cost
Definition: pathnodes.h:1155
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5699
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:108
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:1927
int work_mem
Definition: globals.c:121
Cost total_cost
Definition: pathnodes.h:1156
List * pathkeys
Definition: pathnodes.h:1158
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
double rows
Definition: pathnodes.h:1154
double cpu_tuple_cost
Definition: costsize.c:113
int i
double clamp_row_est(double nrows)
Definition: costsize.c:189
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 1086 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 create_bitmap_and_path().

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

◆ 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 942 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_scan_cost_est(), and create_bitmap_heap_path().

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

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

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

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

◆ cost_bitmap_tree_node()

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

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

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

◆ cost_ctescan()

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

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

1502 {
1503  Cost startup_cost = 0;
1504  Cost run_cost = 0;
1505  QualCost qpqual_cost;
1506  Cost cpu_per_tuple;
1507 
1508  /* Should only be applied to base relations that are CTEs */
1509  Assert(baserel->relid > 0);
1510  Assert(baserel->rtekind == RTE_CTE);
1511 
1512  /* Mark the path with the correct row estimate */
1513  if (param_info)
1514  path->rows = param_info->ppi_rows;
1515  else
1516  path->rows = baserel->rows;
1517 
1518  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1519  cpu_per_tuple = cpu_tuple_cost;
1520 
1521  /* Add scanning CPU costs */
1522  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1523 
1524  startup_cost += qpqual_cost.startup;
1525  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1526  run_cost += cpu_per_tuple * baserel->tuples;
1527 
1528  /* tlist eval costs are paid per output row, not per tuple scanned */
1529  startup_cost += path->pathtarget->cost.startup;
1530  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1531 
1532  path->startup_cost = startup_cost;
1533  path->total_cost = startup_cost + run_cost;
1534 }
PathTarget * pathtarget
Definition: pathnodes.h:1145
double tuples
Definition: pathnodes.h:705
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1155
Index relid
Definition: pathnodes.h:693
RTEKind rtekind
Definition: pathnodes.h:695
double rows
Definition: pathnodes.h:668
Cost total_cost
Definition: pathnodes.h:1156
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4329
#define Assert(condition)
Definition: c.h:745
double rows
Definition: pathnodes.h:1154
QualCost cost
Definition: pathnodes.h:1076
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: pathnodes.h:1104
double Cost
Definition: nodes.h:663

◆ cost_functionscan()

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

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

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

◆ cost_gather()

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

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

368 {
369  Cost startup_cost = 0;
370  Cost run_cost = 0;
371 
372  /* Mark the path with the correct row estimate */
373  if (rows)
374  path->path.rows = *rows;
375  else if (param_info)
376  path->path.rows = param_info->ppi_rows;
377  else
378  path->path.rows = rel->rows;
379 
380  startup_cost = path->subpath->startup_cost;
381 
382  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
383 
384  /* Parallel setup and communication cost. */
385  startup_cost += parallel_setup_cost;
386  run_cost += parallel_tuple_cost * path->path.rows;
387 
388  path->path.startup_cost = startup_cost;
389  path->path.total_cost = (startup_cost + run_cost);
390 }
double parallel_setup_cost
Definition: costsize.c:117
Cost startup_cost
Definition: pathnodes.h:1155
Path * subpath
Definition: pathnodes.h:1495
Cost total_cost
Definition: pathnodes.h:1156
double rows
Definition: pathnodes.h:1154
double ppi_rows
Definition: pathnodes.h:1104
double Cost
Definition: nodes.h:663
double parallel_tuple_cost
Definition: costsize.c:116

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

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

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

2573 {
2574  double output_tuples;
2575  Cost startup_cost;
2576  Cost total_cost;
2577 
2578  output_tuples = numGroups;
2579  startup_cost = input_startup_cost;
2580  total_cost = input_total_cost;
2581 
2582  /*
2583  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2584  * all columns get compared at most of the tuples.
2585  */
2586  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2587 
2588  /*
2589  * If there are quals (HAVING quals), account for their cost and
2590  * selectivity.
2591  */
2592  if (quals)
2593  {
2594  QualCost qual_cost;
2595 
2596  cost_qual_eval(&qual_cost, quals, root);
2597  startup_cost += qual_cost.startup;
2598  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2599 
2600  output_tuples = clamp_row_est(output_tuples *
2602  quals,
2603  0,
2604  JOIN_INNER,
2605  NULL));
2606  }
2607 
2608  path->rows = output_tuples;
2609  path->startup_cost = startup_cost;
2610  path->total_cost = total_cost;
2611 }
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:4043
Cost startup_cost
Definition: pathnodes.h:1155
double cpu_operator_cost
Definition: costsize.c:115
Cost total_cost
Definition: pathnodes.h:1156
double rows
Definition: pathnodes.h:1154
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:189
double Cost
Definition: nodes.h:663

◆ cost_incremental_sort()

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

Definition at line 1788 of file costsize.c.

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

Referenced by create_incremental_sort_path().

1793 {
1794  Cost startup_cost = 0,
1795  run_cost = 0,
1796  input_run_cost = input_total_cost - input_startup_cost;
1797  double group_tuples,
1798  input_groups;
1799  Cost group_startup_cost,
1800  group_run_cost,
1801  group_input_run_cost;
1802  List *presortedExprs = NIL;
1803  ListCell *l;
1804  int i = 0;
1805  bool unknown_varno = false;
1806 
1807  Assert(presorted_keys != 0);
1808 
1809  /*
1810  * We want to be sure the cost of a sort is never estimated as zero, even
1811  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1812  */
1813  if (input_tuples < 2.0)
1814  input_tuples = 2.0;
1815 
1816  /* Default estimate of number of groups, capped to one group per row. */
1817  input_groups = Min(input_tuples, DEFAULT_NUM_DISTINCT);
1818 
1819  /*
1820  * Extract presorted keys as list of expressions.
1821  *
1822  * We need to be careful about Vars containing "varno 0" which might have
1823  * been introduced by generate_append_tlist, which would confuse
1824  * estimate_num_groups (in fact it'd fail for such expressions). See
1825  * recurse_set_operations which has to deal with the same issue.
1826  *
1827  * Unlike recurse_set_operations we can't access the original target list
1828  * here, and even if we could it's not very clear how useful would that be
1829  * for a set operation combining multiple tables. So we simply detect if
1830  * there are any expressions with "varno 0" and use the default
1831  * DEFAULT_NUM_DISTINCT in that case.
1832  *
1833  * We might also use either 1.0 (a single group) or input_tuples (each row
1834  * being a separate group), pretty much the worst and best case for
1835  * incremental sort. But those are extreme cases and using something in
1836  * between seems reasonable. Furthermore, generate_append_tlist is used
1837  * for set operations, which are likely to produce mostly unique output
1838  * anyway - from that standpoint the DEFAULT_NUM_DISTINCT is defensive
1839  * while maintaining lower startup cost.
1840  */
1841  foreach(l, pathkeys)
1842  {
1843  PathKey *key = (PathKey *) lfirst(l);
1845  linitial(key->pk_eclass->ec_members);
1846 
1847  /*
1848  * Check if the expression contains Var with "varno 0" so that we
1849  * don't call estimate_num_groups in that case.
1850  */
1851  if (bms_is_member(0, pull_varnos((Node *) member->em_expr)))
1852  {
1853  unknown_varno = true;
1854  break;
1855  }
1856 
1857  /* expression not containing any Vars with "varno 0" */
1858  presortedExprs = lappend(presortedExprs, member->em_expr);
1859 
1860  i++;
1861  if (i >= presorted_keys)
1862  break;
1863  }
1864 
1865  /* Estimate number of groups with equal presorted keys. */
1866  if (!unknown_varno)
1867  input_groups = estimate_num_groups(root, presortedExprs, input_tuples, NULL);
1868 
1869  group_tuples = input_tuples / input_groups;
1870  group_input_run_cost = input_run_cost / input_groups;
1871 
1872  /*
1873  * Estimate average cost of sorting of one group where presorted keys are
1874  * equal. Incremental sort is sensitive to distribution of tuples to the
1875  * groups, where we're relying on quite rough assumptions. Thus, we're
1876  * pessimistic about incremental sort performance and increase its average
1877  * group size by half.
1878  */
1879  cost_tuplesort(&group_startup_cost, &group_run_cost,
1880  1.5 * group_tuples, width, comparison_cost, sort_mem,
1881  limit_tuples);
1882 
1883  /*
1884  * Startup cost of incremental sort is the startup cost of its first group
1885  * plus the cost of its input.
1886  */
1887  startup_cost += group_startup_cost
1888  + input_startup_cost + group_input_run_cost;
1889 
1890  /*
1891  * After we started producing tuples from the first group, the cost of
1892  * producing all the tuples is given by the cost to finish processing this
1893  * group, plus the total cost to process the remaining groups, plus the
1894  * remaining cost of input.
1895  */
1896  run_cost += group_run_cost
1897  + (group_run_cost + group_startup_cost) * (input_groups - 1)
1898  + group_input_run_cost * (input_groups - 1);
1899 
1900  /*
1901  * Incremental sort adds some overhead by itself. Firstly, it has to
1902  * detect the sort groups. This is roughly equal to one extra copy and
1903  * comparison per tuple. Secondly, it has to reset the tuplesort context
1904  * for every group.
1905  */
1906  run_cost += (cpu_tuple_cost + comparison_cost) * input_tuples;
1907  run_cost += 2.0 * cpu_tuple_cost * input_groups;
1908 
1909  path->rows = input_tuples;
1910  path->startup_cost = startup_cost;
1911  path->total_cost = startup_cost + run_cost;
1912 }
#define NIL
Definition: pg_list.h:65
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3360
#define Min(x, y)
Definition: c.h:927
Definition: nodes.h:529
Oid member
#define linitial(l)
Definition: pg_list.h:195
Cost startup_cost
Definition: pathnodes.h:1155
static void cost_tuplesort(Cost *startup_cost, Cost *run_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:1686
Relids pull_varnos(Node *node)
Definition: var.c:95
List * lappend(List *list, void *datum)
Definition: list.c:321
Cost total_cost
Definition: pathnodes.h:1156
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
double rows
Definition: pathnodes.h:1154
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1041
double cpu_tuple_cost
Definition: costsize.c:113
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:49
int i
Definition: pg_list.h:50
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
double Cost
Definition: nodes.h:663
List * ec_members
Definition: pathnodes.h:964

◆ cost_index()

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

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

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

◆ cost_material()

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

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

2259 {
2260  Cost startup_cost = input_startup_cost;
2261  Cost run_cost = input_total_cost - input_startup_cost;
2262  double nbytes = relation_byte_size(tuples, width);
2263  long work_mem_bytes = work_mem * 1024L;
2264 
2265  path->rows = tuples;
2266 
2267  /*
2268  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2269  * reflect bookkeeping overhead. (This rate must be more than what
2270  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2271  * if it is exactly the same then there will be a cost tie between
2272  * nestloop with A outer, materialized B inner and nestloop with B outer,
2273  * materialized A inner. The extra cost ensures we'll prefer
2274  * materializing the smaller rel.) Note that this is normally a good deal
2275  * less than cpu_tuple_cost; which is OK because a Material plan node
2276  * doesn't do qual-checking or projection, so it's got less overhead than
2277  * most plan nodes.
2278  */
2279  run_cost += 2 * cpu_operator_cost * tuples;
2280 
2281  /*
2282  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2283  * This cost is assumed to be evenly spread through the plan run phase,
2284  * which isn't exactly accurate but our cost model doesn't allow for
2285  * nonuniform costs within the run phase.
2286  */
2287  if (nbytes > work_mem_bytes)
2288  {
2289  double npages = ceil(nbytes / BLCKSZ);
2290 
2291  run_cost += seq_page_cost * npages;
2292  }
2293 
2294  path->startup_cost = startup_cost;
2295  path->total_cost = startup_cost + run_cost;
2296 }
Cost startup_cost
Definition: pathnodes.h:1155
double cpu_operator_cost
Definition: costsize.c:115
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5678
int work_mem
Definition: globals.c:121
Cost total_cost
Definition: pathnodes.h:1156
double rows
Definition: pathnodes.h:1154
double seq_page_cost
Definition: costsize.c:111
double Cost
Definition: nodes.h:663

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

2211 {
2212  Cost startup_cost = 0;
2213  Cost run_cost = 0;
2214  Cost comparison_cost;
2215  double N;
2216  double logN;
2217 
2218  /*
2219  * Avoid log(0)...
2220  */
2221  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2222  logN = LOG2(N);
2223 
2224  /* Assumed cost per tuple comparison */
2225  comparison_cost = 2.0 * cpu_operator_cost;
2226 
2227  /* Heap creation cost */
2228  startup_cost += comparison_cost * N * logN;
2229 
2230  /* Per-tuple heap maintenance cost */
2231  run_cost += tuples * comparison_cost * logN;
2232 
2233  /*
2234  * Although MergeAppend does not do any selection or projection, it's not
2235  * free; add a small per-tuple overhead.
2236  */
2237  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2238 
2239  path->startup_cost = startup_cost + input_startup_cost;
2240  path->total_cost = startup_cost + run_cost + input_total_cost;
2241 }
Cost startup_cost
Definition: pathnodes.h:1155
double cpu_operator_cost
Definition: costsize.c:115
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:108
Cost total_cost
Definition: pathnodes.h:1156
#define LOG2(x)
Definition: costsize.c:101
double cpu_tuple_cost
Definition: costsize.c:113
double Cost
Definition: nodes.h:663

◆ cost_namedtuplestorescan()

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

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

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

◆ cost_qual_eval()

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

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

4044 {
4045  cost_qual_eval_context context;
4046  ListCell *l;
4047 
4048  context.root = root;
4049  context.total.startup = 0;
4050  context.total.per_tuple = 0;
4051 
4052  /* We don't charge any cost for the implicit ANDing at top level ... */
4053 
4054  foreach(l, quals)
4055  {
4056  Node *qual = (Node *) lfirst(l);
4057 
4058  cost_qual_eval_walker(qual, &context);
4059  }
4060 
4061  *cost = context.total;
4062 }
PlannerInfo * root
Definition: costsize.c:146
Definition: nodes.h:529
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:4083
#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 4069 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().

4070 {
4071  cost_qual_eval_context context;
4072 
4073  context.root = root;
4074  context.total.startup = 0;
4075  context.total.per_tuple = 0;
4076 
4077  cost_qual_eval_walker(qual, &context);
4078 
4079  *cost = context.total;
4080 }
PlannerInfo * root
Definition: costsize.c:146
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:4083

◆ cost_recursive_union()

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

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

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

◆ cost_resultscan()

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

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

1580 {
1581  Cost startup_cost = 0;
1582  Cost run_cost = 0;
1583  QualCost qpqual_cost;
1584  Cost cpu_per_tuple;
1585 
1586  /* Should only be applied to RTE_RESULT base relations */
1587  Assert(baserel->relid > 0);
1588  Assert(baserel->rtekind == RTE_RESULT);
1589 
1590  /* Mark the path with the correct row estimate */
1591  if (param_info)
1592  path->rows = param_info->ppi_rows;
1593  else
1594  path->rows = baserel->rows;
1595 
1596  /* We charge qual cost plus cpu_tuple_cost */
1597  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1598 
1599  startup_cost += qpqual_cost.startup;
1600  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1601  run_cost += cpu_per_tuple * baserel->tuples;
1602 
1603  path->startup_cost = startup_cost;
1604  path->total_cost = startup_cost + run_cost;
1605 }
double tuples
Definition: pathnodes.h:705
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1155
Index relid
Definition: pathnodes.h:693
RTEKind rtekind
Definition: pathnodes.h:695
double rows
Definition: pathnodes.h:668
Cost total_cost
Definition: pathnodes.h:1156
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4329
#define Assert(condition)
Definition: c.h:745
double rows
Definition: pathnodes.h:1154
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: pathnodes.h:1104
double Cost
Definition: nodes.h:663

◆ cost_samplescan()

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

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

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

◆ cost_seqscan()

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

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

215 {
216  Cost startup_cost = 0;
217  Cost cpu_run_cost;
218  Cost disk_run_cost;
219  double spc_seq_page_cost;
220  QualCost qpqual_cost;
221  Cost cpu_per_tuple;
222 
223  /* Should only be applied to base relations */
224  Assert(baserel->relid > 0);
225  Assert(baserel->rtekind == RTE_RELATION);
226 
227  /* Mark the path with the correct row estimate */
228  if (param_info)
229  path->rows = param_info->ppi_rows;
230  else
231  path->rows = baserel->rows;
232 
233  if (!enable_seqscan)
234  startup_cost += disable_cost;
235 
236  /* fetch estimated page cost for tablespace containing table */
238  NULL,
239  &spc_seq_page_cost);
240 
241  /*
242  * disk costs
243  */
244  disk_run_cost = spc_seq_page_cost * baserel->pages;
245 
246  /* CPU costs */
247  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
248 
249  startup_cost += qpqual_cost.startup;
250  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
251  cpu_run_cost = cpu_per_tuple * baserel->tuples;
252  /* tlist eval costs are paid per output row, not per tuple scanned */
253  startup_cost += path->pathtarget->cost.startup;
254  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
255 
256  /* Adjust costing for parallelism, if used. */
257  if (path->parallel_workers > 0)
258  {
259  double parallel_divisor = get_parallel_divisor(path);
260 
261  /* The CPU cost is divided among all the workers. */
262  cpu_run_cost /= parallel_divisor;
263 
264  /*
265  * It may be possible to amortize some of the I/O cost, but probably
266  * not very much, because most operating systems already do aggressive
267  * prefetching. For now, we assume that the disk run cost can't be
268  * amortized at all.
269  */
270 
271  /*
272  * In the case of a parallel plan, the row count needs to represent
273  * the number of tuples processed per worker.
274  */
275  path->rows = clamp_row_est(path->rows / parallel_divisor);
276  }
277 
278  path->startup_cost = startup_cost;
279  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
280 }
PathTarget * pathtarget
Definition: pathnodes.h:1145
double tuples
Definition: pathnodes.h:705
Oid reltablespace
Definition: pathnodes.h:694
int parallel_workers
Definition: pathnodes.h:1151
bool enable_seqscan
Definition: costsize.c:125
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1155
Cost disable_cost
Definition: costsize.c:121
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5699
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:693
RTEKind rtekind
Definition: pathnodes.h:695
double rows
Definition: pathnodes.h:668
Cost total_cost
Definition: pathnodes.h:1156
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4329
BlockNumber pages
Definition: pathnodes.h:704
#define Assert(condition)
Definition: c.h:745
double rows
Definition: pathnodes.h:1154
QualCost cost
Definition: pathnodes.h:1076
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: pathnodes.h:1104
double clamp_row_est(double nrows)
Definition: costsize.c:189
double Cost
Definition: nodes.h:663

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

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

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

1932 {
1933  Cost startup_cost;
1934  Cost run_cost;
1935 
1936  cost_tuplesort(&startup_cost, &run_cost,
1937  tuples, width,
1938  comparison_cost, sort_mem,
1939  limit_tuples);
1940 
1941  if (!enable_sort)
1942  startup_cost += disable_cost;
1943 
1944  startup_cost += input_cost;
1945 
1946  path->rows = tuples;
1947  path->startup_cost = startup_cost;
1948  path->total_cost = startup_cost + run_cost;
1949 }
bool enable_sort
Definition: costsize.c:130
Cost startup_cost
Definition: pathnodes.h:1155
Cost disable_cost
Definition: costsize.c:121
static void cost_tuplesort(Cost *startup_cost, Cost *run_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:1686
Cost total_cost
Definition: pathnodes.h:1156
double rows
Definition: pathnodes.h:1154
double Cost
Definition: nodes.h:663

◆ cost_subplan()

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

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

3844 {
3845  QualCost sp_cost;
3846 
3847  /* Figure any cost for evaluating the testexpr */
3848  cost_qual_eval(&sp_cost,
3849  make_ands_implicit((Expr *) subplan->testexpr),
3850  root);
3851 
3852  if (subplan->useHashTable)
3853  {
3854  /*
3855  * If we are using a hash table for the subquery outputs, then the
3856  * cost of evaluating the query is a one-time cost. We charge one
3857  * cpu_operator_cost per tuple for the work of loading the hashtable,
3858  * too.
3859  */
3860  sp_cost.startup += plan->total_cost +
3861  cpu_operator_cost * plan->plan_rows;
3862 
3863  /*
3864  * The per-tuple costs include the cost of evaluating the lefthand
3865  * expressions, plus the cost of probing the hashtable. We already
3866  * accounted for the lefthand expressions as part of the testexpr, and
3867  * will also have counted one cpu_operator_cost for each comparison
3868  * operator. That is probably too low for the probing cost, but it's
3869  * hard to make a better estimate, so live with it for now.
3870  */
3871  }
3872  else
3873  {
3874  /*
3875  * Otherwise we will be rescanning the subplan output on each
3876  * evaluation. We need to estimate how much of the output we will
3877  * actually need to scan. NOTE: this logic should agree with the
3878  * tuple_fraction estimates used by make_subplan() in
3879  * plan/subselect.c.
3880  */
3881  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
3882 
3883  if (subplan->subLinkType == EXISTS_SUBLINK)
3884  {
3885  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
3886  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
3887  }
3888  else if (subplan->subLinkType == ALL_SUBLINK ||
3889  subplan->subLinkType == ANY_SUBLINK)
3890  {
3891  /* assume we need 50% of the tuples */
3892  sp_cost.per_tuple += 0.50 * plan_run_cost;
3893  /* also charge a cpu_operator_cost per row examined */
3894  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
3895  }
3896  else
3897  {
3898  /* assume we need all tuples */
3899  sp_cost.per_tuple += plan_run_cost;
3900  }
3901 
3902  /*
3903  * Also account for subplan's startup cost. If the subplan is
3904  * uncorrelated or undirect correlated, AND its topmost node is one
3905  * that materializes its output, assume that we'll only need to pay
3906  * its startup cost once; otherwise assume we pay the startup cost
3907  * every time.
3908  */
3909  if (subplan->parParam == NIL &&
3911  sp_cost.startup += plan->startup_cost;
3912  else
3913  sp_cost.per_tuple += plan->startup_cost;
3914  }
3915 
3916  subplan->startup_cost = sp_cost.startup;
3917  subplan->per_call_cost = sp_cost.per_tuple;
3918 }
#define NIL
Definition: pg_list.h:65
double plan_rows
Definition: plannodes.h:129
SubLinkType subLinkType
Definition: primnodes.h:704
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:4043
Cost startup_cost
Definition: plannodes.h:123
double cpu_operator_cost
Definition: costsize.c:115
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:718
Node * testexpr
Definition: primnodes.h:706
Cost per_call_cost
Definition: primnodes.h:733
List * parParam
Definition: primnodes.h:729
#define nodeTag(nodeptr)
Definition: nodes.h:534
Cost total_cost
Definition: plannodes.h:124
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:623
bool useHashTable
Definition: primnodes.h:718
Cost startup_cost
Definition: primnodes.h:732
double clamp_row_est(double nrows)
Definition: costsize.c:189
double Cost
Definition: nodes.h:663

◆ cost_subqueryscan()

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

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

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

◆ cost_tablefuncscan()

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

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

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

◆ cost_tidscan()

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

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

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

◆ cost_valuesscan()

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

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

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

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

2498 {
2499  Cost startup_cost;
2500  Cost total_cost;
2501  ListCell *lc;
2502 
2503  startup_cost = input_startup_cost;
2504  total_cost = input_total_cost;
2505 
2506  /*
2507  * Window functions are assumed to cost their stated execution cost, plus
2508  * the cost of evaluating their input expressions, per tuple. Since they
2509  * may in fact evaluate their inputs at multiple rows during each cycle,
2510  * this could be a drastic underestimate; but without a way to know how
2511  * many rows the window function will fetch, it's hard to do better. In
2512  * any case, it's a good estimate for all the built-in window functions,
2513  * so we'll just do this for now.
2514  */
2515  foreach(lc, windowFuncs)
2516  {
2517  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
2518  Cost wfunccost;
2519  QualCost argcosts;
2520 
2521  argcosts.startup = argcosts.per_tuple = 0;
2522  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
2523  &argcosts);
2524  startup_cost += argcosts.startup;
2525  wfunccost = argcosts.per_tuple;
2526 
2527  /* also add the input expressions' cost to per-input-row costs */
2528  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
2529  startup_cost += argcosts.startup;
2530  wfunccost += argcosts.per_tuple;
2531 
2532  /*
2533  * Add the filter's cost to per-input-row costs. XXX We should reduce
2534  * input expression costs according to filter selectivity.
2535  */
2536  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
2537  startup_cost += argcosts.startup;
2538  wfunccost += argcosts.per_tuple;
2539 
2540  total_cost += wfunccost * input_tuples;
2541  }
2542 
2543  /*
2544  * We also charge cpu_operator_cost per grouping column per tuple for
2545  * grouping comparisons, plus cpu_tuple_cost per tuple for general
2546  * overhead.
2547  *
2548  * XXX this neglects costs of spooling the data to disk when it overflows
2549  * work_mem. Sooner or later that should get accounted for.
2550  */
2551  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
2552  total_cost += cpu_tuple_cost * input_tuples;
2553 
2554  path->rows = input_tuples;
2555  path->startup_cost = startup_cost;
2556  path->total_cost = total_cost;
2557 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4069
List * args
Definition: primnodes.h:377
Definition: nodes.h:529
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1908
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1155
#define lfirst_node(type, lc)
Definition: pg_list.h:193
double cpu_operator_cost
Definition: costsize.c:115
Oid winfnoid
Definition: primnodes.h:373
Cost total_cost
Definition: pathnodes.h:1156
Expr * aggfilter
Definition: primnodes.h:378
double rows
Definition: pathnodes.h:1154
double cpu_tuple_cost
Definition: costsize.c:113
double Cost
Definition: nodes.h:663

◆ final_cost_hashjoin()

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

Definition at line 3586 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_hash_mem(), 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, RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, and PathTarget::width.

Referenced by create_hashjoin_path().

3589 {
3590  Path *outer_path = path->jpath.outerjoinpath;
3591  Path *inner_path = path->jpath.innerjoinpath;
3592  double outer_path_rows = outer_path->rows;
3593  double inner_path_rows = inner_path->rows;
3594  double inner_path_rows_total = workspace->inner_rows_total;
3595  List *hashclauses = path->path_hashclauses;
3596  Cost startup_cost = workspace->startup_cost;
3597  Cost run_cost = workspace->run_cost;
3598  int numbuckets = workspace->numbuckets;
3599  int numbatches = workspace->numbatches;
3600  int hash_mem;
3601  Cost cpu_per_tuple;
3602  QualCost hash_qual_cost;
3603  QualCost qp_qual_cost;
3604  double hashjointuples;
3605  double virtualbuckets;
3606  Selectivity innerbucketsize;
3607  Selectivity innermcvfreq;
3608  ListCell *hcl;
3609 
3610  /* Mark the path with the correct row estimate */
3611  if (path->jpath.path.param_info)
3612  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3613  else
3614  path->jpath.path.rows = path->jpath.path.parent->rows;
3615 
3616  /* For partial paths, scale row estimate. */
3617  if (path->jpath.path.parallel_workers > 0)
3618  {
3619  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3620 
3621  path->jpath.path.rows =
3622  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3623  }
3624 
3625  /*
3626  * We could include disable_cost in the preliminary estimate, but that
3627  * would amount to optimizing for the case where the join method is
3628  * disabled, which doesn't seem like the way to bet.
3629  */
3630  if (!enable_hashjoin)
3631  startup_cost += disable_cost;
3632 
3633  /* mark the path with estimated # of batches */
3634  path->num_batches = numbatches;
3635 
3636  /* store the total number of tuples (sum of partial row estimates) */
3637  path->inner_rows_total = inner_path_rows_total;
3638 
3639  /* and compute the number of "virtual" buckets in the whole join */
3640  virtualbuckets = (double) numbuckets * (double) numbatches;
3641 
3642  /*
3643  * Determine bucketsize fraction and MCV frequency for the inner relation.
3644  * We use the smallest bucketsize or MCV frequency estimated for any
3645  * individual hashclause; this is undoubtedly conservative.
3646  *
3647  * BUT: if inner relation has been unique-ified, we can assume it's good
3648  * for hashing. This is important both because it's the right answer, and
3649  * because we avoid contaminating the cache with a value that's wrong for
3650  * non-unique-ified paths.
3651  */
3652  if (IsA(inner_path, UniquePath))
3653  {
3654  innerbucketsize = 1.0 / virtualbuckets;
3655  innermcvfreq = 0.0;
3656  }
3657  else
3658  {
3659  innerbucketsize = 1.0;
3660  innermcvfreq = 1.0;
3661  foreach(hcl, hashclauses)
3662  {
3663  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
3664  Selectivity thisbucketsize;
3665  Selectivity thismcvfreq;
3666 
3667  /*
3668  * First we have to figure out which side of the hashjoin clause
3669  * is the inner side.
3670  *
3671  * Since we tend to visit the same clauses over and over when
3672  * planning a large query, we cache the bucket stats estimates in
3673  * the RestrictInfo node to avoid repeated lookups of statistics.
3674  */
3675  if (bms_is_subset(restrictinfo->right_relids,
3676  inner_path->parent->relids))
3677  {
3678  /* righthand side is inner */
3679  thisbucketsize = restrictinfo->right_bucketsize;
3680  if (thisbucketsize < 0)
3681  {
3682  /* not cached yet */
3684  get_rightop(restrictinfo->clause),
3685  virtualbuckets,
3686  &restrictinfo->right_mcvfreq,
3687  &restrictinfo->right_bucketsize);
3688  thisbucketsize = restrictinfo->right_bucketsize;
3689  }
3690  thismcvfreq = restrictinfo->right_mcvfreq;
3691  }
3692  else
3693  {
3694  Assert(bms_is_subset(restrictinfo->left_relids,
3695  inner_path->parent->relids));
3696  /* lefthand side is inner */
3697  thisbucketsize = restrictinfo->left_bucketsize;
3698  if (thisbucketsize < 0)
3699  {
3700  /* not cached yet */
3702  get_leftop(restrictinfo->clause),
3703  virtualbuckets,
3704  &restrictinfo->left_mcvfreq,
3705  &restrictinfo->left_bucketsize);
3706  thisbucketsize = restrictinfo->left_bucketsize;
3707  }
3708  thismcvfreq = restrictinfo->left_mcvfreq;
3709  }
3710 
3711  if (innerbucketsize > thisbucketsize)
3712  innerbucketsize = thisbucketsize;
3713  if (innermcvfreq > thismcvfreq)
3714  innermcvfreq = thismcvfreq;
3715  }
3716  }
3717 
3718  /*
3719  * If the bucket holding the inner MCV would exceed hash_mem, we don't
3720  * want to hash unless there is really no other alternative, so apply
3721  * disable_cost. (The executor normally copes with excessive memory usage
3722  * by splitting batches, but obviously it cannot separate equal values
3723  * that way, so it will be unable to drive the batch size below hash_mem
3724  * when this is true.)
3725  */
3726  hash_mem = get_hash_mem();
3727  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
3728  inner_path->pathtarget->width) >
3729  (hash_mem * 1024L))
3730  startup_cost += disable_cost;
3731 
3732  /*
3733  * Compute cost of the hashquals and qpquals (other restriction clauses)
3734  * separately.
3735  */
3736  cost_qual_eval(&hash_qual_cost, hashclauses, root);
3737  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3738  qp_qual_cost.startup -= hash_qual_cost.startup;
3739  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
3740 
3741  /* CPU costs */
3742 
3743  if (path->jpath.jointype == JOIN_SEMI ||
3744  path->jpath.jointype == JOIN_ANTI ||
3745  extra->inner_unique)
3746  {
3747  double outer_matched_rows;
3748  Selectivity inner_scan_frac;
3749 
3750  /*
3751  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3752  * executor will stop after the first match.
3753  *
3754  * For an outer-rel row that has at least one match, we can expect the
3755  * bucket scan to stop after a fraction 1/(match_count+1) of the
3756  * bucket's rows, if the matches are evenly distributed. Since they
3757  * probably aren't quite evenly distributed, we apply a fuzz factor of
3758  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
3759  * to clamp inner_scan_frac to at most 1.0; but since match_count is
3760  * at least 1, no such clamp is needed now.)
3761  */
3762  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3763  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3764 
3765  startup_cost += hash_qual_cost.startup;
3766  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
3767  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
3768 
3769  /*
3770  * For unmatched outer-rel rows, the picture is quite a lot different.
3771  * In the first place, there is no reason to assume that these rows
3772  * preferentially hit heavily-populated buckets; instead assume they
3773  * are uncorrelated with the inner distribution and so they see an
3774  * average bucket size of inner_path_rows / virtualbuckets. In the
3775  * second place, it seems likely that they will have few if any exact
3776  * hash-code matches and so very few of the tuples in the bucket will
3777  * actually require eval of the hash quals. We don't have any good
3778  * way to estimate how many will, but for the moment assume that the
3779  * effective cost per bucket entry is one-tenth what it is for
3780  * matchable tuples.
3781  */
3782  run_cost += hash_qual_cost.per_tuple *
3783  (outer_path_rows - outer_matched_rows) *
3784  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
3785 
3786  /* Get # of tuples that will pass the basic join */
3787  if (path->jpath.jointype == JOIN_ANTI)
3788  hashjointuples = outer_path_rows - outer_matched_rows;
3789  else
3790  hashjointuples = outer_matched_rows;
3791  }
3792  else
3793  {
3794  /*
3795  * The number of tuple comparisons needed is the number of outer
3796  * tuples times the typical number of tuples in a hash bucket, which
3797  * is the inner relation size times its bucketsize fraction. At each
3798  * one, we need to evaluate the hashjoin quals. But actually,
3799  * charging the full qual eval cost at each tuple is pessimistic,
3800  * since we don't evaluate the quals unless the hash values match
3801  * exactly. For lack of a better idea, halve the cost estimate to
3802  * allow for that.
3803  */
3804  startup_cost += hash_qual_cost.startup;
3805  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
3806  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
3807 
3808  /*
3809  * Get approx # tuples passing the hashquals. We use
3810  * approx_tuple_count here because we need an estimate done with
3811  * JOIN_INNER semantics.
3812  */
3813  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
3814  }
3815 
3816  /*
3817  * For each tuple that gets through the hashjoin proper, we charge
3818  * cpu_tuple_cost plus the cost of evaluating additional restriction
3819  * clauses that are to be applied at the join. (This is pessimistic since
3820  * not all of the quals may get evaluated at each tuple.)
3821  */
3822  startup_cost += qp_qual_cost.startup;
3823  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3824  run_cost += cpu_per_tuple * hashjointuples;
3825 
3826  /* tlist eval costs are paid per output row, not per tuple scanned */
3827  startup_cost += path->jpath.path.pathtarget->cost.startup;
3828  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3829 
3830  path->jpath.path.startup_cost = startup_cost;
3831  path->jpath.path.total_cost = startup_cost + run_cost;
3832 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
JoinPath jpath
Definition: pathnodes.h:1599
PathTarget * pathtarget
Definition: pathnodes.h:1145
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:2428
int num_batches
Definition: pathnodes.h:1601
Selectivity right_mcvfreq
Definition: pathnodes.h:2049
Selectivity outer_match_frac
Definition: pathnodes.h:2405
Path * innerjoinpath
Definition: pathnodes.h:1526
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4572
int parallel_workers
Definition: pathnodes.h:1151
ParamPathInfo * param_info
Definition: pathnodes.h:1147
Relids left_relids
Definition: pathnodes.h:2012
double Selectivity
Definition: nodes.h:662
double inner_rows_total
Definition: pathnodes.h:1602
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:4043
Cost startup_cost
Definition: pathnodes.h:1155
Cost disable_cost
Definition: costsize.c:121
List * joinrestrictinfo
Definition: pathnodes.h:1528
RelOptInfo * parent
Definition: pathnodes.h:1144
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:5699
Relids relids
Definition: pathnodes.h:665
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:70
Expr * clause
Definition: pathnodes.h:1985
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5678
Path * outerjoinpath
Definition: pathnodes.h:1525
double inner_rows_total
Definition: pathnodes.h:2549
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:82
double rows
Definition: pathnodes.h:668
Cost total_cost
Definition: pathnodes.h:1156
Selectivity left_bucketsize
Definition: pathnodes.h:2046
Relids right_relids
Definition: pathnodes.h:2013
Path path
Definition: pathnodes.h:1518
#define Assert(condition)
Definition: c.h:745
double rows
Definition: pathnodes.h:1154
Selectivity left_mcvfreq
Definition: pathnodes.h:2048
QualCost cost
Definition: pathnodes.h:1076
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: pathnodes.h:1104
bool enable_hashjoin
Definition: costsize.c:136
Selectivity match_count
Definition: pathnodes.h:2406
Selectivity right_bucketsize
Definition: pathnodes.h:2047
JoinType jointype
Definition: pathnodes.h:1520
void estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
Definition: selfuncs.c:3723
List * path_hashclauses
Definition: pathnodes.h:1600
double clamp_row_est(double nrows)
Definition: costsize.c:189
Definition: pg_list.h:50
double Cost
Definition: nodes.h:663
int get_hash_mem(void)
Definition: nodeHash.c:3389

◆ final_cost_mergejoin()

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

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

3153 {
3154  Path *outer_path = path->jpath.outerjoinpath;
3155  Path *inner_path = path->jpath.innerjoinpath;
3156  double inner_path_rows = inner_path->rows;
3157  List *mergeclauses = path->path_mergeclauses;
3158  List *innersortkeys = path->innersortkeys;
3159  Cost startup_cost = workspace->startup_cost;
3160  Cost run_cost = workspace->run_cost;
3161  Cost inner_run_cost = workspace->inner_run_cost;
3162  double outer_rows = workspace->outer_rows;
3163  double inner_rows = workspace->inner_rows;
3164  double outer_skip_rows = workspace->outer_skip_rows;
3165  double inner_skip_rows = workspace->inner_skip_rows;
3166  Cost cpu_per_tuple,
3167  bare_inner_cost,
3168  mat_inner_cost;
3169  QualCost merge_qual_cost;
3170  QualCost qp_qual_cost;
3171  double mergejointuples,
3172  rescannedtuples;
3173  double rescanratio;
3174 
3175  /* Protect some assumptions below that rowcounts aren't zero or NaN */
3176  if (inner_path_rows <= 0 || isnan(inner_path_rows))
3177  inner_path_rows = 1;
3178 
3179  /* Mark the path with the correct row estimate */
3180  if (path->jpath.path.param_info)
3181  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3182  else
3183  path->jpath.path.rows = path->jpath.path.parent->rows;
3184 
3185  /* For partial paths, scale row estimate. */
3186  if (path->jpath.path.parallel_workers > 0)
3187  {
3188  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3189 
3190  path->jpath.path.rows =
3191  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3192  }
3193 
3194  /*
3195  * We could include disable_cost in the preliminary estimate, but that
3196  * would amount to optimizing for the case where the join method is
3197  * disabled, which doesn't seem like the way to bet.
3198  */
3199  if (!enable_mergejoin)
3200  startup_cost += disable_cost;
3201 
3202  /*
3203  * Compute cost of the mergequals and qpquals (other restriction clauses)
3204  * separately.
3205  */
3206  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
3207  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3208  qp_qual_cost.startup -= merge_qual_cost.startup;
3209  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
3210 
3211  /*
3212  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3213  * executor will stop scanning for matches after the first match. When
3214  * all the joinclauses are merge clauses, this means we don't ever need to
3215  * back up the merge, and so we can skip mark/restore overhead.
3216  */
3217  if ((path->jpath.jointype == JOIN_SEMI ||
3218  path->jpath.jointype == JOIN_ANTI ||
3219  extra->inner_unique) &&
3222  path->skip_mark_restore = true;
3223  else
3224  path->skip_mark_restore = false;
3225 
3226  /*
3227  * Get approx # tuples passing the mergequals. We use approx_tuple_count
3228  * here because we need an estimate done with JOIN_INNER semantics.
3229  */
3230  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
3231 
3232  /*
3233  * When there are equal merge keys in the outer relation, the mergejoin
3234  * must rescan any matching tuples in the inner relation. This means
3235  * re-fetching inner tuples; we have to estimate how often that happens.
3236  *
3237  * For regular inner and outer joins, the number of re-fetches can be
3238  * estimated approximately as size of merge join output minus size of
3239  * inner relation. Assume that the distinct key values are 1, 2, ..., and
3240  * denote the number of values of each key in the outer relation as m1,
3241  * m2, ...; in the inner relation, n1, n2, ... Then we have
3242  *
3243  * size of join = m1 * n1 + m2 * n2 + ...
3244  *
3245  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
3246  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
3247  * relation
3248  *
3249  * This equation works correctly for outer tuples having no inner match
3250  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
3251  * are effectively subtracting those from the number of rescanned tuples,
3252  * when we should not. Can we do better without expensive selectivity
3253  * computations?
3254  *
3255  * The whole issue is moot if we are working from a unique-ified outer
3256  * input, or if we know we don't need to mark/restore at all.
3257  */
3258  if (IsA(outer_path, UniquePath) || path->skip_mark_restore)
3259  rescannedtuples = 0;
3260  else
3261  {
3262  rescannedtuples = mergejointuples - inner_path_rows;
3263  /* Must clamp because of possible underestimate */
3264  if (rescannedtuples < 0)
3265  rescannedtuples = 0;
3266  }
3267 
3268  /*
3269  * We'll inflate various costs this much to account for rescanning. Note
3270  * that this is to be multiplied by something involving inner_rows, or
3271  * another number related to the portion of the inner rel we'll scan.
3272  */
3273  rescanratio = 1.0 + (rescannedtuples / inner_rows);
3274 
3275  /*
3276  * Decide whether we want to materialize the inner input to shield it from
3277  * mark/restore and performing re-fetches. Our cost model for regular
3278  * re-fetches is that a re-fetch costs the same as an original fetch,
3279  * which is probably an overestimate; but on the other hand we ignore the
3280  * bookkeeping costs of mark/restore. Not clear if it's worth developing
3281  * a more refined model. So we just need to inflate the inner run cost by
3282  * rescanratio.
3283  */
3284  bare_inner_cost = inner_run_cost * rescanratio;
3285 
3286  /*
3287  * When we interpose a Material node the re-fetch cost is assumed to be
3288  * just cpu_operator_cost per tuple, independently of the underlying
3289  * plan's cost; and we charge an extra cpu_operator_cost per original
3290  * fetch as well. Note that we're assuming the materialize node will
3291  * never spill to disk, since it only has to remember tuples back to the
3292  * last mark. (If there are a huge number of duplicates, our other cost
3293  * factors will make the path so expensive that it probably won't get
3294  * chosen anyway.) So we don't use cost_rescan here.
3295  *
3296  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3297  * of the generated Material node.
3298  */
3299  mat_inner_cost = inner_run_cost +
3300  cpu_operator_cost * inner_rows * rescanratio;
3301 
3302  /*
3303  * If we don't need mark/restore at all, we don't need materialization.
3304  */
3305  if (path->skip_mark_restore)
3306  path->materialize_inner = false;
3307 
3308  /*
3309  * Prefer materializing if it looks cheaper, unless the user has asked to
3310  * suppress materialization.
3311  */
3312  else if (enable_material && mat_inner_cost < bare_inner_cost)
3313  path->materialize_inner = true;
3314 
3315  /*
3316  * Even if materializing doesn't look cheaper, we *must* do it if the
3317  * inner path is to be used directly (without sorting) and it doesn't
3318  * support mark/restore.
3319  *
3320  * Since the inner side must be ordered, and only Sorts and IndexScans can
3321  * create order to begin with, and they both support mark/restore, you
3322  * might think there's no problem --- but you'd be wrong. Nestloop and
3323  * merge joins can *preserve* the order of their inputs, so they can be
3324  * selected as the input of a mergejoin, and they don't support
3325  * mark/restore at present.
3326  *
3327  * We don't test the value of enable_material here, because
3328  * materialization is required for correctness in this case, and turning
3329  * it off does not entitle us to deliver an invalid plan.
3330  */
3331  else if (innersortkeys == NIL &&
3332  !ExecSupportsMarkRestore(inner_path))
3333  path->materialize_inner = true;
3334 
3335  /*
3336  * Also, force materializing if the inner path is to be sorted and the
3337  * sort is expected to spill to disk. This is because the final merge
3338  * pass can be done on-the-fly if it doesn't have to support mark/restore.
3339  * We don't try to adjust the cost estimates for this consideration,
3340  * though.
3341  *
3342  * Since materialization is a performance optimization in this case,
3343  * rather than necessary for correctness, we skip it if enable_material is
3344  * off.
3345  */
3346  else if (enable_material && innersortkeys != NIL &&
3347  relation_byte_size(inner_path_rows,
3348  inner_path->pathtarget->width) >
3349  (work_mem * 1024L))
3350  path->materialize_inner = true;
3351  else
3352  path->materialize_inner = false;
3353 
3354  /* Charge the right incremental cost for the chosen case */
3355  if (path->materialize_inner)
3356  run_cost += mat_inner_cost;
3357  else
3358  run_cost += bare_inner_cost;
3359 
3360  /* CPU costs */
3361 
3362  /*
3363  * The number of tuple comparisons needed is approximately number of outer
3364  * rows plus number of inner rows plus number of rescanned tuples (can we
3365  * refine this?). At each one, we need to evaluate the mergejoin quals.
3366  */
3367  startup_cost += merge_qual_cost.startup;
3368  startup_cost += merge_qual_cost.per_tuple *
3369  (outer_skip_rows + inner_skip_rows * rescanratio);
3370  run_cost += merge_qual_cost.per_tuple *
3371  ((outer_rows - outer_skip_rows) +
3372  (inner_rows - inner_skip_rows) * rescanratio);
3373 
3374  /*
3375  * For each tuple that gets through the mergejoin proper, we charge
3376  * cpu_tuple_cost plus the cost of evaluating additional restriction
3377  * clauses that are to be applied at the join. (This is pessimistic since
3378  * not all of the quals may get evaluated at each tuple.)
3379  *
3380  * Note: we could adjust for SEMI/ANTI joins skipping some qual
3381  * evaluations here, but it's probably not worth the trouble.
3382  */
3383  startup_cost += qp_qual_cost.startup;
3384  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3385  run_cost += cpu_per_tuple * mergejointuples;
3386 
3387  /* tlist eval costs are paid per output row, not per tuple scanned */
3388  startup_cost += path->jpath.path.pathtarget->cost.startup;
3389  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3390 
3391  path->jpath.path.startup_cost = startup_cost;
3392  path->jpath.path.total_cost = startup_cost + run_cost;
3393 }
#define NIL
Definition: pg_list.h:65
List * path_mergeclauses
Definition: pathnodes.h:1581
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
PathTarget * pathtarget
Definition: pathnodes.h:1145
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:409
bool materialize_inner
Definition: pathnodes.h:1585
Path * innerjoinpath
Definition: pathnodes.h:1526
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4572
int parallel_workers
Definition: pathnodes.h:1151
ParamPathInfo * param_info
Definition: pathnodes.h:1147
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
bool skip_mark_restore
Definition: pathnodes.h:1584
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4043
Cost startup_cost
Definition: pathnodes.h:1155
Cost disable_cost
Definition: costsize.c:121
List * joinrestrictinfo
Definition: pathnodes.h:1528
RelOptInfo * parent
Definition: pathnodes.h:1144
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5699
double cpu_operator_cost
Definition: costsize.c:115
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5678
Path * outerjoinpath
Definition: pathnodes.h:1525
int work_mem
Definition: globals.c:121
double rows
Definition: pathnodes.h:668
Cost total_cost
Definition: pathnodes.h:1156
double outer_skip_rows
Definition: pathnodes.h:2543
bool enable_mergejoin
Definition: costsize.c:135
Path path
Definition: pathnodes.h:1518
double rows
Definition: pathnodes.h:1154
QualCost cost
Definition: pathnodes.h:1076
static int list_length(const List *l)
Definition: pg_list.h:169
List * innersortkeys
Definition: pathnodes.h:1583
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: pathnodes.h:1104
JoinType jointype
Definition: pathnodes.h:1520
JoinPath jpath
Definition: pathnodes.h:1580
double inner_skip_rows
Definition: pathnodes.h:2544
double clamp_row_est(double nrows)
Definition: costsize.c:189
Definition: pg_list.h:50
double Cost
Definition: nodes.h:663
bool enable_material
Definition: costsize.c:134

◆ final_cost_nestloop()

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

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

2716 {
2717  Path *outer_path = path->outerjoinpath;
2718  Path *inner_path = path->innerjoinpath;
2719  double outer_path_rows = outer_path->rows;
2720  double inner_path_rows = inner_path->rows;
2721  Cost startup_cost = workspace->startup_cost;
2722  Cost run_cost = workspace->run_cost;
2723  Cost cpu_per_tuple;
2724  QualCost restrict_qual_cost;
2725  double ntuples;
2726 
2727  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2728  if (outer_path_rows <= 0 || isnan(outer_path_rows))
2729  outer_path_rows = 1;
2730  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2731  inner_path_rows = 1;
2732 
2733  /* Mark the path with the correct row estimate */
2734  if (path->path.param_info)
2735  path->path.rows = path->path.param_info->ppi_rows;
2736  else
2737  path->path.rows = path->path.parent->rows;
2738 
2739  /* For partial paths, scale row estimate. */
2740  if (path->path.parallel_workers > 0)
2741  {
2742  double parallel_divisor = get_parallel_divisor(&path->path);
2743 
2744  path->path.rows =
2745  clamp_row_est(path->path.rows / parallel_divisor);
2746  }
2747 
2748  /*
2749  * We could include disable_cost in the preliminary estimate, but that
2750  * would amount to optimizing for the case where the join method is
2751  * disabled, which doesn't seem like the way to bet.
2752  */
2753  if (!enable_nestloop)
2754  startup_cost += disable_cost;
2755 
2756  /* cost of inner-relation source data (we already dealt with outer rel) */
2757 
2758  if (path->jointype == JOIN_SEMI || path->jointype == JOIN_ANTI ||
2759  extra->inner_unique)
2760  {
2761  /*
2762  * With a SEMI or ANTI join, or if the innerrel is known unique, the
2763  * executor will stop after the first match.
2764  */
2765  Cost inner_run_cost = workspace->inner_run_cost;
2766  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
2767  double outer_matched_rows;
2768  double outer_unmatched_rows;
2769  Selectivity inner_scan_frac;
2770 
2771  /*
2772  * For an outer-rel row that has at least one match, we can expect the
2773  * inner scan to stop after a fraction 1/(match_count+1) of the inner
2774  * rows, if the matches are evenly distributed. Since they probably
2775  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
2776  * that fraction. (If we used a larger fuzz factor, we'd have to
2777  * clamp inner_scan_frac to at most 1.0; but since match_count is at
2778  * least 1, no such clamp is needed now.)
2779  */
2780  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
2781  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
2782  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
2783 
2784  /*
2785  * Compute number of tuples processed (not number emitted!). First,
2786  * account for successfully-matched outer rows.
2787  */
2788  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
2789 
2790  /*
2791  * Now we need to estimate the actual costs of scanning the inner
2792  * relation, which may be quite a bit less than N times inner_run_cost
2793  * due to early scan stops. We consider two cases. If the inner path
2794  * is an indexscan using all the joinquals as indexquals, then an
2795  * unmatched outer row results in an indexscan returning no rows,
2796  * which is probably quite cheap. Otherwise, the executor will have
2797  * to scan the whole inner rel for an unmatched row; not so cheap.
2798  */
2799  if (has_indexed_join_quals(path))
2800  {
2801  /*
2802  * Successfully-matched outer rows will only require scanning
2803  * inner_scan_frac of the inner relation. In this case, we don't
2804  * need to charge the full inner_run_cost even when that's more
2805  * than inner_rescan_run_cost, because we can assume that none of
2806  * the inner scans ever scan the whole inner relation. So it's
2807  * okay to assume that all the inner scan executions can be
2808  * fractions of the full cost, even if materialization is reducing
2809  * the rescan cost. At this writing, it's impossible to get here
2810  * for a materialized inner scan, so inner_run_cost and
2811  * inner_rescan_run_cost will be the same anyway; but just in
2812  * case, use inner_run_cost for the first matched tuple and
2813  * inner_rescan_run_cost for additional ones.
2814  */
2815  run_cost += inner_run_cost * inner_scan_frac;
2816  if (outer_matched_rows > 1)
2817  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
2818 
2819  /*
2820  * Add the cost of inner-scan executions for unmatched outer rows.
2821  * We estimate this as the same cost as returning the first tuple
2822  * of a nonempty scan. We consider that these are all rescans,
2823  * since we used inner_run_cost once already.
2824  */
2825  run_cost += outer_unmatched_rows *
2826  inner_rescan_run_cost / inner_path_rows;
2827 
2828  /*
2829  * We won't be evaluating any quals at all for unmatched rows, so
2830  * don't add them to ntuples.
2831  */
2832  }
2833  else
2834  {
2835  /*
2836  * Here, a complicating factor is that rescans may be cheaper than
2837  * first scans. If we never scan all the way to the end of the
2838  * inner rel, it might be (depending on the plan type) that we'd
2839  * never pay the whole inner first-scan run cost. However it is
2840  * difficult to estimate whether that will happen (and it could
2841  * not happen if there are any unmatched outer rows!), so be
2842  * conservative and always charge the whole first-scan cost once.
2843  * We consider this charge to correspond to the first unmatched
2844  * outer row, unless there isn't one in our estimate, in which
2845  * case blame it on the first matched row.
2846  */
2847 
2848  /* First, count all unmatched join tuples as being processed */
2849  ntuples += outer_unmatched_rows * inner_path_rows;
2850 
2851  /* Now add the forced full scan, and decrement appropriate count */
2852  run_cost += inner_run_cost;
2853  if (outer_unmatched_rows >= 1)
2854  outer_unmatched_rows -= 1;
2855  else
2856  outer_matched_rows -= 1;
2857 
2858  /* Add inner run cost for additional outer tuples having matches */
2859  if (outer_matched_rows > 0)
2860  run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
2861 
2862  /* Add inner run cost for additional unmatched outer tuples */
2863  if (outer_unmatched_rows > 0)
2864  run_cost += outer_unmatched_rows * inner_rescan_run_cost;
2865  }
2866  }
2867  else
2868  {
2869  /* Normal-case source costs were included in preliminary estimate */
2870 
2871  /* Compute number of tuples processed (not number emitted!) */
2872  ntuples = outer_path_rows * inner_path_rows;
2873  }
2874 
2875  /* CPU costs */
2876  cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
2877  startup_cost += restrict_qual_cost.startup;
2878  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
2879  run_cost += cpu_per_tuple * ntuples;
2880 
2881  /* tlist eval costs are paid per output row, not per tuple scanned */
2882  startup_cost += path->path.pathtarget->cost.startup;
2883  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
2884 
2885  path->path.startup_cost = startup_cost;
2886  path->path.total_cost = startup_cost + run_cost;
2887 }
PathTarget * pathtarget
Definition: pathnodes.h:1145
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:2428
bool enable_nestloop
Definition: costsize.c:133
Selectivity outer_match_frac
Definition: pathnodes.h:2405
Path * innerjoinpath
Definition: pathnodes.h:1526
int parallel_workers
Definition: pathnodes.h:1151
ParamPathInfo * param_info
Definition: pathnodes.h:1147
double Selectivity
Definition: nodes.h:662
Cost inner_rescan_run_cost
Definition: pathnodes.h:2538
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:4043
Cost startup_cost
Definition: pathnodes.h:1155
Cost disable_cost
Definition: costsize.c:121
List * joinrestrictinfo
Definition: pathnodes.h:1528
RelOptInfo * parent
Definition: pathnodes.h:1144
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5699
Path * outerjoinpath
Definition: pathnodes.h:1525
double rows
Definition: pathnodes.h:668
Cost total_cost
Definition: pathnodes.h:1156
Path path
Definition: pathnodes.h:1518
static bool has_indexed_join_quals(NestPath *joinpath)
Definition: costsize.c:4480
double rows
Definition: pathnodes.h:1154
QualCost cost
Definition: pathnodes.h:1076
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: pathnodes.h:1104
Selectivity match_count
Definition: pathnodes.h:2406
JoinType jointype
Definition: pathnodes.h:1520
double clamp_row_est(double nrows)
Definition: costsize.c:189
double Cost
Definition: nodes.h:663

◆ get_parameterized_baserel_size()

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

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

4660 {
4661  List *allclauses;
4662  double nrows;
4663 
4664  /*
4665  * Estimate the number of rows returned by the parameterized scan, knowing
4666  * that it will apply all the extra join clauses as well as the rel's own
4667  * restriction clauses. Note that we force the clauses to be treated as
4668  * non-join clauses during selectivity estimation.
4669  */
4670  allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
4671  nrows = rel->tuples *
4673  allclauses,
4674  rel->relid, /* do not use 0! */
4675  JOIN_INNER,
4676  NULL);
4677  nrows = clamp_row_est(nrows);
4678  /* For safety, make sure result is not more than the base estimate */
4679  if (nrows > rel->rows)
4680  nrows = rel->rows;
4681  return nrows;
4682 }
double tuples
Definition: pathnodes.h:705
List * baserestrictinfo
Definition: pathnodes.h:727
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:552
Index relid
Definition: pathnodes.h:693
double rows
Definition: pathnodes.h:668
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:189
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 4739 of file costsize.c.

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

Referenced by get_joinrel_parampathinfo().

4744 {
4745  double nrows;
4746 
4747  /*
4748  * Estimate the number of rows returned by the parameterized join as the
4749  * sizes of the input paths times the selectivity of the clauses that have
4750  * ended up at this join node.
4751  *
4752  * As with set_joinrel_size_estimates, the rowcount estimate could depend
4753  * on the pair of input paths provided, though ideally we'd get the same
4754  * estimate for any pair with the same parameterization.
4755  */
4756  nrows = calc_joinrel_size_estimate(root,
4757  rel,
4758  outer_path->parent,
4759  inner_path->parent,
4760  outer_path->rows,
4761  inner_path->rows,
4762  sjinfo,
4763  restrict_clauses);
4764  /* For safety, make sure result is not more than the base estimate */
4765  if (nrows > rel->rows)
4766  nrows = rel->rows;
4767  return nrows;
4768 }
RelOptInfo * parent
Definition: pathnodes.h:1144
double rows
Definition: pathnodes.h:668
double rows
Definition: pathnodes.h:1154
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:4780

◆ index_pages_fetched()

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

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

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

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

3484 {
3485  Cost startup_cost = 0;
3486  Cost run_cost = 0;
3487  double outer_path_rows = outer_path->rows;
3488  double inner_path_rows = inner_path->rows;
3489  double inner_path_rows_total = inner_path_rows;
3490  int num_hashclauses = list_length(hashclauses);
3491  int numbuckets;
3492  int numbatches;
3493  int num_skew_mcvs;
3494  size_t space_allowed; /* unused */
3495 
3496  /* cost of source data */
3497  startup_cost += outer_path->startup_cost;
3498  run_cost += outer_path->total_cost - outer_path->startup_cost;
3499  startup_cost += inner_path->total_cost;
3500 
3501  /*
3502  * Cost of computing hash function: must do it once per input tuple. We
3503  * charge one cpu_operator_cost for each column's hash function. Also,
3504  * tack on one cpu_tuple_cost per inner row, to model the costs of
3505  * inserting the row into the hashtable.
3506  *
3507  * XXX when a hashclause is more complex than a single operator, we really
3508  * should charge the extra eval costs of the left or right side, as
3509  * appropriate, here. This seems more work than it's worth at the moment.
3510  */
3511  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
3512  * inner_path_rows;
3513  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
3514 
3515  /*
3516  * If this is a parallel hash build, then the value we have for
3517  * inner_rows_total currently refers only to the rows returned by each
3518  * participant. For shared hash table size estimation, we need the total
3519  * number, so we need to undo the division.
3520  */
3521  if (parallel_hash)
3522  inner_path_rows_total *= get_parallel_divisor(inner_path);
3523 
3524  /*
3525  * Get hash table size that executor would use for inner relation.
3526  *
3527  * XXX for the moment, always assume that skew optimization will be
3528  * performed. As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
3529  * trying to determine that for sure.
3530  *
3531  * XXX at some point it might be interesting to try to account for skew
3532  * optimization in the cost estimate, but for now, we don't.
3533  */
3534  ExecChooseHashTableSize(inner_path_rows_total,
3535  inner_path->pathtarget->width,
3536  true, /* useskew */
3537  parallel_hash, /* try_combined_hash_mem */
3538  outer_path->parallel_workers,
3539  &space_allowed,
3540  &numbuckets,
3541  &numbatches,
3542  &num_skew_mcvs);
3543 
3544  /*
3545  * If inner relation is too big then we will need to "batch" the join,
3546  * which implies writing and reading most of the tuples to disk an extra
3547  * time. Charge seq_page_cost per page, since the I/O should be nice and
3548  * sequential. Writing the inner rel counts as startup cost, all the rest
3549  * as run cost.
3550  */
3551  if (numbatches > 1)
3552  {
3553  double outerpages = page_size(outer_path_rows,
3554  outer_path->pathtarget->width);
3555  double innerpages = page_size(inner_path_rows,
3556  inner_path->pathtarget->width);
3557 
3558  startup_cost += seq_page_cost * innerpages;
3559  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
3560  }
3561 
3562  /* CPU costs left for later */
3563 
3564  /* Public result fields */
3565  workspace->startup_cost = startup_cost;
3566  workspace->total_cost = startup_cost + run_cost;
3567  /* Save private data for final_cost_hashjoin */
3568  workspace->run_cost = run_cost;
3569  workspace->numbuckets = numbuckets;
3570  workspace->numbatches = numbatches;
3571  workspace->inner_rows_total = inner_path_rows_total;
3572 }
PathTarget * pathtarget
Definition: pathnodes.h:1145
int parallel_workers
Definition: pathnodes.h:1151
static double page_size(double tuples, int width)
Definition: costsize.c:5689
Cost startup_cost
Definition: pathnodes.h:1155
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5699
double cpu_operator_cost
Definition: costsize.c:115
double inner_rows_total
Definition: pathnodes.h:2549
Cost total_cost
Definition: pathnodes.h:1156
void ExecChooseHashTableSize(double ntuples, int tupwidth, bool useskew, bool try_combined_hash_mem, int parallel_workers, size_t *space_allowed, int *numbuckets, int *numbatches, int *num_skew_mcvs)
Definition: nodeHash.c:668
double rows
Definition: pathnodes.h:1154
static int list_length(const List *l)
Definition: pg_list.h:169
double cpu_tuple_cost
Definition: costsize.c:113
double seq_page_cost
Definition: costsize.c:111
double Cost
Definition: nodes.h:663

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

2926 {
2927  Cost startup_cost = 0;
2928  Cost run_cost = 0;
2929  double outer_path_rows = outer_path->rows;
2930  double inner_path_rows = inner_path->rows;
2931  Cost inner_run_cost;
2932  double outer_rows,
2933  inner_rows,
2934  outer_skip_rows,
2935  inner_skip_rows;
2936  Selectivity outerstartsel,
2937  outerendsel,
2938  innerstartsel,
2939  innerendsel;
2940  Path sort_path; /* dummy for result of cost_sort */
2941 
2942  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2943  if (outer_path_rows <= 0 || isnan(outer_path_rows))
2944  outer_path_rows = 1;
2945  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2946  inner_path_rows = 1;
2947 
2948  /*
2949  * A merge join will stop as soon as it exhausts either input stream
2950  * (unless it's an outer join, in which case the outer side has to be
2951  * scanned all the way anyway). Estimate fraction of the left and right
2952  * inputs that will actually need to be scanned. Likewise, we can
2953  * estimate the number of rows that will be skipped before the first join
2954  * pair is found, which should be factored into startup cost. We use only
2955  * the first (most significant) merge clause for this purpose. Since
2956  * mergejoinscansel() is a fairly expensive computation, we cache the
2957  * results in the merge clause RestrictInfo.
2958  */
2959  if (mergeclauses && jointype != JOIN_FULL)
2960  {
2961  RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
2962  List *opathkeys;
2963  List *ipathkeys;
2964  PathKey *opathkey;
2965  PathKey *ipathkey;
2966  MergeScanSelCache *cache;
2967 
2968  /* Get the input pathkeys to determine the sort-order details */
2969  opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
2970  ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
2971  Assert(opathkeys);
2972  Assert(ipathkeys);
2973  opathkey = (PathKey *) linitial(opathkeys);
2974  ipathkey = (PathKey *) linitial(ipathkeys);
2975  /* debugging check */
2976  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
2977  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
2978  opathkey->pk_strategy != ipathkey->pk_strategy ||
2979  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
2980  elog(ERROR, "left and right pathkeys do not match in mergejoin");
2981 
2982  /* Get the selectivity with caching */
2983  cache = cached_scansel(root, firstclause, opathkey);
2984 
2985  if (bms_is_subset(firstclause->left_relids,
2986  outer_path->parent->relids))
2987  {
2988  /* left side of clause is outer */
2989  outerstartsel = cache->leftstartsel;
2990  outerendsel = cache->leftendsel;
2991  innerstartsel = cache->rightstartsel;
2992  innerendsel = cache->rightendsel;
2993  }
2994  else
2995  {
2996  /* left side of clause is inner */
2997  outerstartsel = cache->rightstartsel;
2998  outerendsel = cache->rightendsel;
2999  innerstartsel = cache->leftstartsel;
3000  innerendsel = cache->leftendsel;
3001  }
3002  if (jointype == JOIN_LEFT ||
3003  jointype == JOIN_ANTI)
3004  {
3005  outerstartsel = 0.0;
3006  outerendsel = 1.0;
3007  }
3008  else if (jointype == JOIN_RIGHT)
3009  {
3010  innerstartsel = 0.0;
3011  innerendsel = 1.0;
3012  }
3013  }
3014  else
3015  {
3016  /* cope with clauseless or full mergejoin */
3017  outerstartsel = innerstartsel = 0.0;
3018  outerendsel = innerendsel = 1.0;
3019  }
3020 
3021  /*
3022  * Convert selectivities to row counts. We force outer_rows and
3023  * inner_rows to be at least 1, but the skip_rows estimates can be zero.
3024  */
3025  outer_skip_rows = rint(outer_path_rows * outerstartsel);
3026  inner_skip_rows = rint(inner_path_rows * innerstartsel);
3027  outer_rows = clamp_row_est(outer_path_rows * outerendsel);
3028  inner_rows = clamp_row_est(inner_path_rows * innerendsel);
3029 
3030  Assert(outer_skip_rows <= outer_rows);
3031  Assert(inner_skip_rows <= inner_rows);
3032 
3033  /*
3034  * Readjust scan selectivities to account for above rounding. This is
3035  * normally an insignificant effect, but when there are only a few rows in
3036  * the inputs, failing to do this makes for a large percentage error.
3037  */
3038  outerstartsel = outer_skip_rows / outer_path_rows;
3039  innerstartsel = inner_skip_rows / inner_path_rows;
3040  outerendsel = outer_rows / outer_path_rows;
3041  innerendsel = inner_rows / inner_path_rows;
3042 
3043  Assert(outerstartsel <= outerendsel);
3044  Assert(innerstartsel <= innerendsel);
3045 
3046  /* cost of source data */
3047 
3048  if (outersortkeys) /* do we need to sort outer? */
3049  {
3050  cost_sort(&sort_path,
3051  root,
3052  outersortkeys,
3053  outer_path->total_cost,
3054  outer_path_rows,
3055  outer_path->pathtarget->width,
3056  0.0,
3057  work_mem,
3058  -1.0);
3059  startup_cost += sort_path.startup_cost;
3060  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3061  * outerstartsel;
3062  run_cost += (sort_path.total_cost - sort_path.startup_cost)
3063  * (outerendsel - outerstartsel);
3064  }
3065  else
3066  {
3067  startup_cost += outer_path->startup_cost;
3068  startup_cost += (outer_path->total_cost - outer_path->startup_cost)
3069  * outerstartsel;
3070  run_cost += (outer_path->total_cost - outer_path->startup_cost)
3071  * (outerendsel - outerstartsel);
3072  }
3073 
3074  if (innersortkeys) /* do we need to sort inner? */
3075  {
3076  cost_sort(&sort_path,
3077  root,
3078  innersortkeys,
3079  inner_path->total_cost,
3080  inner_path_rows,
3081  inner_path->pathtarget->width,
3082  0.0,
3083  work_mem,
3084  -1.0);
3085  startup_cost += sort_path.startup_cost;
3086  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3087  * innerstartsel;
3088  inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
3089  * (innerendsel - innerstartsel);
3090  }
3091  else
3092  {
3093  startup_cost += inner_path->startup_cost;
3094  startup_cost += (inner_path->total_cost - inner_path->startup_cost)
3095  * innerstartsel;
3096  inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
3097  * (innerendsel - innerstartsel);
3098  }
3099 
3100  /*
3101  * We can't yet determine whether rescanning occurs, or whether
3102  * materialization of the inner input should be done. The minimum
3103  * possible inner input cost, regardless of rescan and materialization
3104  * considerations, is inner_run_cost. We include that in
3105  * workspace->total_cost, but not yet in run_cost.
3106  */
3107 
3108  /* CPU costs left for later */
3109 
3110  /* Public result fields */
3111  workspace->startup_cost = startup_cost;
3112  workspace->total_cost = startup_cost + run_cost + inner_run_cost;
3113  /* Save private data for final_cost_mergejoin */
3114  workspace->run_cost = run_cost;
3115  workspace->inner_run_cost = inner_run_cost;
3116  workspace->outer_rows = outer_rows;
3117  workspace->inner_rows = inner_rows;
3118  workspace->outer_skip_rows = outer_skip_rows;
3119  workspace->inner_skip_rows = inner_skip_rows;
3120 }
Selectivity leftendsel
Definition: pathnodes.h:2082
PathTarget * pathtarget
Definition: pathnodes.h:1145
static MergeScanSelCache * cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
Definition: costsize.c:3399
Relids left_relids
Definition: pathnodes.h:2012
double Selectivity
Definition: nodes.h:662
int pk_strategy
Definition: pathnodes.h:1043
#define linitial(l)
Definition: pg_list.h:195
bool pk_nulls_first
Definition: pathnodes.h:1044
#define ERROR
Definition: elog.h:43
Cost startup_cost
Definition: pathnodes.h:1155
RelOptInfo * parent
Definition: pathnodes.h:1144
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
Selectivity rightstartsel
Definition: pathnodes.h:2083
Relids relids
Definition: pathnodes.h:665
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:1927
int work_mem
Definition: globals.c:121
Cost total_cost
Definition: pathnodes.h:1156
double outer_skip_rows
Definition: pathnodes.h:2543
List * pathkeys
Definition: pathnodes.h:1158
#define Assert(condition)
Definition: c.h:745
double rows
Definition: pathnodes.h:1154
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1041
Oid pk_opfamily
Definition: pathnodes.h:1042
#define elog(elevel,...)
Definition: elog.h:214
double inner_skip_rows
Definition: pathnodes.h:2544
double clamp_row_est(double nrows)
Definition: costsize.c:189
Definition: pg_list.h:50
Selectivity rightendsel
Definition: pathnodes.h:2084
double Cost
Definition: nodes.h:663
Selectivity leftstartsel
Definition: pathnodes.h:2081

◆ initial_cost_nestloop()

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

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

2642 {
2643  Cost startup_cost = 0;
2644  Cost run_cost = 0;
2645  double outer_path_rows = outer_path->rows;
2646  Cost inner_rescan_start_cost;
2647  Cost inner_rescan_total_cost;
2648  Cost inner_run_cost;
2649  Cost inner_rescan_run_cost;
2650 
2651  /* estimate costs to rescan the inner relation */
2652  cost_rescan(root, inner_path,
2653  &inner_rescan_start_cost,
2654  &inner_rescan_total_cost);
2655 
2656  /* cost of source data */
2657 
2658  /*
2659  * NOTE: clearly, we must pay both outer and inner paths' startup_cost
2660  * before we can start returning tuples, so the join's startup cost is
2661  * their sum. We'll also pay the inner path's rescan startup cost
2662  * multiple times.
2663  */
2664  startup_cost += outer_path->startup_cost + inner_path->startup_cost;
2665  run_cost += outer_path->total_cost - outer_path->startup_cost;
2666  if (outer_path_rows > 1)
2667  run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
2668 
2669  inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
2670  inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
2671 
2672  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
2673  extra->inner_unique)
2674  {
2675  /*
2676  * With a SEMI or ANTI join, or if the innerrel is known unique, the
2677  * executor will stop after the first match.
2678  *
2679  * Getting decent estimates requires inspection of the join quals,
2680  * which we choose to postpone to final_cost_nestloop.
2681  */
2682 
2683  /* Save private data for final_cost_nestloop */
2684  workspace->inner_run_cost = inner_run_cost;
2685  workspace->inner_rescan_run_cost = inner_rescan_run_cost;
2686  }
2687  else
2688  {
2689  /* Normal case; we'll scan whole input rel for each outer row */
2690  run_cost += inner_run_cost;
2691  if (outer_path_rows > 1)
2692  run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
2693  }
2694 
2695  /* CPU costs left for later */
2696 
2697  /* Public result fields */
2698  workspace->startup_cost = startup_cost;
2699  workspace->total_cost = startup_cost + run_cost;
2700  /* Save private data for final_cost_nestloop */
2701  workspace->run_cost = run_cost;
2702 }
static void cost_rescan(PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:3936
Cost inner_rescan_run_cost
Definition: pathnodes.h:2538
Cost startup_cost
Definition: pathnodes.h:1155
Cost total_cost
Definition: pathnodes.h:1156
double rows
Definition: pathnodes.h:1154
double Cost
Definition: nodes.h:663

◆ set_baserel_size_estimates()

void set_baserel_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

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

4629 {
4630  double nrows;
4631 
4632  /* Should only be applied to base relations */
4633  Assert(rel->relid > 0);
4634 
4635  nrows = rel->tuples *
4637  rel->baserestrictinfo,
4638  0,
4639  JOIN_INNER,
4640  NULL);
4641 
4642  rel->rows = clamp_row_est(nrows);
4643 
4645 
4646  set_rel_width(root, rel);
4647 }
double tuples
Definition: pathnodes.h:705
List * baserestrictinfo
Definition: pathnodes.h:727
static void set_rel_width(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5442
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4043
Index relid
Definition: pathnodes.h:693
double rows
Definition: pathnodes.h:668
#define Assert(condition)
Definition: c.h:745
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:189
QualCost baserestrictcost
Definition: pathnodes.h:728

◆ set_cte_size_estimates()

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

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

5309 {
5310  RangeTblEntry *rte;
5311 
5312  /* Should only be applied to base relations that are CTE references */
5313  Assert(rel->relid > 0);
5314  rte = planner_rt_fetch(rel->relid, root);
5315  Assert(rte->rtekind == RTE_CTE);
5316 
5317  if (rte->self_reference)
5318  {
5319  /*
5320  * In a self-reference, arbitrarily assume the average worktable size
5321  * is about 10 times the nonrecursive term's size.
5322  */
5323  rel->tuples = 10 * cte_rows;
5324  }
5325  else
5326  {
5327  /* Otherwise just believe the CTE's rowcount estimate */
5328  rel->tuples = cte_rows;
5329  }
5330 
5331  /* Now estimate number of output rows, etc */
5332  set_baserel_size_estimates(root, rel);
5333 }
double tuples
Definition: pathnodes.h:705
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:373
Index relid
Definition: pathnodes.h:693
bool self_reference
Definition: parsenodes.h:1081
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4628
#define Assert(condition)
Definition: c.h:745
RTEKind rtekind
Definition: