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_tidrangescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidrangequals, 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 5897 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().

5899 {
5900  Cost indexTotalCost;
5901  Selectivity indexSelectivity;
5902  double T;
5903  double pages_fetched;
5904  double tuples_fetched;
5905  double heap_pages;
5906  long maxentries;
5907 
5908  /*
5909  * Fetch total cost of obtaining the bitmap, as well as its total
5910  * selectivity.
5911  */
5912  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
5913 
5914  /*
5915  * Estimate number of main-table pages fetched.
5916  */
5917  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
5918 
5919  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
5920 
5921  /*
5922  * For a single scan, the number of heap pages that need to be fetched is
5923  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
5924  * re-reads needed).
5925  */
5926  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
5927 
5928  /*
5929  * Calculate the number of pages fetched from the heap. Then based on
5930  * current work_mem estimate get the estimated maxentries in the bitmap.
5931  * (Note that we always do this calculation based on the number of pages
5932  * that would be fetched in a single iteration, even if loop_count > 1.
5933  * That's correct, because only that number of entries will be stored in
5934  * the bitmap at one time.)
5935  */
5936  heap_pages = Min(pages_fetched, baserel->pages);
5937  maxentries = tbm_calculate_entries(work_mem * 1024L);
5938 
5939  if (loop_count > 1)
5940  {
5941  /*
5942  * For repeated bitmap scans, scale up the number of tuples fetched in
5943  * the Mackert and Lohman formula by the number of scans, so that we
5944  * estimate the number of pages fetched by all the scans. Then
5945  * pro-rate for one scan.
5946  */
5947  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
5948  baserel->pages,
5949  get_indexpath_pages(bitmapqual),
5950  root);
5951  pages_fetched /= loop_count;
5952  }
5953 
5954  if (pages_fetched >= T)
5955  pages_fetched = T;
5956  else
5957  pages_fetched = ceil(pages_fetched);
5958 
5959  if (maxentries < heap_pages)
5960  {
5961  double exact_pages;
5962  double lossy_pages;
5963 
5964  /*
5965  * Crude approximation of the number of lossy pages. Because of the
5966  * way tbm_lossify() is coded, the number of lossy pages increases
5967  * very sharply as soon as we run short of memory; this formula has
5968  * that property and seems to perform adequately in testing, but it's
5969  * possible we could do better somehow.
5970  */
5971  lossy_pages = Max(0, heap_pages - maxentries / 2);
5972  exact_pages = heap_pages - lossy_pages;
5973 
5974  /*
5975  * If there are lossy pages then recompute the number of tuples
5976  * processed by the bitmap heap node. We assume here that the chance
5977  * of a given tuple coming from an exact page is the same as the
5978  * chance that a given page is exact. This might not be true, but
5979  * it's not clear how we can do any better.
5980  */
5981  if (lossy_pages > 0)
5982  tuples_fetched =
5983  clamp_row_est(indexSelectivity *
5984  (exact_pages / heap_pages) * baserel->tuples +
5985  (lossy_pages / heap_pages) * baserel->tuples);
5986  }
5987 
5988  if (cost)
5989  *cost = indexTotalCost;
5990  if (tuple)
5991  *tuple = tuples_fetched;
5992 
5993  return pages_fetched;
5994 }
double tuples
Definition: pathnodes.h:710
#define Min(x, y)
Definition: c.h:986
double Selectivity
Definition: nodes.h:666
int work_mem
Definition: globals.c:122
#define Max(x, y)
Definition: c.h:980
static const uint32 T[65]
Definition: md5.c:119
BlockNumber pages
Definition: pathnodes.h:709
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:902
long tbm_calculate_entries(double maxbytes)
Definition: tidbitmap.c:1545
double clamp_row_est(double nrows)
Definition: costsize.c:196
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:837
double Cost
Definition: nodes.h:667
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1053

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

4497 {
4498  Selectivity jselec;
4499  Selectivity nselec;
4500  Selectivity avgmatch;
4501  SpecialJoinInfo norm_sjinfo;
4502  List *joinquals;
4503  ListCell *l;
4504 
4505  /*
4506  * In an ANTI join, we must ignore clauses that are "pushed down", since
4507  * those won't affect the match logic. In a SEMI join, we do not
4508  * distinguish joinquals from "pushed down" quals, so just use the whole
4509  * restrictinfo list. For other outer join types, we should consider only
4510  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
4511  */
4512  if (IS_OUTER_JOIN(jointype))
4513  {
4514  joinquals = NIL;
4515  foreach(l, restrictlist)
4516  {
4517  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4518 
4519  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
4520  joinquals = lappend(joinquals, rinfo);
4521  }
4522  }
4523  else
4524  joinquals = restrictlist;
4525 
4526  /*
4527  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
4528  */
4529  jselec = clauselist_selectivity(root,
4530  joinquals,
4531  0,
4532  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
4533  sjinfo);
4534 
4535  /*
4536  * Also get the normal inner-join selectivity of the join clauses.
4537  */
4538  norm_sjinfo.type = T_SpecialJoinInfo;
4539  norm_sjinfo.min_lefthand = outerrel->relids;
4540  norm_sjinfo.min_righthand = innerrel->relids;
4541  norm_sjinfo.syn_lefthand = outerrel->relids;
4542  norm_sjinfo.syn_righthand = innerrel->relids;
4543  norm_sjinfo.jointype = JOIN_INNER;
4544  /* we don't bother trying to make the remaining fields valid */
4545  norm_sjinfo.lhs_strict = false;
4546  norm_sjinfo.delay_upper_joins = false;
4547  norm_sjinfo.semi_can_btree = false;
4548  norm_sjinfo.semi_can_hash = false;
4549  norm_sjinfo.semi_operators = NIL;
4550  norm_sjinfo.semi_rhs_exprs = NIL;
4551 
4552  nselec = clauselist_selectivity(root,
4553  joinquals,
4554  0,
4555  JOIN_INNER,
4556  &norm_sjinfo);
4557 
4558  /* Avoid leaking a lot of ListCells */
4559  if (IS_OUTER_JOIN(jointype))
4560  list_free(joinquals);
4561 
4562  /*
4563  * jselec can be interpreted as the fraction of outer-rel rows that have
4564  * any matches (this is true for both SEMI and ANTI cases). And nselec is
4565  * the fraction of the Cartesian product that matches. So, the average
4566  * number of matches for each outer-rel row that has at least one match is
4567  * nselec * inner_rows / jselec.
4568  *
4569  * Note: it is correct to use the inner rel's "rows" count here, even
4570  * though we might later be considering a parameterized inner path with
4571  * fewer rows. This is because we have included all the join clauses in
4572  * the selectivity estimate.
4573  */
4574  if (jselec > 0) /* protect against zero divide */
4575  {
4576  avgmatch = nselec * innerrel->rows / jselec;
4577  /* Clamp to sane range */
4578  avgmatch = Max(1.0, avgmatch);
4579  }
4580  else
4581  avgmatch = 1.0;
4582 
4583  semifactors->outer_match_frac = jselec;
4584  semifactors->match_count = avgmatch;
4585 }
#define NIL
Definition: pg_list.h:65
Relids min_righthand
Definition: pathnodes.h:2197
Selectivity outer_match_frac
Definition: pathnodes.h:2426
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:749
double Selectivity
Definition: nodes.h:666
Relids syn_lefthand
Definition: pathnodes.h:2198
Relids syn_righthand
Definition: pathnodes.h:2199
List * semi_rhs_exprs
Definition: pathnodes.h:2207
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Relids relids
Definition: pathnodes.h:670
List * lappend(List *list, void *datum)
Definition: list.c:336
bool delay_upper_joins
Definition: pathnodes.h:2202
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2083
double rows
Definition: pathnodes.h:673
#define Max(x, y)
Definition: c.h:980
JoinType jointype
Definition: pathnodes.h:2200
Selectivity match_count
Definition: pathnodes.h:2427
List * semi_operators
Definition: pathnodes.h:2206
void list_free(List *list)
Definition: list.c:1391
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
Definition: pg_list.h:50
Relids min_lefthand
Definition: pathnodes.h:2196

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

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

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

2421 {
2422  double output_tuples;
2423  Cost startup_cost;
2424  Cost total_cost;
2425  AggClauseCosts dummy_aggcosts;
2426 
2427  /* Use all-zero per-aggregate costs if NULL is passed */
2428  if (aggcosts == NULL)
2429  {
2430  Assert(aggstrategy == AGG_HASHED);
2431  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
2432  aggcosts = &dummy_aggcosts;
2433  }
2434 
2435  /*
2436  * The transCost.per_tuple component of aggcosts should be charged once
2437  * per input tuple, corresponding to the costs of evaluating the aggregate
2438  * transfns and their input expressions. The finalCost.per_tuple component
2439  * is charged once per output tuple, corresponding to the costs of
2440  * evaluating the finalfns. Startup costs are of course charged but once.
2441  *
2442  * If we are grouping, we charge an additional cpu_operator_cost per
2443  * grouping column per input tuple for grouping comparisons.
2444  *
2445  * We will produce a single output tuple if not grouping, and a tuple per
2446  * group otherwise. We charge cpu_tuple_cost for each output tuple.
2447  *
2448  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2449  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2450  * input path is already sorted appropriately, AGG_SORTED should be
2451  * preferred (since it has no risk of memory overflow). This will happen
2452  * as long as the computed total costs are indeed exactly equal --- but if
2453  * there's roundoff error we might do the wrong thing. So be sure that
2454  * the computations below form the same intermediate values in the same
2455  * order.
2456  */
2457  if (aggstrategy == AGG_PLAIN)
2458  {
2459  startup_cost = input_total_cost;
2460  startup_cost += aggcosts->transCost.startup;
2461  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2462  startup_cost += aggcosts->finalCost.startup;
2463  startup_cost += aggcosts->finalCost.per_tuple;
2464  /* we aren't grouping */
2465  total_cost = startup_cost + cpu_tuple_cost;
2466  output_tuples = 1;
2467  }
2468  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2469  {
2470  /* Here we are able to deliver output on-the-fly */
2471  startup_cost = input_startup_cost;
2472  total_cost = input_total_cost;
2473  if (aggstrategy == AGG_MIXED && !enable_hashagg)
2474  {
2475  startup_cost += disable_cost;
2476  total_cost += disable_cost;
2477  }
2478  /* calcs phrased this way to match HASHED case, see note above */
2479  total_cost += aggcosts->transCost.startup;
2480  total_cost += aggcosts->transCost.per_tuple * input_tuples;
2481  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2482  total_cost += aggcosts->finalCost.startup;
2483  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2484  total_cost += cpu_tuple_cost * numGroups;
2485  output_tuples = numGroups;
2486  }
2487  else
2488  {
2489  /* must be AGG_HASHED */
2490  startup_cost = input_total_cost;
2491  if (!enable_hashagg)
2492  startup_cost += disable_cost;
2493  startup_cost += aggcosts->transCost.startup;
2494  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2495  /* cost of computing hash value */
2496  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2497  startup_cost += aggcosts->finalCost.startup;
2498 
2499  total_cost = startup_cost;
2500  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2501  /* cost of retrieving from hash table */
2502  total_cost += cpu_tuple_cost * numGroups;
2503  output_tuples = numGroups;
2504  }
2505 
2506  /*
2507  * Add the disk costs of hash aggregation that spills to disk.
2508  *
2509  * Groups that go into the hash table stay in memory until finalized, so
2510  * spilling and reprocessing tuples doesn't incur additional invocations
2511  * of transCost or finalCost. Furthermore, the computed hash value is
2512  * stored with the spilled tuples, so we don't incur extra invocations of
2513  * the hash function.
2514  *
2515  * Hash Agg begins returning tuples after the first batch is complete.
2516  * Accrue writes (spilled tuples) to startup_cost and to total_cost;
2517  * accrue reads only to total_cost.
2518  */
2519  if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
2520  {
2521  double pages;
2522  double pages_written = 0.0;
2523  double pages_read = 0.0;
2524  double spill_cost;
2525  double hashentrysize;
2526  double nbatches;
2527  Size mem_limit;
2528  uint64 ngroups_limit;
2529  int num_partitions;
2530  int depth;
2531 
2532  /*
2533  * Estimate number of batches based on the computed limits. If less
2534  * than or equal to one, all groups are expected to fit in memory;
2535  * otherwise we expect to spill.
2536  */
2537  hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
2538  input_width,
2539  aggcosts->transitionSpace);
2540  hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
2541  &ngroups_limit, &num_partitions);
2542 
2543  nbatches = Max((numGroups * hashentrysize) / mem_limit,
2544  numGroups / ngroups_limit);
2545 
2546  nbatches = Max(ceil(nbatches), 1.0);
2547  num_partitions = Max(num_partitions, 2);
2548 
2549  /*
2550  * The number of partitions can change at different levels of
2551  * recursion; but for the purposes of this calculation assume it stays
2552  * constant.
2553  */
2554  depth = ceil(log(nbatches) / log(num_partitions));
2555 
2556  /*
2557  * Estimate number of pages read and written. For each level of
2558  * recursion, a tuple must be written and then later read.
2559  */
2560  pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
2561  pages_written = pages_read = pages * depth;
2562 
2563  /*
2564  * HashAgg has somewhat worse IO behavior than Sort on typical
2565  * hardware/OS combinations. Account for this with a generic penalty.
2566  */
2567  pages_read *= 2.0;
2568  pages_written *= 2.0;
2569 
2570  startup_cost += pages_written * random_page_cost;
2571  total_cost += pages_written * random_page_cost;
2572  total_cost += pages_read * seq_page_cost;
2573 
2574  /* account for CPU cost of spilling a tuple and reading it back */
2575  spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
2576  startup_cost += spill_cost;
2577  total_cost += spill_cost;
2578  }
2579 
2580  /*
2581  * If there are quals (HAVING quals), account for their cost and
2582  * selectivity.
2583  */
2584  if (quals)
2585  {
2586  QualCost qual_cost;
2587 
2588  cost_qual_eval(&qual_cost, quals, root);
2589  startup_cost += qual_cost.startup;
2590  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2591 
2592  output_tuples = clamp_row_est(output_tuples *
2594  quals,
2595  0,
2596  JOIN_INNER,
2597  NULL));
2598  }
2599 
2600  path->rows = output_tuples;
2601  path->startup_cost = startup_cost;
2602  path->total_cost = total_cost;
2603 }
QualCost finalCost
Definition: pathnodes.h:59
#define MemSet(start, val, len)
Definition: c.h:1008
QualCost transCost
Definition: pathnodes.h:58
Cost startup
Definition: pathnodes.h:45
double random_page_cost
Definition: costsize.c:119
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1693
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4161
Cost startup_cost
Definition: pathnodes.h:1165
Cost disable_cost
Definition: costsize.c:128
List * aggtransinfos
Definition: pathnodes.h:351
double cpu_operator_cost
Definition: costsize.c:122
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5843
Cost total_cost
Definition: pathnodes.h:1166
#define Max(x, y)
Definition: c.h:980
#define Assert(condition)
Definition: c.h:804
double rows
Definition: pathnodes.h:1164
size_t Size
Definition: c.h:540
static int list_length(const List *l)
Definition: pg_list.h:149
double cpu_tuple_cost
Definition: costsize.c:120
bool enable_hashagg
Definition: costsize.c:139
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:1797
Size transitionSpace
Definition: pathnodes.h:60
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
double clamp_row_est(double nrows)
Definition: costsize.c:196
double seq_page_cost
Definition: costsize.c:118
double Cost
Definition: nodes.h:667

◆ cost_append()

void cost_append ( AppendPath path)

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

2140 {
2141  ListCell *l;
2142 
2143  apath->path.startup_cost = 0;
2144  apath->path.total_cost = 0;
2145  apath->path.rows = 0;
2146 
2147  if (apath->subpaths == NIL)
2148  return;
2149 
2150  if (!apath->path.parallel_aware)
2151  {
2152  List *pathkeys = apath->path.pathkeys;
2153 
2154  if (pathkeys == NIL)
2155  {
2156  Path *subpath = (Path *) linitial(apath->subpaths);
2157 
2158  /*
2159  * For an unordered, non-parallel-aware Append we take the startup
2160  * cost as the startup cost of the first subpath.
2161  */
2162  apath->path.startup_cost = subpath->startup_cost;
2163 
2164  /* Compute rows and costs as sums of subplan rows and costs. */
2165  foreach(l, apath->subpaths)
2166  {
2167  Path *subpath = (Path *) lfirst(l);
2168 
2169  apath->path.rows += subpath->rows;
2170  apath->path.total_cost += subpath->total_cost;
2171  }
2172  }
2173  else
2174  {
2175  /*
2176  * For an ordered, non-parallel-aware Append we take the startup
2177  * cost as the sum of the subpath startup costs. This ensures
2178  * that we don't underestimate the startup cost when a query's
2179  * LIMIT is such that several of the children have to be run to
2180  * satisfy it. This might be overkill --- another plausible hack
2181  * would be to take the Append's startup cost as the maximum of
2182  * the child startup costs. But we don't want to risk believing
2183  * that an ORDER BY LIMIT query can be satisfied at small cost
2184  * when the first child has small startup cost but later ones
2185  * don't. (If we had the ability to deal with nonlinear cost
2186  * interpolation for partial retrievals, we would not need to be
2187  * so conservative about this.)
2188  *
2189  * This case is also different from the above in that we have to
2190  * account for possibly injecting sorts into subpaths that aren't
2191  * natively ordered.
2192  */
2193  foreach(l, apath->subpaths)
2194  {
2195  Path *subpath = (Path *) lfirst(l);
2196  Path sort_path; /* dummy for result of cost_sort */
2197 
2198  if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
2199  {
2200  /*
2201  * We'll need to insert a Sort node, so include costs for
2202  * that. We can use the parent's LIMIT if any, since we
2203  * certainly won't pull more than that many tuples from
2204  * any child.
2205  */
2206  cost_sort(&sort_path,
2207  NULL, /* doesn't currently need root */
2208  pathkeys,
2209  subpath->total_cost,
2210  subpath->rows,
2211  subpath->pathtarget->width,
2212  0.0,
2213  work_mem,
2214  apath->limit_tuples);
2215  subpath = &sort_path;
2216  }
2217 
2218  apath->path.rows += subpath->rows;
2219  apath->path.startup_cost += subpath->startup_cost;
2220  apath->path.total_cost += subpath->total_cost;
2221  }
2222  }
2223  }
2224  else /* parallel-aware */
2225  {
2226  int i = 0;
2227  double parallel_divisor = get_parallel_divisor(&apath->path);
2228 
2229  /* Parallel-aware Append never produces ordered output. */
2230  Assert(apath->path.pathkeys == NIL);
2231 
2232  /* Calculate startup cost. */
2233  foreach(l, apath->subpaths)
2234  {
2235  Path *subpath = (Path *) lfirst(l);
2236 
2237  /*
2238  * Append will start returning tuples when the child node having
2239  * lowest startup cost is done setting up. We consider only the
2240  * first few subplans that immediately get a worker assigned.
2241  */
2242  if (i == 0)
2243  apath->path.startup_cost = subpath->startup_cost;
2244  else if (i < apath->path.parallel_workers)
2245  apath->path.startup_cost = Min(apath->path.startup_cost,
2246  subpath->startup_cost);
2247 
2248  /*
2249  * Apply parallel divisor to subpaths. Scale the number of rows
2250  * for each partial subpath based on the ratio of the parallel
2251  * divisor originally used for the subpath to the one we adopted.
2252  * Also add the cost of partial paths to the total cost, but
2253  * ignore non-partial paths for now.
2254  */
2255  if (i < apath->first_partial_path)
2256  apath->path.rows += subpath->rows / parallel_divisor;
2257  else
2258  {
2259  double subpath_parallel_divisor;
2260 
2261  subpath_parallel_divisor = get_parallel_divisor(subpath);
2262  apath->path.rows += subpath->rows * (subpath_parallel_divisor /
2263  parallel_divisor);
2264  apath->path.total_cost += subpath->total_cost;
2265  }
2266 
2267  apath->path.rows = clamp_row_est(apath->path.rows);
2268 
2269  i++;
2270  }
2271 
2272  /* Add cost for non-partial subpaths. */
2273  apath->path.total_cost +=
2274  append_nonpartial_cost(apath->subpaths,
2275  apath->first_partial_path,
2276  apath->path.parallel_workers);
2277  }
2278 
2279  /*
2280  * Although Append does not do any selection or projection, it's not free;
2281  * add a small per-tuple overhead.
2282  */
2283  apath->path.total_cost +=
2284  cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * apath->path.rows;
2285 }
#define NIL
Definition: pg_list.h:65
PathTarget * pathtarget
Definition: pathnodes.h:1155
#define Min(x, y)
Definition: c.h:986
static Cost append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
Definition: costsize.c:2063
#define linitial(l)
Definition: pg_list.h:174
Cost startup_cost
Definition: pathnodes.h:1165
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5864
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:2032
int work_mem
Definition: globals.c:122
Cost total_cost
Definition: pathnodes.h:1166
List * pathkeys
Definition: pathnodes.h:1168
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1164
double cpu_tuple_cost
Definition: costsize.c:120
int i
double clamp_row_est(double nrows)
Definition: costsize.c:196
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 1096 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().

1097 {
1098  Cost totalCost;
1099  Selectivity selec;
1100  ListCell *l;
1101 
1102  /*
1103  * We estimate AND selectivity on the assumption that the inputs are
1104  * independent. This is probably often wrong, but we don't have the info
1105  * to do better.
1106  *
1107  * The runtime cost of the BitmapAnd itself is estimated at 100x
1108  * cpu_operator_cost for each tbm_intersect needed. Probably too small,
1109  * definitely too simplistic?
1110  */
1111  totalCost = 0.0;
1112  selec = 1.0;
1113  foreach(l, path->bitmapquals)
1114  {
1115  Path *subpath = (Path *) lfirst(l);
1116  Cost subCost;
1117  Selectivity subselec;
1118 
1119  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1120 
1121  selec *= subselec;
1122 
1123  totalCost += subCost;
1124  if (l != list_head(path->bitmapquals))
1125  totalCost += 100.0 * cpu_operator_cost;
1126  }
1127  path->bitmapselectivity = selec;
1128  path->path.rows = 0; /* per above, not used */
1129  path->path.startup_cost = totalCost;
1130  path->path.total_cost = totalCost;
1131 }
double Selectivity
Definition: nodes.h:666
Selectivity bitmapselectivity
Definition: pathnodes.h:1303
List * bitmapquals
Definition: pathnodes.h:1302
Cost startup_cost
Definition: pathnodes.h:1165
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
double cpu_operator_cost
Definition: costsize.c:122
Cost total_cost
Definition: pathnodes.h:1166
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1164
double Cost
Definition: nodes.h:667
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1053

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

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

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

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

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

◆ cost_bitmap_tree_node()

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

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

1054 {
1055  if (IsA(path, IndexPath))
1056  {
1057  *cost = ((IndexPath *) path)->indextotalcost;
1058  *selec = ((IndexPath *) path)->indexselectivity;
1059 
1060  /*
1061  * Charge a small amount per retrieved tuple to reflect the costs of
1062  * manipulating the bitmap. This is mostly to make sure that a bitmap
1063  * scan doesn't look to be the same cost as an indexscan to retrieve a
1064  * single tuple.
1065  */
1066  *cost += 0.1 * cpu_operator_cost * path->rows;
1067  }
1068  else if (IsA(path, BitmapAndPath))
1069  {
1070  *cost = path->total_cost;
1071  *selec = ((BitmapAndPath *) path)->bitmapselectivity;
1072  }
1073  else if (IsA(path, BitmapOrPath))
1074  {
1075  *cost = path->total_cost;
1076  *selec = ((BitmapOrPath *) path)->bitmapselectivity;
1077  }
1078  else
1079  {
1080  elog(ERROR, "unrecognized node type: %d", nodeTag(path));
1081  *cost = *selec = 0; /* keep compiler quiet */
1082  }
1083 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
#define ERROR
Definition: elog.h:45
double cpu_operator_cost
Definition: costsize.c:122
Cost total_cost
Definition: pathnodes.h:1166
double rows
Definition: pathnodes.h:1164
#define nodeTag(nodeptr)
Definition: nodes.h:538
#define elog(elevel,...)
Definition: elog.h:227

◆ cost_ctescan()

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

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

1607 {
1608  Cost startup_cost = 0;
1609  Cost run_cost = 0;
1610  QualCost qpqual_cost;
1611  Cost cpu_per_tuple;
1612 
1613  /* Should only be applied to base relations that are CTEs */
1614  Assert(baserel->relid > 0);
1615  Assert(baserel->rtekind == RTE_CTE);
1616 
1617  /* Mark the path with the correct row estimate */
1618  if (param_info)
1619  path->rows = param_info->ppi_rows;
1620  else
1621  path->rows = baserel->rows;
1622 
1623  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1624  cpu_per_tuple = cpu_tuple_cost;
1625 
1626  /* Add scanning CPU costs */
1627  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1628 
1629  startup_cost += qpqual_cost.startup;
1630  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1631  run_cost += cpu_per_tuple * baserel->tuples;
1632 
1633  /* tlist eval costs are paid per output row, not per tuple scanned */
1634  startup_cost += path->pathtarget->cost.startup;
1635  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1636 
1637  path->startup_cost = startup_cost;
1638  path->total_cost = startup_cost + run_cost;
1639 }
PathTarget * pathtarget
Definition: pathnodes.h:1155
double tuples
Definition: pathnodes.h:710
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1165
Index relid
Definition: pathnodes.h:698
RTEKind rtekind
Definition: pathnodes.h:700
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4447
#define Assert(condition)
Definition: c.h:804
double rows
Definition: pathnodes.h:1164
QualCost cost
Definition: pathnodes.h:1086
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
double Cost
Definition: nodes.h:667

◆ cost_functionscan()

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

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

1440 {
1441  Cost startup_cost = 0;
1442  Cost run_cost = 0;
1443  QualCost qpqual_cost;
1444  Cost cpu_per_tuple;
1445  RangeTblEntry *rte;
1446  QualCost exprcost;
1447 
1448  /* Should only be applied to base relations that are functions */
1449  Assert(baserel->relid > 0);
1450  rte = planner_rt_fetch(baserel->relid, root);
1451  Assert(rte->rtekind == RTE_FUNCTION);
1452 
1453  /* Mark the path with the correct row estimate */
1454  if (param_info)
1455  path->rows = param_info->ppi_rows;
1456  else
1457  path->rows = baserel->rows;
1458 
1459  /*
1460  * Estimate costs of executing the function expression(s).
1461  *
1462  * Currently, nodeFunctionscan.c always executes the functions to
1463  * completion before returning any rows, and caches the results in a
1464  * tuplestore. So the function eval cost is all startup cost, and per-row
1465  * costs are minimal.
1466  *
1467  * XXX in principle we ought to charge tuplestore spill costs if the
1468  * number of rows is large. However, given how phony our rowcount
1469  * estimates for functions tend to be, there's not a lot of point in that
1470  * refinement right now.
1471  */
1472  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1473 
1474  startup_cost += exprcost.startup + exprcost.per_tuple;
1475 
1476  /* Add scanning CPU costs */
1477  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1478 
1479  startup_cost += qpqual_cost.startup;
1480  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1481  run_cost += cpu_per_tuple * baserel->tuples;
1482 
1483  /* tlist eval costs are paid per output row, not per tuple scanned */
1484  startup_cost += path->pathtarget->cost.startup;
1485  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1486 
1487  path->startup_cost = startup_cost;
1488  path->total_cost = startup_cost + run_cost;
1489 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4187
PathTarget * pathtarget
Definition: pathnodes.h:1155
double tuples
Definition: pathnodes.h:710
Definition: nodes.h:533
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1165
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:377
Index relid
Definition: pathnodes.h:698
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4447
#define Assert(condition)
Definition: c.h:804
List * functions
Definition: parsenodes.h:1068
double rows
Definition: pathnodes.h:1164
QualCost cost
Definition: pathnodes.h:1086
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
RTEKind rtekind
Definition: parsenodes.h:981
double Cost
Definition: nodes.h:667

◆ cost_gather()

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

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

378 {
379  Cost startup_cost = 0;
380  Cost run_cost = 0;
381 
382  /* Mark the path with the correct row estimate */
383  if (rows)
384  path->path.rows = *rows;
385  else if (param_info)
386  path->path.rows = param_info->ppi_rows;
387  else
388  path->path.rows = rel->rows;
389 
390  startup_cost = path->subpath->startup_cost;
391 
392  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
393 
394  /* Parallel setup and communication cost. */
395  startup_cost += parallel_setup_cost;
396  run_cost += parallel_tuple_cost * path->path.rows;
397 
398  path->path.startup_cost = startup_cost;
399  path->path.total_cost = (startup_cost + run_cost);
400 }
double parallel_setup_cost
Definition: costsize.c:124
Cost startup_cost
Definition: pathnodes.h:1165
Path * subpath
Definition: pathnodes.h:1513
Cost total_cost
Definition: pathnodes.h:1166
double rows
Definition: pathnodes.h:1164
double ppi_rows
Definition: pathnodes.h:1114
double Cost
Definition: nodes.h:667
double parallel_tuple_cost
Definition: costsize.c:123

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

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

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

2692 {
2693  double output_tuples;
2694  Cost startup_cost;
2695  Cost total_cost;
2696 
2697  output_tuples = numGroups;
2698  startup_cost = input_startup_cost;
2699  total_cost = input_total_cost;
2700 
2701  /*
2702  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2703  * all columns get compared at most of the tuples.
2704  */
2705  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2706 
2707  /*
2708  * If there are quals (HAVING quals), account for their cost and
2709  * selectivity.
2710  */
2711  if (quals)
2712  {
2713  QualCost qual_cost;
2714 
2715  cost_qual_eval(&qual_cost, quals, root);
2716  startup_cost += qual_cost.startup;
2717  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2718 
2719  output_tuples = clamp_row_est(output_tuples *
2721  quals,
2722  0,
2723  JOIN_INNER,
2724  NULL));
2725  }
2726 
2727  path->rows = output_tuples;
2728  path->startup_cost = startup_cost;
2729  path->total_cost = total_cost;
2730 }
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:4161
Cost startup_cost
Definition: pathnodes.h:1165
double cpu_operator_cost
Definition: costsize.c:122
Cost total_cost
Definition: pathnodes.h:1166
double rows
Definition: pathnodes.h:1164
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
double clamp_row_est(double nrows)
Definition: costsize.c:196
double Cost
Definition: nodes.h:667

◆ 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 1893 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, Min, NIL, PathKey::pk_eclass, pull_varnos(), Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by create_incremental_sort_path().

1898 {
1899  Cost startup_cost = 0,
1900  run_cost = 0,
1901  input_run_cost = input_total_cost - input_startup_cost;
1902  double group_tuples,
1903  input_groups;
1904  Cost group_startup_cost,
1905  group_run_cost,
1906  group_input_run_cost;
1907  List *presortedExprs = NIL;
1908  ListCell *l;
1909  int i = 0;
1910  bool unknown_varno = false;
1911 
1912  Assert(presorted_keys != 0);
1913 
1914  /*
1915  * We want to be sure the cost of a sort is never estimated as zero, even
1916  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1917  */
1918  if (input_tuples < 2.0)
1919  input_tuples = 2.0;
1920 
1921  /* Default estimate of number of groups, capped to one group per row. */
1922  input_groups = Min(input_tuples, DEFAULT_NUM_DISTINCT);
1923 
1924  /*
1925  * Extract presorted keys as list of expressions.
1926  *
1927  * We need to be careful about Vars containing "varno 0" which might have
1928  * been introduced by generate_append_tlist, which would confuse
1929  * estimate_num_groups (in fact it'd fail for such expressions). See
1930  * recurse_set_operations which has to deal with the same issue.
1931  *
1932  * Unlike recurse_set_operations we can't access the original target list
1933  * here, and even if we could it's not very clear how useful would that be
1934  * for a set operation combining multiple tables. So we simply detect if
1935  * there are any expressions with "varno 0" and use the default
1936  * DEFAULT_NUM_DISTINCT in that case.
1937  *
1938  * We might also use either 1.0 (a single group) or input_tuples (each row
1939  * being a separate group), pretty much the worst and best case for
1940  * incremental sort. But those are extreme cases and using something in
1941  * between seems reasonable. Furthermore, generate_append_tlist is used
1942  * for set operations, which are likely to produce mostly unique output
1943  * anyway - from that standpoint the DEFAULT_NUM_DISTINCT is defensive
1944  * while maintaining lower startup cost.
1945  */
1946  foreach(l, pathkeys)
1947  {
1948  PathKey *key = (PathKey *) lfirst(l);
1949  EquivalenceMember *member = (EquivalenceMember *)
1950  linitial(key->pk_eclass->ec_members);
1951 
1952  /*
1953  * Check if the expression contains Var with "varno 0" so that we
1954  * don't call estimate_num_groups in that case.
1955  */
1956  if (bms_is_member(0, pull_varnos(root, (Node *) member->em_expr)))
1957  {
1958  unknown_varno = true;
1959  break;
1960  }
1961 
1962  /* expression not containing any Vars with "varno 0" */
1963  presortedExprs = lappend(presortedExprs, member->em_expr);
1964 
1965  i++;
1966  if (i >= presorted_keys)
1967  break;
1968  }
1969 
1970  /* Estimate number of groups with equal presorted keys. */
1971  if (!unknown_varno)
1972  input_groups = estimate_num_groups(root, presortedExprs, input_tuples, NULL);
1973 
1974  group_tuples = input_tuples / input_groups;
1975  group_input_run_cost = input_run_cost / input_groups;
1976 
1977  /*
1978  * Estimate average cost of sorting of one group where presorted keys are
1979  * equal. Incremental sort is sensitive to distribution of tuples to the
1980  * groups, where we're relying on quite rough assumptions. Thus, we're
1981  * pessimistic about incremental sort performance and increase its average
1982  * group size by half.
1983  */
1984  cost_tuplesort(&group_startup_cost, &group_run_cost,
1985  1.5 * group_tuples, width, comparison_cost, sort_mem,
1986  limit_tuples);
1987 
1988  /*
1989  * Startup cost of incremental sort is the startup cost of its first group
1990  * plus the cost of its input.
1991  */
1992  startup_cost += group_startup_cost
1993  + input_startup_cost + group_input_run_cost;
1994 
1995  /*
1996  * After we started producing tuples from the first group, the cost of
1997  * producing all the tuples is given by the cost to finish processing this
1998  * group, plus the total cost to process the remaining groups, plus the
1999  * remaining cost of input.
2000  */
2001  run_cost += group_run_cost
2002  + (group_run_cost + group_startup_cost) * (input_groups - 1)
2003  + group_input_run_cost * (input_groups - 1);
2004 
2005  /*
2006  * Incremental sort adds some overhead by itself. Firstly, it has to
2007  * detect the sort groups. This is roughly equal to one extra copy and
2008  * comparison per tuple. Secondly, it has to reset the tuplesort context
2009  * for every group.
2010  */
2011  run_cost += (cpu_tuple_cost + comparison_cost) * input_tuples;
2012  run_cost += 2.0 * cpu_tuple_cost * input_groups;
2013 
2014  path->rows = input_tuples;
2015  path->startup_cost = startup_cost;
2016  path->total_cost = startup_cost + run_cost;
2017 }
#define NIL
Definition: pg_list.h:65
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:97
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3360
#define Min(x, y)
Definition: c.h:986
Definition: nodes.h:533
#define linitial(l)
Definition: pg_list.h:174
Cost startup_cost
Definition: pathnodes.h:1165
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:1791
List * lappend(List *list, void *datum)
Definition: list.c:336
Cost total_cost
Definition: pathnodes.h:1166
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
double rows
Definition: pathnodes.h:1164
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1051
double cpu_tuple_cost
Definition: costsize.c:120
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:52
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:667
List * ec_members
Definition: pathnodes.h:974

◆ cost_index()

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

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

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

◆ cost_material()

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

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

2364 {
2365  Cost startup_cost = input_startup_cost;
2366  Cost run_cost = input_total_cost - input_startup_cost;
2367  double nbytes = relation_byte_size(tuples, width);
2368  long work_mem_bytes = work_mem * 1024L;
2369 
2370  path->rows = tuples;
2371 
2372  /*
2373  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2374  * reflect bookkeeping overhead. (This rate must be more than what
2375  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2376  * if it is exactly the same then there will be a cost tie between
2377  * nestloop with A outer, materialized B inner and nestloop with B outer,
2378  * materialized A inner. The extra cost ensures we'll prefer
2379  * materializing the smaller rel.) Note that this is normally a good deal
2380  * less than cpu_tuple_cost; which is OK because a Material plan node
2381  * doesn't do qual-checking or projection, so it's got less overhead than
2382  * most plan nodes.
2383  */
2384  run_cost += 2 * cpu_operator_cost * tuples;
2385 
2386  /*
2387  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2388  * This cost is assumed to be evenly spread through the plan run phase,
2389  * which isn't exactly accurate but our cost model doesn't allow for
2390  * nonuniform costs within the run phase.
2391  */
2392  if (nbytes > work_mem_bytes)
2393  {
2394  double npages = ceil(nbytes / BLCKSZ);
2395 
2396  run_cost += seq_page_cost * npages;
2397  }
2398 
2399  path->startup_cost = startup_cost;
2400  path->total_cost = startup_cost + run_cost;
2401 }
Cost startup_cost
Definition: pathnodes.h:1165
double cpu_operator_cost
Definition: costsize.c:122
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5843
int work_mem
Definition: globals.c:122
Cost total_cost
Definition: pathnodes.h:1166
double rows
Definition: pathnodes.h:1164
double seq_page_cost
Definition: costsize.c:118
double Cost
Definition: nodes.h:667

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

2316 {
2317  Cost startup_cost = 0;
2318  Cost run_cost = 0;
2319  Cost comparison_cost;
2320  double N;
2321  double logN;
2322 
2323  /*
2324  * Avoid log(0)...
2325  */
2326  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2327  logN = LOG2(N);
2328 
2329  /* Assumed cost per tuple comparison */
2330  comparison_cost = 2.0 * cpu_operator_cost;
2331 
2332  /* Heap creation cost */
2333  startup_cost += comparison_cost * N * logN;
2334 
2335  /* Per-tuple heap maintenance cost */
2336  run_cost += tuples * comparison_cost * logN;
2337 
2338  /*
2339  * Although MergeAppend does not do any selection or projection, it's not
2340  * free; add a small per-tuple overhead.
2341  */
2342  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2343 
2344  path->startup_cost = startup_cost + input_startup_cost;
2345  path->total_cost = startup_cost + run_cost + input_total_cost;
2346 }
Cost startup_cost
Definition: pathnodes.h:1165
double cpu_operator_cost
Definition: costsize.c:122
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:108
Cost total_cost
Definition: pathnodes.h:1166
#define LOG2(x)
Definition: costsize.c:101
double cpu_tuple_cost
Definition: costsize.c:120
double Cost
Definition: nodes.h:667

◆ cost_namedtuplestorescan()

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

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

1648 {
1649  Cost startup_cost = 0;
1650  Cost run_cost = 0;
1651  QualCost qpqual_cost;
1652  Cost cpu_per_tuple;
1653 
1654  /* Should only be applied to base relations that are Tuplestores */
1655  Assert(baserel->relid > 0);
1656  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1657 
1658  /* Mark the path with the correct row estimate */
1659  if (param_info)
1660  path->rows = param_info->ppi_rows;
1661  else
1662  path->rows = baserel->rows;
1663 
1664  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1665  cpu_per_tuple = cpu_tuple_cost;
1666 
1667  /* Add scanning CPU costs */
1668  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1669 
1670  startup_cost += qpqual_cost.startup;
1671  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1672  run_cost += cpu_per_tuple * baserel->tuples;
1673 
1674  path->startup_cost = startup_cost;
1675  path->total_cost = startup_cost + run_cost;
1676 }
double tuples
Definition: pathnodes.h:710
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1165
Index relid
Definition: pathnodes.h:698
RTEKind rtekind
Definition: pathnodes.h:700
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4447
#define Assert(condition)
Definition: c.h:804
double rows
Definition: pathnodes.h:1164
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
double Cost
Definition: nodes.h:667

◆ cost_qual_eval()

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

Definition at line 4161 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_tidrangescan(), cost_tidscan(), create_group_result_path(), create_minmaxagg_path(), estimate_path_cost_size(), final_cost_hashjoin(), final_cost_mergejoin(), final_cost_nestloop(), get_restriction_qual_cost(), inline_function(), plan_cluster_use_sort(), postgresGetForeignJoinPaths(), postgresGetForeignRelSize(), set_baserel_size_estimates(), and set_foreign_size_estimates().

4162 {
4163  cost_qual_eval_context context;
4164  ListCell *l;
4165 
4166  context.root = root;
4167  context.total.startup = 0;
4168  context.total.per_tuple = 0;
4169 
4170  /* We don't charge any cost for the implicit ANDing at top level ... */
4171 
4172  foreach(l, quals)
4173  {
4174  Node *qual = (Node *) lfirst(l);
4175 
4176  cost_qual_eval_walker(qual, &context);
4177  }
4178 
4179  *cost = context.total;
4180 }
PlannerInfo * root
Definition: costsize.c:153
Definition: nodes.h:533
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:4201
#define lfirst(lc)
Definition: pg_list.h:169

◆ cost_qual_eval_node()

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

Definition at line 4187 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(), index_other_operands_eval_cost(), make_sort_input_target(), order_qual_clauses(), set_pathtarget_cost_width(), and set_rel_width().

4188 {
4189  cost_qual_eval_context context;
4190 
4191  context.root = root;
4192  context.total.startup = 0;
4193  context.total.per_tuple = 0;
4194 
4195  cost_qual_eval_walker(qual, &context);
4196 
4197  *cost = context.total;
4198 }
PlannerInfo * root
Definition: costsize.c:153
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:4201

◆ cost_recursive_union()

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

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

1721 {
1722  Cost startup_cost;
1723  Cost total_cost;
1724  double total_rows;
1725 
1726  /* We probably have decent estimates for the non-recursive term */
1727  startup_cost = nrterm->startup_cost;
1728  total_cost = nrterm->total_cost;
1729  total_rows = nrterm->rows;
1730 
1731  /*
1732  * We arbitrarily assume that about 10 recursive iterations will be
1733  * needed, and that we've managed to get a good fix on the cost and output
1734  * size of each one of them. These are mighty shaky assumptions but it's
1735  * hard to see how to do better.
1736  */
1737  total_cost += 10 * rterm->total_cost;
1738  total_rows += 10 * rterm->rows;
1739 
1740  /*
1741  * Also charge cpu_tuple_cost per row to account for the costs of
1742  * manipulating the tuplestores. (We don't worry about possible
1743  * spill-to-disk costs.)
1744  */
1745  total_cost += cpu_tuple_cost * total_rows;
1746 
1747  runion->startup_cost = startup_cost;
1748  runion->total_cost = total_cost;
1749  runion->rows = total_rows;
1750  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1751  rterm->pathtarget->width);
1752 }
PathTarget * pathtarget
Definition: pathnodes.h:1155
Cost startup_cost
Definition: pathnodes.h:1165
Cost total_cost
Definition: pathnodes.h:1166
#define Max(x, y)
Definition: c.h:980
double rows
Definition: pathnodes.h:1164
double cpu_tuple_cost
Definition: costsize.c:120
double Cost
Definition: nodes.h:667

◆ cost_resultscan()

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

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

1685 {
1686  Cost startup_cost = 0;
1687  Cost run_cost = 0;
1688  QualCost qpqual_cost;
1689  Cost cpu_per_tuple;
1690 
1691  /* Should only be applied to RTE_RESULT base relations */
1692  Assert(baserel->relid > 0);
1693  Assert(baserel->rtekind == RTE_RESULT);
1694 
1695  /* Mark the path with the correct row estimate */
1696  if (param_info)
1697  path->rows = param_info->ppi_rows;
1698  else
1699  path->rows = baserel->rows;
1700 
1701  /* We charge qual cost plus cpu_tuple_cost */
1702  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1703 
1704  startup_cost += qpqual_cost.startup;
1705  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1706  run_cost += cpu_per_tuple * baserel->tuples;
1707 
1708  path->startup_cost = startup_cost;
1709  path->total_cost = startup_cost + run_cost;
1710 }
double tuples
Definition: pathnodes.h:710
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1165
Index relid
Definition: pathnodes.h:698
RTEKind rtekind
Definition: pathnodes.h:700
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4447
#define Assert(condition)
Definition: c.h:804
double rows
Definition: pathnodes.h:1164
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
double Cost
Definition: nodes.h:667

◆ cost_samplescan()

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

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

302 {
303  Cost startup_cost = 0;
304  Cost run_cost = 0;
305  RangeTblEntry *rte;
306  TableSampleClause *tsc;
307  TsmRoutine *tsm;
308  double spc_seq_page_cost,
309  spc_random_page_cost,
310  spc_page_cost;
311  QualCost qpqual_cost;
312  Cost cpu_per_tuple;
313 
314  /* Should only be applied to base relations with tablesample clauses */
315  Assert(baserel->relid > 0);
316  rte = planner_rt_fetch(baserel->relid, root);
317  Assert(rte->rtekind == RTE_RELATION);
318  tsc = rte->tablesample;
319  Assert(tsc != NULL);
320  tsm = GetTsmRoutine(tsc->tsmhandler);
321 
322  /* Mark the path with the correct row estimate */
323  if (param_info)
324  path->rows = param_info->ppi_rows;
325  else
326  path->rows = baserel->rows;
327 
328  /* fetch estimated page cost for tablespace containing table */
330  &spc_random_page_cost,
331  &spc_seq_page_cost);
332 
333  /* if NextSampleBlock is used, assume random access, else sequential */
334  spc_page_cost = (tsm->NextSampleBlock != NULL) ?
335  spc_random_page_cost : spc_seq_page_cost;
336 
337  /*
338  * disk costs (recall that baserel->pages has already been set to the
339  * number of pages the sampling method will visit)
340  */
341  run_cost += spc_page_cost * baserel->pages;
342 
343  /*
344  * CPU costs (recall that baserel->tuples has already been set to the
345  * number of tuples the sampling method will select). Note that we ignore
346  * execution cost of the TABLESAMPLE parameter expressions; they will be
347  * evaluated only once per scan, and in most usages they'll likely be
348  * simple constants anyway. We also don't charge anything for the
349  * calculations the sampling method might do internally.
350  */
351  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
352 
353  startup_cost += qpqual_cost.startup;
354  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
355  run_cost += cpu_per_tuple * baserel->tuples;
356  /* tlist eval costs are paid per output row, not per tuple scanned */
357  startup_cost += path->pathtarget->cost.startup;
358  run_cost += path->pathtarget->cost.per_tuple * path->rows;
359 
360  path->startup_cost = startup_cost;
361  path->total_cost = startup_cost + run_cost;
362 }
PathTarget * pathtarget
Definition: pathnodes.h:1155
double tuples
Definition: pathnodes.h:710
Oid reltablespace
Definition: pathnodes.h:699
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1165
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:377
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:181
Index relid
Definition: pathnodes.h:698
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4447
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
BlockNumber pages
Definition: pathnodes.h:709
#define Assert(condition)
Definition: c.h:804
double rows
Definition: pathnodes.h:1164
QualCost cost
Definition: pathnodes.h:1086
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
RTEKind rtekind
Definition: parsenodes.h:981
struct TableSampleClause * tablesample
Definition: parsenodes.h:1011
double Cost
Definition: nodes.h:667

◆ cost_seqscan()

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

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

225 {
226  Cost startup_cost = 0;
227  Cost cpu_run_cost;
228  Cost disk_run_cost;
229  double spc_seq_page_cost;
230  QualCost qpqual_cost;
231  Cost cpu_per_tuple;
232 
233  /* Should only be applied to base relations */
234  Assert(baserel->relid > 0);
235  Assert(baserel->rtekind == RTE_RELATION);
236 
237  /* Mark the path with the correct row estimate */
238  if (param_info)
239  path->rows = param_info->ppi_rows;
240  else
241  path->rows = baserel->rows;
242 
243  if (!enable_seqscan)
244  startup_cost += disable_cost;
245 
246  /* fetch estimated page cost for tablespace containing table */
248  NULL,
249  &spc_seq_page_cost);
250 
251  /*
252  * disk costs
253  */
254  disk_run_cost = spc_seq_page_cost * baserel->pages;
255 
256  /* CPU costs */
257  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
258 
259  startup_cost += qpqual_cost.startup;
260  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
261  cpu_run_cost = cpu_per_tuple * baserel->tuples;
262  /* tlist eval costs are paid per output row, not per tuple scanned */
263  startup_cost += path->pathtarget->cost.startup;
264  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
265 
266  /* Adjust costing for parallelism, if used. */
267  if (path->parallel_workers > 0)
268  {
269  double parallel_divisor = get_parallel_divisor(path);
270 
271  /* The CPU cost is divided among all the workers. */
272  cpu_run_cost /= parallel_divisor;
273 
274  /*
275  * It may be possible to amortize some of the I/O cost, but probably
276  * not very much, because most operating systems already do aggressive
277  * prefetching. For now, we assume that the disk run cost can't be
278  * amortized at all.
279  */
280 
281  /*
282  * In the case of a parallel plan, the row count needs to represent
283  * the number of tuples processed per worker.
284  */
285  path->rows = clamp_row_est(path->rows / parallel_divisor);
286  }
287 
288  path->startup_cost = startup_cost;
289  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
290 }
PathTarget * pathtarget
Definition: pathnodes.h:1155
double tuples
Definition: pathnodes.h:710
Oid reltablespace
Definition: pathnodes.h:699
int parallel_workers
Definition: pathnodes.h:1161
bool enable_seqscan
Definition: costsize.c:132
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1165
Cost disable_cost
Definition: costsize.c:128
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5864
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:181
Index relid
Definition: pathnodes.h:698
RTEKind rtekind
Definition: pathnodes.h:700
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4447
BlockNumber pages
Definition: pathnodes.h:709
#define Assert(condition)
Definition: c.h:804
double rows
Definition: pathnodes.h:1164
QualCost cost
Definition: pathnodes.h:1086
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
double clamp_row_est(double nrows)
Definition: costsize.c:196
double Cost
Definition: nodes.h:667

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

2037 {
2038  Cost startup_cost;
2039  Cost run_cost;
2040 
2041  cost_tuplesort(&startup_cost, &run_cost,
2042  tuples, width,
2043  comparison_cost, sort_mem,
2044  limit_tuples);
2045 
2046  if (!enable_sort)
2047  startup_cost += disable_cost;
2048 
2049  startup_cost += input_cost;
2050 
2051  path->rows = tuples;
2052  path->startup_cost = startup_cost;
2053  path->total_cost = startup_cost + run_cost;
2054 }
bool enable_sort
Definition: costsize.c:137
Cost startup_cost
Definition: pathnodes.h:1165
Cost disable_cost
Definition: costsize.c:128
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:1791
Cost total_cost
Definition: pathnodes.h:1166
double rows
Definition: pathnodes.h:1164
double Cost
Definition: nodes.h:667

◆ cost_subplan()

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

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

3962 {
3963  QualCost sp_cost;
3964 
3965  /* Figure any cost for evaluating the testexpr */
3966  cost_qual_eval(&sp_cost,
3967  make_ands_implicit((Expr *) subplan->testexpr),
3968  root);
3969 
3970  if (subplan->useHashTable)
3971  {
3972  /*
3973  * If we are using a hash table for the subquery outputs, then the
3974  * cost of evaluating the query is a one-time cost. We charge one
3975  * cpu_operator_cost per tuple for the work of loading the hashtable,
3976  * too.
3977  */
3978  sp_cost.startup += plan->total_cost +
3979  cpu_operator_cost * plan->plan_rows;
3980 
3981  /*
3982  * The per-tuple costs include the cost of evaluating the lefthand
3983  * expressions, plus the cost of probing the hashtable. We already
3984  * accounted for the lefthand expressions as part of the testexpr, and
3985  * will also have counted one cpu_operator_cost for each comparison
3986  * operator. That is probably too low for the probing cost, but it's
3987  * hard to make a better estimate, so live with it for now.
3988  */
3989  }
3990  else
3991  {
3992  /*
3993  * Otherwise we will be rescanning the subplan output on each
3994  * evaluation. We need to estimate how much of the output we will
3995  * actually need to scan. NOTE: this logic should agree with the
3996  * tuple_fraction estimates used by make_subplan() in
3997  * plan/subselect.c.
3998  */
3999  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4000 
4001  if (subplan->subLinkType == EXISTS_SUBLINK)
4002  {
4003  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4004  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4005  }
4006  else if (subplan->subLinkType == ALL_SUBLINK ||
4007  subplan->subLinkType == ANY_SUBLINK)
4008  {
4009  /* assume we need 50% of the tuples */
4010  sp_cost.per_tuple += 0.50 * plan_run_cost;
4011  /* also charge a cpu_operator_cost per row examined */
4012  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4013  }
4014  else
4015  {
4016  /* assume we need all tuples */
4017  sp_cost.per_tuple += plan_run_cost;
4018  }
4019 
4020  /*
4021  * Also account for subplan's startup cost. If the subplan is
4022  * uncorrelated or undirect correlated, AND its topmost node is one
4023  * that materializes its output, assume that we'll only need to pay
4024  * its startup cost once; otherwise assume we pay the startup cost
4025  * every time.
4026  */
4027  if (subplan->parParam == NIL &&
4029  sp_cost.startup += plan->startup_cost;
4030  else
4031  sp_cost.per_tuple += plan->startup_cost;
4032  }
4033 
4034  subplan->startup_cost = sp_cost.startup;
4035  subplan->per_call_cost = sp_cost.per_tuple;
4036 }
#define NIL
Definition: pg_list.h:65
double plan_rows
Definition: plannodes.h:123
SubLinkType subLinkType
Definition: primnodes.h:725
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:4161
Cost startup_cost
Definition: plannodes.h:117
double cpu_operator_cost
Definition: costsize.c:122
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
Node * testexpr
Definition: primnodes.h:727
Cost per_call_cost
Definition: primnodes.h:754
List * parParam
Definition: primnodes.h:750
#define nodeTag(nodeptr)
Definition: nodes.h:538
Cost total_cost
Definition: plannodes.h:118
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:634
bool useHashTable
Definition: primnodes.h:739
Cost startup_cost
Definition: primnodes.h:753
double clamp_row_est(double nrows)
Definition: costsize.c:196
double Cost
Definition: nodes.h:667

◆ cost_subqueryscan()

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

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

1391 {
1392  Cost startup_cost;
1393  Cost run_cost;
1394  QualCost qpqual_cost;
1395  Cost cpu_per_tuple;
1396 
1397  /* Should only be applied to base relations that are subqueries */
1398  Assert(baserel->relid > 0);
1399  Assert(baserel->rtekind == RTE_SUBQUERY);
1400 
1401  /* Mark the path with the correct row estimate */
1402  if (param_info)
1403  path->path.rows = param_info->ppi_rows;
1404  else
1405  path->path.rows = baserel->rows;
1406 
1407  /*
1408  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1409  * any restriction clauses and tlist that will be attached to the
1410  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1411  * projection overhead.
1412  */
1413  path->path.startup_cost = path->subpath->startup_cost;
1414  path->path.total_cost = path->subpath->total_cost;
1415 
1416  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1417 
1418  startup_cost = qpqual_cost.startup;
1419  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1420  run_cost = cpu_per_tuple * baserel->tuples;
1421 
1422  /* tlist eval costs are paid per output row, not per tuple scanned */
1423  startup_cost += path->path.pathtarget->cost.startup;
1424  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1425 
1426  path->path.startup_cost += startup_cost;
1427  path->path.total_cost += startup_cost + run_cost;
1428 }
PathTarget * pathtarget
Definition: pathnodes.h:1155
double tuples
Definition: pathnodes.h:710
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1165
Index relid
Definition: pathnodes.h:698
RTEKind rtekind
Definition: pathnodes.h:700
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4447
#define Assert(condition)
Definition: c.h:804
double rows
Definition: pathnodes.h:1164
QualCost cost
Definition: pathnodes.h:1086
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
double Cost
Definition: nodes.h:667

◆ cost_tablefuncscan()

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

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

1501 {
1502  Cost startup_cost = 0;
1503  Cost run_cost = 0;
1504  QualCost qpqual_cost;
1505  Cost cpu_per_tuple;
1506  RangeTblEntry *rte;
1507  QualCost exprcost;
1508 
1509  /* Should only be applied to base relations that are functions */
1510  Assert(baserel->relid > 0);
1511  rte = planner_rt_fetch(baserel->relid, root);
1512  Assert(rte->rtekind == RTE_TABLEFUNC);
1513 
1514  /* Mark the path with the correct row estimate */
1515  if (param_info)
1516  path->rows = param_info->ppi_rows;
1517  else
1518  path->rows = baserel->rows;
1519 
1520  /*
1521  * Estimate costs of executing the table func expression(s).
1522  *
1523  * XXX in principle we ought to charge tuplestore spill costs if the
1524  * number of rows is large. However, given how phony our rowcount
1525  * estimates for tablefuncs tend to be, there's not a lot of point in that
1526  * refinement right now.
1527  */
1528  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1529 
1530  startup_cost += exprcost.startup + exprcost.per_tuple;
1531 
1532  /* Add scanning CPU costs */
1533  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1534 
1535  startup_cost += qpqual_cost.startup;
1536  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1537  run_cost += cpu_per_tuple * baserel->tuples;
1538 
1539  /* tlist eval costs are paid per output row, not per tuple scanned */
1540  startup_cost += path->pathtarget->cost.startup;
1541  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1542 
1543  path->startup_cost = startup_cost;
1544  path->total_cost = startup_cost + run_cost;
1545 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4187
PathTarget * pathtarget
Definition: pathnodes.h:1155
double tuples
Definition: pathnodes.h:710
Definition: nodes.h:533
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
TableFunc * tablefunc
Definition: parsenodes.h:1074
Cost startup_cost
Definition: pathnodes.h:1165
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:377
Index relid
Definition: pathnodes.h:698
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4447
#define Assert(condition)
Definition: c.h:804
double rows
Definition: pathnodes.h:1164
QualCost cost
Definition: pathnodes.h:1086
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
RTEKind rtekind
Definition: parsenodes.h:981
double Cost
Definition: nodes.h:667

◆ cost_tidrangescan()

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

Definition at line 1296 of file costsize.c.

References Assert, clauselist_selectivity(), PathTarget::cost, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_tidscan, get_restriction_qual_cost(), get_tablespace_page_costs(), JOIN_INNER, RelOptInfo::pages, 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_tidrangescan_path().

1299 {
1300  Selectivity selectivity;
1301  double pages;
1302  Cost startup_cost = 0;
1303  Cost run_cost = 0;
1304  QualCost qpqual_cost;
1305  Cost cpu_per_tuple;
1306  QualCost tid_qual_cost;
1307  double ntuples;
1308  double nseqpages;
1309  double spc_random_page_cost;
1310  double spc_seq_page_cost;
1311 
1312  /* Should only be applied to base relations */
1313  Assert(baserel->relid > 0);
1314  Assert(baserel->rtekind == RTE_RELATION);
1315 
1316  /* Mark the path with the correct row estimate */
1317  if (param_info)
1318  path->rows = param_info->ppi_rows;
1319  else
1320  path->rows = baserel->rows;
1321 
1322  /* Count how many tuples and pages we expect to scan */
1323  selectivity = clauselist_selectivity(root, tidrangequals, baserel->relid,
1324  JOIN_INNER, NULL);
1325  pages = ceil(selectivity * baserel->pages);
1326 
1327  if (pages <= 0.0)
1328  pages = 1.0;
1329 
1330  /*
1331  * The first page in a range requires a random seek, but each subsequent
1332  * page is just a normal sequential page read. NOTE: it's desirable for
1333  * TID Range Scans to cost more than the equivalent Sequential Scans,
1334  * because Seq Scans have some performance advantages such as scan
1335  * synchronization and parallelizability, and we'd prefer one of them to
1336  * be picked unless a TID Range Scan really is better.
1337  */
1338  ntuples = selectivity * baserel->tuples;
1339  nseqpages = pages - 1.0;
1340 
1341  if (!enable_tidscan)
1342  startup_cost += disable_cost;
1343 
1344  /*
1345  * The TID qual expressions will be computed once, any other baserestrict
1346  * quals once per retrieved tuple.
1347  */
1348  cost_qual_eval(&tid_qual_cost, tidrangequals, root);
1349 
1350  /* fetch estimated page cost for tablespace containing table */
1352  &spc_random_page_cost,
1353  &spc_seq_page_cost);
1354 
1355  /* disk costs; 1 random page and the remainder as seq pages */
1356  run_cost += spc_random_page_cost + spc_seq_page_cost * nseqpages;
1357 
1358  /* Add scanning CPU costs */
1359  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1360 
1361  /*
1362  * XXX currently we assume TID quals are a subset of qpquals at this
1363  * point; they will be removed (if possible) when we create the plan, so
1364  * we subtract their cost from the total qpqual cost. (If the TID quals
1365  * can't be removed, this is a mistake and we're going to underestimate
1366  * the CPU cost a bit.)
1367  */
1368  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1369  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1370  tid_qual_cost.per_tuple;
1371  run_cost += cpu_per_tuple * ntuples;
1372 
1373  /* tlist eval costs are paid per output row, not per tuple scanned */
1374  startup_cost += path->pathtarget->cost.startup;
1375  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1376 
1377  path->startup_cost = startup_cost;
1378  path->total_cost = startup_cost + run_cost;
1379 }
PathTarget * pathtarget
Definition: pathnodes.h:1155
bool enable_tidscan
Definition: costsize.c:136
double tuples
Definition: pathnodes.h:710
Oid reltablespace
Definition: pathnodes.h:699
double Selectivity
Definition: nodes.h:666
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:4161
Cost startup_cost
Definition: pathnodes.h:1165
Cost disable_cost
Definition: costsize.c:128
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:181
Index relid
Definition: pathnodes.h:698
RTEKind rtekind
Definition: pathnodes.h:700
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4447
BlockNumber pages
Definition: pathnodes.h:709
#define Assert(condition)
Definition: c.h:804
double rows
Definition: pathnodes.h:1164
QualCost cost
Definition: pathnodes.h:1086
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
double Cost
Definition: nodes.h:667

◆ cost_tidscan()

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

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

1190 {
1191  Cost startup_cost = 0;
1192  Cost run_cost = 0;
1193  bool isCurrentOf = false;
1194  QualCost qpqual_cost;
1195  Cost cpu_per_tuple;
1196  QualCost tid_qual_cost;
1197  int ntuples;
1198  ListCell *l;
1199  double spc_random_page_cost;
1200 
1201  /* Should only be applied to base relations */
1202  Assert(baserel->relid > 0);
1203  Assert(baserel->rtekind == RTE_RELATION);
1204 
1205  /* Mark the path with the correct row estimate */
1206  if (param_info)
1207  path->rows = param_info->ppi_rows;
1208  else
1209  path->rows = baserel->rows;
1210 
1211  /* Count how many tuples we expect to retrieve */
1212  ntuples = 0;
1213  foreach(l, tidquals)
1214  {
1215  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
1216  Expr *qual = rinfo->clause;
1217 
1218  if (IsA(qual, ScalarArrayOpExpr))
1219  {
1220  /* Each element of the array yields 1 tuple */
1221  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) qual;
1222  Node *arraynode = (Node *) lsecond(saop->args);
1223 
1224  ntuples += estimate_array_length(arraynode);
1225  }
1226  else if (IsA(qual, CurrentOfExpr))
1227  {
1228  /* CURRENT OF yields 1 tuple */
1229  isCurrentOf = true;
1230  ntuples++;
1231  }
1232  else
1233  {
1234  /* It's just CTID = something, count 1 tuple */
1235  ntuples++;
1236  }
1237  }
1238 
1239  /*
1240  * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
1241  * understands how to do it correctly. Therefore, honor enable_tidscan
1242  * only when CURRENT OF isn't present. Also note that cost_qual_eval
1243  * counts a CurrentOfExpr as having startup cost disable_cost, which we
1244  * subtract off here; that's to prevent other plan types such as seqscan
1245  * from winning.
1246  */
1247  if (isCurrentOf)
1248  {
1250  startup_cost -= disable_cost;
1251  }
1252  else if (!enable_tidscan)
1253  startup_cost += disable_cost;
1254 
1255  /*
1256  * The TID qual expressions will be computed once, any other baserestrict
1257  * quals once per retrieved tuple.
1258  */
1259  cost_qual_eval(&tid_qual_cost, tidquals, root);
1260 
1261  /* fetch estimated page cost for tablespace containing table */
1263  &spc_random_page_cost,
1264  NULL);
1265 
1266  /* disk costs --- assume each tuple on a different page */
1267  run_cost += spc_random_page_cost * ntuples;
1268 
1269  /* Add scanning CPU costs */
1270  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1271 
1272  /* XXX currently we assume TID quals are a subset of qpquals */
1273  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1274  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1275  tid_qual_cost.per_tuple;
1276  run_cost += cpu_per_tuple * ntuples;
1277 
1278  /* tlist eval costs are paid per output row, not per tuple scanned */
1279  startup_cost += path->pathtarget->cost.startup;
1280  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1281 
1282  path->startup_cost = startup_cost;
1283  path->total_cost = startup_cost + run_cost;
1284 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
PathTarget * pathtarget
Definition: pathnodes.h:1155
bool enable_tidscan
Definition: costsize.c:136
Oid reltablespace
Definition: pathnodes.h:699
Definition: nodes.h:533
#define lsecond(l)
Definition: pg_list.h:179
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:4161
Cost startup_cost
Definition: pathnodes.h:1165
Cost disable_cost
Definition: costsize.c:128
#define lfirst_node(type, lc)
Definition: pg_list.h:172
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:181
Index relid
Definition: pathnodes.h:698
Expr * clause
Definition: pathnodes.h:2006
RTEKind rtekind
Definition: pathnodes.h:700
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4447
#define Assert(condition)
Definition: c.h:804
double rows
Definition: pathnodes.h:1164
QualCost cost
Definition: pathnodes.h:1086
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
QualCost baserestrictcost
Definition: pathnodes.h:735
double Cost
Definition: nodes.h:667

◆ cost_valuesscan()

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

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

1557 {
1558  Cost startup_cost = 0;
1559  Cost run_cost = 0;
1560  QualCost qpqual_cost;
1561  Cost cpu_per_tuple;
1562 
1563  /* Should only be applied to base relations that are values lists */
1564  Assert(baserel->relid > 0);
1565  Assert(baserel->rtekind == RTE_VALUES);
1566 
1567  /* Mark the path with the correct row estimate */
1568  if (param_info)
1569  path->rows = param_info->ppi_rows;
1570  else
1571  path->rows = baserel->rows;
1572 
1573  /*
1574  * For now, estimate list evaluation cost at one operator eval per list
1575  * (probably pretty bogus, but is it worth being smarter?)
1576  */
1577  cpu_per_tuple = cpu_operator_cost;
1578 
1579  /* Add scanning CPU costs */
1580  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1581 
1582  startup_cost += qpqual_cost.startup;
1583  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1584  run_cost += cpu_per_tuple * baserel->tuples;
1585 
1586  /* tlist eval costs are paid per output row, not per tuple scanned */
1587  startup_cost += path->pathtarget->cost.startup;
1588  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1589 
1590  path->startup_cost = startup_cost;
1591  path->total_cost = startup_cost + run_cost;
1592 }
PathTarget * pathtarget
Definition: pathnodes.h:1155
double tuples
Definition: pathnodes.h:710
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1165
double cpu_operator_cost
Definition: costsize.c:122
Index relid
Definition: pathnodes.h:698
RTEKind rtekind
Definition: pathnodes.h:700
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4447
#define Assert(condition)
Definition: c.h:804
double rows
Definition: pathnodes.h:1164
QualCost cost
Definition: pathnodes.h:1086
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
double Cost
Definition: nodes.h:667

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

2617 {
2618  Cost startup_cost;
2619  Cost total_cost;
2620  ListCell *lc;
2621 
2622  startup_cost = input_startup_cost;
2623  total_cost = input_total_cost;
2624 
2625  /*
2626  * Window functions are assumed to cost their stated execution cost, plus
2627  * the cost of evaluating their input expressions, per tuple. Since they
2628  * may in fact evaluate their inputs at multiple rows during each cycle,
2629  * this could be a drastic underestimate; but without a way to know how
2630  * many rows the window function will fetch, it's hard to do better. In
2631  * any case, it's a good estimate for all the built-in window functions,
2632  * so we'll just do this for now.
2633  */
2634  foreach(lc, windowFuncs)
2635  {
2636  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
2637  Cost wfunccost;
2638  QualCost argcosts;
2639 
2640  argcosts.startup = argcosts.per_tuple = 0;
2641  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
2642  &argcosts);
2643  startup_cost += argcosts.startup;
2644  wfunccost = argcosts.per_tuple;
2645 
2646  /* also add the input expressions' cost to per-input-row costs */
2647  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
2648  startup_cost += argcosts.startup;
2649  wfunccost += argcosts.per_tuple;
2650 
2651  /*
2652  * Add the filter's cost to per-input-row costs. XXX We should reduce
2653  * input expression costs according to filter selectivity.
2654  */
2655  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
2656  startup_cost += argcosts.startup;
2657  wfunccost += argcosts.per_tuple;
2658 
2659  total_cost += wfunccost * input_tuples;
2660  }
2661 
2662  /*
2663  * We also charge cpu_operator_cost per grouping column per tuple for
2664  * grouping comparisons, plus cpu_tuple_cost per tuple for general
2665  * overhead.
2666  *
2667  * XXX this neglects costs of spooling the data to disk when it overflows
2668  * work_mem. Sooner or later that should get accounted for.
2669  */
2670  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
2671  total_cost += cpu_tuple_cost * input_tuples;
2672 
2673  path->rows = input_tuples;
2674  path->startup_cost = startup_cost;
2675  path->total_cost = total_cost;
2676 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4187
List * args
Definition: primnodes.h:385
Definition: nodes.h:533
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1924
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1165
#define lfirst_node(type, lc)
Definition: pg_list.h:172
double cpu_operator_cost
Definition: costsize.c:122
Oid winfnoid
Definition: primnodes.h:381
Cost total_cost
Definition: pathnodes.h:1166
Expr * aggfilter
Definition: primnodes.h:386
double rows
Definition: pathnodes.h:1164
double cpu_tuple_cost
Definition: costsize.c:120
double Cost
Definition: nodes.h:667

◆ final_cost_hashjoin()

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

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

3707 {
3708  Path *outer_path = path->jpath.outerjoinpath;
3709  Path *inner_path = path->jpath.innerjoinpath;
3710  double outer_path_rows = outer_path->rows;
3711  double inner_path_rows = inner_path->rows;
3712  double inner_path_rows_total = workspace->inner_rows_total;
3713  List *hashclauses = path->path_hashclauses;
3714  Cost startup_cost = workspace->startup_cost;
3715  Cost run_cost = workspace->run_cost;
3716  int numbuckets = workspace->numbuckets;
3717  int numbatches = workspace->numbatches;
3718  int hash_mem;
3719  Cost cpu_per_tuple;
3720  QualCost hash_qual_cost;
3721  QualCost qp_qual_cost;
3722  double hashjointuples;
3723  double virtualbuckets;
3724  Selectivity innerbucketsize;
3725  Selectivity innermcvfreq;
3726  ListCell *hcl;
3727 
3728  /* Mark the path with the correct row estimate */
3729  if (path->jpath.path.param_info)
3730  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3731  else
3732  path->jpath.path.rows = path->jpath.path.parent->rows;
3733 
3734  /* For partial paths, scale row estimate. */
3735  if (path->jpath.path.parallel_workers > 0)
3736  {
3737  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3738 
3739  path->jpath.path.rows =
3740  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3741  }
3742 
3743  /*
3744  * We could include disable_cost in the preliminary estimate, but that
3745  * would amount to optimizing for the case where the join method is
3746  * disabled, which doesn't seem like the way to bet.
3747  */
3748  if (!enable_hashjoin)
3749  startup_cost += disable_cost;
3750 
3751  /* mark the path with estimated # of batches */
3752  path->num_batches = numbatches;
3753 
3754  /* store the total number of tuples (sum of partial row estimates) */
3755  path->inner_rows_total = inner_path_rows_total;
3756 
3757  /* and compute the number of "virtual" buckets in the whole join */
3758  virtualbuckets = (double) numbuckets * (double) numbatches;
3759 
3760  /*
3761  * Determine bucketsize fraction and MCV frequency for the inner relation.
3762  * We use the smallest bucketsize or MCV frequency estimated for any
3763  * individual hashclause; this is undoubtedly conservative.
3764  *
3765  * BUT: if inner relation has been unique-ified, we can assume it's good
3766  * for hashing. This is important both because it's the right answer, and
3767  * because we avoid contaminating the cache with a value that's wrong for
3768  * non-unique-ified paths.
3769  */
3770  if (IsA(inner_path, UniquePath))
3771  {
3772  innerbucketsize = 1.0 / virtualbuckets;
3773  innermcvfreq = 0.0;
3774  }
3775  else
3776  {
3777  innerbucketsize = 1.0;
3778  innermcvfreq = 1.0;
3779  foreach(hcl, hashclauses)
3780  {
3781  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
3782  Selectivity thisbucketsize;
3783  Selectivity thismcvfreq;
3784 
3785  /*
3786  * First we have to figure out which side of the hashjoin clause
3787  * is the inner side.
3788  *
3789  * Since we tend to visit the same clauses over and over when
3790  * planning a large query, we cache the bucket stats estimates in
3791  * the RestrictInfo node to avoid repeated lookups of statistics.
3792  */
3793  if (bms_is_subset(restrictinfo->right_relids,
3794  inner_path->parent->relids))
3795  {
3796  /* righthand side is inner */
3797  thisbucketsize = restrictinfo->right_bucketsize;
3798  if (thisbucketsize < 0)
3799  {
3800  /* not cached yet */
3802  get_rightop(restrictinfo->clause),
3803  virtualbuckets,
3804  &restrictinfo->right_mcvfreq,
3805  &restrictinfo->right_bucketsize);
3806  thisbucketsize = restrictinfo->right_bucketsize;
3807  }
3808  thismcvfreq = restrictinfo->right_mcvfreq;
3809  }
3810  else
3811  {
3812  Assert(bms_is_subset(restrictinfo->left_relids,
3813  inner_path->parent->relids));
3814  /* lefthand side is inner */
3815  thisbucketsize = restrictinfo->left_bucketsize;
3816  if (thisbucketsize < 0)
3817  {
3818  /* not cached yet */
3820  get_leftop(restrictinfo->clause),
3821  virtualbuckets,
3822  &restrictinfo->left_mcvfreq,
3823  &restrictinfo->left_bucketsize);
3824  thisbucketsize = restrictinfo->left_bucketsize;
3825  }
3826  thismcvfreq = restrictinfo->left_mcvfreq;
3827  }
3828 
3829  if (innerbucketsize > thisbucketsize)
3830  innerbucketsize = thisbucketsize;
3831  if (innermcvfreq > thismcvfreq)
3832  innermcvfreq = thismcvfreq;
3833  }
3834  }
3835 
3836  /*
3837  * If the bucket holding the inner MCV would exceed hash_mem, we don't
3838  * want to hash unless there is really no other alternative, so apply
3839  * disable_cost. (The executor normally copes with excessive memory usage
3840  * by splitting batches, but obviously it cannot separate equal values
3841  * that way, so it will be unable to drive the batch size below hash_mem
3842  * when this is true.)
3843  */
3844  hash_mem = get_hash_mem();
3845  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
3846  inner_path->pathtarget->width) >
3847  (hash_mem * 1024L))
3848  startup_cost += disable_cost;
3849 
3850  /*
3851  * Compute cost of the hashquals and qpquals (other restriction clauses)
3852  * separately.
3853  */
3854  cost_qual_eval(&hash_qual_cost, hashclauses, root);
3855  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3856  qp_qual_cost.startup -= hash_qual_cost.startup;
3857  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
3858 
3859  /* CPU costs */
3860 
3861  if (path->jpath.jointype == JOIN_SEMI ||
3862  path->jpath.jointype == JOIN_ANTI ||
3863  extra->inner_unique)
3864  {
3865  double outer_matched_rows;
3866  Selectivity inner_scan_frac;
3867 
3868  /*
3869  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3870  * executor will stop after the first match.
3871  *
3872  * For an outer-rel row that has at least one match, we can expect the
3873  * bucket scan to stop after a fraction 1/(match_count+1) of the
3874  * bucket's rows, if the matches are evenly distributed. Since they
3875  * probably aren't quite evenly distributed, we apply a fuzz factor of
3876  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
3877  * to clamp inner_scan_frac to at most 1.0; but since match_count is
3878  * at least 1, no such clamp is needed now.)
3879  */
3880  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3881  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3882 
3883  startup_cost += hash_qual_cost.startup;
3884  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
3885  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
3886 
3887  /*
3888  * For unmatched outer-rel rows, the picture is quite a lot different.
3889  * In the first place, there is no reason to assume that these rows
3890  * preferentially hit heavily-populated buckets; instead assume they
3891  * are uncorrelated with the inner distribution and so they see an
3892  * average bucket size of inner_path_rows / virtualbuckets. In the
3893  * second place, it seems likely that they will have few if any exact
3894  * hash-code matches and so very few of the tuples in the bucket will
3895  * actually require eval of the hash quals. We don't have any good
3896  * way to estimate how many will, but for the moment assume that the
3897  * effective cost per bucket entry is one-tenth what it is for
3898  * matchable tuples.
3899  */
3900  run_cost += hash_qual_cost.per_tuple *
3901  (outer_path_rows - outer_matched_rows) *
3902  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
3903 
3904  /* Get # of tuples that will pass the basic join */
3905  if (path->jpath.jointype == JOIN_ANTI)
3906  hashjointuples = outer_path_rows - outer_matched_rows;
3907  else
3908  hashjointuples = outer_matched_rows;
3909  }
3910  else
3911  {
3912  /*
3913  * The number of tuple comparisons needed is the number of outer
3914  * tuples times the typical number of tuples in a hash bucket, which
3915  * is the inner relation size times its bucketsize fraction. At each
3916  * one, we need to evaluate the hashjoin quals. But actually,
3917  * charging the full qual eval cost at each tuple is pessimistic,
3918  * since we don't evaluate the quals unless the hash values match
3919  * exactly. For lack of a better idea, halve the cost estimate to
3920  * allow for that.
3921  */
3922  startup_cost += hash_qual_cost.startup;
3923  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
3924  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
3925 
3926  /*
3927  * Get approx # tuples passing the hashquals. We use
3928  * approx_tuple_count here because we need an estimate done with
3929  * JOIN_INNER semantics.
3930  */
3931  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
3932  }
3933 
3934  /*
3935  * For each tuple that gets through the hashjoin proper, we charge
3936  * cpu_tuple_cost plus the cost of evaluating additional restriction
3937  * clauses that are to be applied at the join. (This is pessimistic since
3938  * not all of the quals may get evaluated at each tuple.)
3939  */
3940  startup_cost += qp_qual_cost.startup;
3941  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3942  run_cost += cpu_per_tuple * hashjointuples;
3943 
3944  /* tlist eval costs are paid per output row, not per tuple scanned */
3945  startup_cost += path->jpath.path.pathtarget->cost.startup;
3946  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3947 
3948  path->jpath.path.startup_cost = startup_cost;
3949  path->jpath.path.total_cost = startup_cost + run_cost;
3950 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
JoinPath jpath
Definition: pathnodes.h:1617
PathTarget * pathtarget
Definition: pathnodes.h:1155
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:2449
int num_batches
Definition: pathnodes.h:1619
Selectivity right_mcvfreq
Definition: pathnodes.h:2070
Selectivity outer_match_frac
Definition: pathnodes.h:2426
Path * innerjoinpath
Definition: pathnodes.h:1544
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4690
int parallel_workers
Definition: pathnodes.h:1161
ParamPathInfo * param_info
Definition: pathnodes.h:1157
Relids left_relids
Definition: pathnodes.h:2033
double Selectivity
Definition: nodes.h:666
double inner_rows_total
Definition: pathnodes.h:1620
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:4161
Cost startup_cost
Definition: pathnodes.h:1165
Cost disable_cost
Definition: costsize.c:128
List * joinrestrictinfo
Definition: pathnodes.h:1546
RelOptInfo * parent
Definition: pathnodes.h:1154
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
#define lfirst_node(type, lc)
Definition: pg_list.h:172
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5864
Relids relids
Definition: pathnodes.h:670
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:73
Expr * clause
Definition: pathnodes.h:2006
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5843
Path * outerjoinpath
Definition: pathnodes.h:1543
double inner_rows_total
Definition: pathnodes.h:2570
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:85
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
Selectivity left_bucketsize
Definition: pathnodes.h:2067
Relids right_relids
Definition: pathnodes.h:2034
Path path
Definition: pathnodes.h:1536
#define Assert(condition)
Definition: c.h:804
double rows
Definition: pathnodes.h:1164
Selectivity left_mcvfreq
Definition: pathnodes.h:2069
QualCost cost
Definition: pathnodes.h:1086
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
bool enable_hashjoin
Definition: costsize.c:143
Selectivity match_count
Definition: pathnodes.h:2427
Selectivity right_bucketsize
Definition: pathnodes.h:2068
JoinType jointype
Definition: pathnodes.h:1538
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:1618
double clamp_row_est(double nrows)
Definition: costsize.c:196
Definition: pg_list.h:50
double Cost
Definition: nodes.h:667
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 3268 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().

3271 {
3272  Path *outer_path = path->jpath.outerjoinpath;
3273  Path *inner_path = path->jpath.innerjoinpath;
3274  double inner_path_rows = inner_path->rows;
3275  List *mergeclauses = path->path_mergeclauses;
3276  List *innersortkeys = path->innersortkeys;
3277  Cost startup_cost = workspace->startup_cost;
3278  Cost run_cost = workspace->run_cost;
3279  Cost inner_run_cost = workspace->inner_run_cost;
3280  double outer_rows = workspace->outer_rows;
3281  double inner_rows = workspace->inner_rows;
3282  double outer_skip_rows = workspace->outer_skip_rows;
3283  double inner_skip_rows = workspace->inner_skip_rows;
3284  Cost cpu_per_tuple,
3285  bare_inner_cost,
3286  mat_inner_cost;
3287  QualCost merge_qual_cost;
3288  QualCost qp_qual_cost;
3289  double mergejointuples,
3290  rescannedtuples;
3291  double rescanratio;
3292 
3293  /* Protect some assumptions below that rowcounts aren't zero */
3294  if (inner_path_rows <= 0)
3295  inner_path_rows = 1;
3296 
3297  /* Mark the path with the correct row estimate */
3298  if (path->jpath.path.param_info)
3299  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3300  else
3301  path->jpath.path.rows = path->jpath.path.parent->rows;
3302 
3303  /* For partial paths, scale row estimate. */
3304  if (path->jpath.path.parallel_workers > 0)
3305  {
3306  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3307 
3308  path->jpath.path.rows =
3309  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3310  }
3311 
3312  /*
3313  * We could include disable_cost in the preliminary estimate, but that
3314  * would amount to optimizing for the case where the join method is
3315  * disabled, which doesn't seem like the way to bet.
3316  */
3317  if (!enable_mergejoin)
3318  startup_cost += disable_cost;
3319 
3320  /*
3321  * Compute cost of the mergequals and qpquals (other restriction clauses)
3322  * separately.
3323  */
3324  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
3325  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3326  qp_qual_cost.startup -= merge_qual_cost.startup;
3327  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
3328 
3329  /*
3330  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3331  * executor will stop scanning for matches after the first match. When
3332  * all the joinclauses are merge clauses, this means we don't ever need to
3333  * back up the merge, and so we can skip mark/restore overhead.
3334  */
3335  if ((path->jpath.jointype == JOIN_SEMI ||
3336  path->jpath.jointype == JOIN_ANTI ||
3337  extra->inner_unique) &&
3340  path->skip_mark_restore = true;
3341  else
3342  path->skip_mark_restore = false;
3343 
3344  /*
3345  * Get approx # tuples passing the mergequals. We use approx_tuple_count
3346  * here because we need an estimate done with JOIN_INNER semantics.
3347  */
3348  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
3349 
3350  /*
3351  * When there are equal merge keys in the outer relation, the mergejoin
3352  * must rescan any matching tuples in the inner relation. This means
3353  * re-fetching inner tuples; we have to estimate how often that happens.
3354  *
3355  * For regular inner and outer joins, the number of re-fetches can be
3356  * estimated approximately as size of merge join output minus size of
3357  * inner relation. Assume that the distinct key values are 1, 2, ..., and
3358  * denote the number of values of each key in the outer relation as m1,
3359  * m2, ...; in the inner relation, n1, n2, ... Then we have
3360  *
3361  * size of join = m1 * n1 + m2 * n2 + ...
3362  *
3363  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
3364  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
3365  * relation
3366  *
3367  * This equation works correctly for outer tuples having no inner match
3368  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
3369  * are effectively subtracting those from the number of rescanned tuples,
3370  * when we should not. Can we do better without expensive selectivity
3371  * computations?
3372  *
3373  * The whole issue is moot if we are working from a unique-ified outer
3374  * input, or if we know we don't need to mark/restore at all.
3375  */
3376  if (IsA(outer_path, UniquePath) || path->skip_mark_restore)
3377  rescannedtuples = 0;
3378  else
3379  {
3380  rescannedtuples = mergejointuples - inner_path_rows;
3381  /* Must clamp because of possible underestimate */
3382  if (rescannedtuples < 0)
3383  rescannedtuples = 0;
3384  }
3385 
3386  /*
3387  * We'll inflate various costs this much to account for rescanning. Note
3388  * that this is to be multiplied by something involving inner_rows, or
3389  * another number related to the portion of the inner rel we'll scan.
3390  */
3391  rescanratio = 1.0 + (rescannedtuples / inner_rows);
3392 
3393  /*
3394  * Decide whether we want to materialize the inner input to shield it from
3395  * mark/restore and performing re-fetches. Our cost model for regular
3396  * re-fetches is that a re-fetch costs the same as an original fetch,
3397  * which is probably an overestimate; but on the other hand we ignore the
3398  * bookkeeping costs of mark/restore. Not clear if it's worth developing
3399  * a more refined model. So we just need to inflate the inner run cost by
3400  * rescanratio.
3401  */
3402  bare_inner_cost = inner_run_cost * rescanratio;
3403 
3404  /*
3405  * When we interpose a Material node the re-fetch cost is assumed to be
3406  * just cpu_operator_cost per tuple, independently of the underlying
3407  * plan's cost; and we charge an extra cpu_operator_cost per original
3408  * fetch as well. Note that we're assuming the materialize node will
3409  * never spill to disk, since it only has to remember tuples back to the
3410  * last mark. (If there are a huge number of duplicates, our other cost
3411  * factors will make the path so expensive that it probably won't get
3412  * chosen anyway.) So we don't use cost_rescan here.
3413  *
3414  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3415  * of the generated Material node.
3416  */
3417  mat_inner_cost = inner_run_cost +
3418  cpu_operator_cost * inner_rows * rescanratio;
3419 
3420  /*
3421  * If we don't need mark/restore at all, we don't need materialization.
3422  */
3423  if (path->skip_mark_restore)
3424  path->materialize_inner = false;
3425 
3426  /*
3427  * Prefer materializing if it looks cheaper, unless the user has asked to
3428  * suppress materialization.
3429  */
3430  else if (enable_material && mat_inner_cost < bare_inner_cost)
3431  path->materialize_inner = true;
3432 
3433  /*
3434  * Even if materializing doesn't look cheaper, we *must* do it if the
3435  * inner path is to be used directly (without sorting) and it doesn't
3436  * support mark/restore.
3437  *
3438  * Since the inner side must be ordered, and only Sorts and IndexScans can
3439  * create order to begin with, and they both support mark/restore, you
3440  * might think there's no problem --- but you'd be wrong. Nestloop and
3441  * merge joins can *preserve* the order of their inputs, so they can be
3442  * selected as the input of a mergejoin, and they don't support
3443  * mark/restore at present.
3444  *
3445  * We don't test the value of enable_material here, because
3446  * materialization is required for correctness in this case, and turning
3447  * it off does not entitle us to deliver an invalid plan.
3448  */
3449  else if (innersortkeys == NIL &&
3450  !ExecSupportsMarkRestore(inner_path))
3451  path->materialize_inner = true;
3452 
3453  /*
3454  * Also, force materializing if the inner path is to be sorted and the
3455  * sort is expected to spill to disk. This is because the final merge
3456  * pass can be done on-the-fly if it doesn't have to support mark/restore.
3457  * We don't try to adjust the cost estimates for this consideration,
3458  * though.
3459  *
3460  * Since materialization is a performance optimization in this case,
3461  * rather than necessary for correctness, we skip it if enable_material is
3462  * off.
3463  */
3464  else if (enable_material && innersortkeys != NIL &&
3465  relation_byte_size(inner_path_rows,
3466  inner_path->pathtarget->width) >
3467  (work_mem * 1024L))
3468  path->materialize_inner = true;
3469  else
3470  path->materialize_inner = false;
3471 
3472  /* Charge the right incremental cost for the chosen case */
3473  if (path->materialize_inner)
3474  run_cost += mat_inner_cost;
3475  else
3476  run_cost += bare_inner_cost;
3477 
3478  /* CPU costs */
3479 
3480  /*
3481  * The number of tuple comparisons needed is approximately number of outer
3482  * rows plus number of inner rows plus number of rescanned tuples (can we
3483  * refine this?). At each one, we need to evaluate the mergejoin quals.
3484  */
3485  startup_cost += merge_qual_cost.startup;
3486  startup_cost += merge_qual_cost.per_tuple *
3487  (outer_skip_rows + inner_skip_rows * rescanratio);
3488  run_cost += merge_qual_cost.per_tuple *
3489  ((outer_rows - outer_skip_rows) +
3490  (inner_rows - inner_skip_rows) * rescanratio);
3491 
3492  /*
3493  * For each tuple that gets through the mergejoin proper, we charge
3494  * cpu_tuple_cost plus the cost of evaluating additional restriction
3495  * clauses that are to be applied at the join. (This is pessimistic since
3496  * not all of the quals may get evaluated at each tuple.)
3497  *
3498  * Note: we could adjust for SEMI/ANTI joins skipping some qual
3499  * evaluations here, but it's probably not worth the trouble.
3500  */
3501  startup_cost += qp_qual_cost.startup;
3502  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3503  run_cost += cpu_per_tuple * mergejointuples;
3504 
3505  /* tlist eval costs are paid per output row, not per tuple scanned */
3506  startup_cost += path->jpath.path.pathtarget->cost.startup;
3507  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3508 
3509  path->jpath.path.startup_cost = startup_cost;
3510  path->jpath.path.total_cost = startup_cost + run_cost;
3511 }
#define NIL
Definition: pg_list.h:65
List * path_mergeclauses
Definition: pathnodes.h:1599
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
PathTarget * pathtarget
Definition: pathnodes.h:1155
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:414
bool materialize_inner
Definition: pathnodes.h:1603
Path * innerjoinpath
Definition: pathnodes.h:1544
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4690
int parallel_workers
Definition: pathnodes.h:1161
ParamPathInfo * param_info
Definition: pathnodes.h:1157
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
bool skip_mark_restore
Definition: pathnodes.h:1602
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4161
Cost startup_cost
Definition: pathnodes.h:1165
Cost disable_cost
Definition: costsize.c:128
List * joinrestrictinfo
Definition: pathnodes.h:1546
RelOptInfo * parent
Definition: pathnodes.h:1154
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5864
double cpu_operator_cost
Definition: costsize.c:122
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5843
Path * outerjoinpath
Definition: pathnodes.h:1543
int work_mem
Definition: globals.c:122
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
double outer_skip_rows
Definition: pathnodes.h:2564
bool enable_mergejoin
Definition: costsize.c:142
Path path
Definition: pathnodes.h:1536
double rows
Definition: pathnodes.h:1164
QualCost cost
Definition: pathnodes.h:1086
static int list_length(const List *l)
Definition: pg_list.h:149
List * innersortkeys
Definition: pathnodes.h:1601
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
JoinType jointype
Definition: pathnodes.h:1538
JoinPath jpath
Definition: pathnodes.h:1598
double inner_skip_rows
Definition: pathnodes.h:2565
double clamp_row_est(double nrows)
Definition: costsize.c:196
Definition: pg_list.h:50
double Cost
Definition: nodes.h:667
bool enable_material
Definition: costsize.c:141

◆ final_cost_nestloop()

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

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

2835 {
2836  Path *outer_path = path->outerjoinpath;
2837  Path *inner_path = path->innerjoinpath;
2838  double outer_path_rows = outer_path->rows;
2839  double inner_path_rows = inner_path->rows;
2840  Cost startup_cost = workspace->startup_cost;
2841  Cost run_cost = workspace->run_cost;
2842  Cost cpu_per_tuple;
2843  QualCost restrict_qual_cost;
2844  double ntuples;
2845 
2846  /* Protect some assumptions below that rowcounts aren't zero */
2847  if (outer_path_rows <= 0)
2848  outer_path_rows = 1;
2849  if (inner_path_rows <= 0)
2850  inner_path_rows = 1;
2851  /* Mark the path with the correct row estimate */
2852  if (path->path.param_info)
2853  path->path.rows = path->path.param_info->ppi_rows;
2854  else
2855  path->path.rows = path->path.parent->rows;
2856 
2857  /* For partial paths, scale row estimate. */
2858  if (path->path.parallel_workers > 0)
2859  {
2860  double parallel_divisor = get_parallel_divisor(&path->path);
2861 
2862  path->path.rows =
2863  clamp_row_est(path->path.rows / parallel_divisor);
2864  }
2865 
2866  /*
2867  * We could include disable_cost in the preliminary estimate, but that
2868  * would amount to optimizing for the case where the join method is
2869  * disabled, which doesn't seem like the way to bet.
2870  */
2871  if (!enable_nestloop)
2872  startup_cost += disable_cost;
2873 
2874  /* cost of inner-relation source data (we already dealt with outer rel) */
2875 
2876  if (path->jointype == JOIN_SEMI || path->jointype == JOIN_ANTI ||
2877  extra->inner_unique)
2878  {
2879  /*
2880  * With a SEMI or ANTI join, or if the innerrel is known unique, the
2881  * executor will stop after the first match.
2882  */
2883  Cost inner_run_cost = workspace->inner_run_cost;
2884  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
2885  double outer_matched_rows;
2886  double outer_unmatched_rows;
2887  Selectivity inner_scan_frac;
2888 
2889  /*
2890  * For an outer-rel row that has at least one match, we can expect the
2891  * inner scan to stop after a fraction 1/(match_count+1) of the inner
2892  * rows, if the matches are evenly distributed. Since they probably
2893  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
2894  * that fraction. (If we used a larger fuzz factor, we'd have to
2895  * clamp inner_scan_frac to at most 1.0; but since match_count is at
2896  * least 1, no such clamp is needed now.)
2897  */
2898  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
2899  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
2900  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
2901 
2902  /*
2903  * Compute number of tuples processed (not number emitted!). First,
2904  * account for successfully-matched outer rows.
2905  */
2906  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
2907 
2908  /*
2909  * Now we need to estimate the actual costs of scanning the inner
2910  * relation, which may be quite a bit less than N times inner_run_cost
2911  * due to early scan stops. We consider two cases. If the inner path
2912  * is an indexscan using all the joinquals as indexquals, then an
2913  * unmatched outer row results in an indexscan returning no rows,
2914  * which is probably quite cheap. Otherwise, the executor will have
2915  * to scan the whole inner rel for an unmatched row; not so cheap.
2916  */
2917  if (has_indexed_join_quals(path))
2918  {
2919  /*
2920  * Successfully-matched outer rows will only require scanning
2921  * inner_scan_frac of the inner relation. In this case, we don't
2922  * need to charge the full inner_run_cost even when that's more
2923  * than inner_rescan_run_cost, because we can assume that none of
2924  * the inner scans ever scan the whole inner relation. So it's
2925  * okay to assume that all the inner scan executions can be
2926  * fractions of the full cost, even if materialization is reducing
2927  * the rescan cost. At this writing, it's impossible to get here
2928  * for a materialized inner scan, so inner_run_cost and
2929  * inner_rescan_run_cost will be the same anyway; but just in
2930  * case, use inner_run_cost for the first matched tuple and
2931  * inner_rescan_run_cost for additional ones.
2932  */
2933  run_cost += inner_run_cost * inner_scan_frac;
2934  if (outer_matched_rows > 1)
2935  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
2936 
2937  /*
2938  * Add the cost of inner-scan executions for unmatched outer rows.
2939  * We estimate this as the same cost as returning the first tuple
2940  * of a nonempty scan. We consider that these are all rescans,
2941  * since we used inner_run_cost once already.
2942  */
2943  run_cost += outer_unmatched_rows *
2944  inner_rescan_run_cost / inner_path_rows;
2945 
2946  /*
2947  * We won't be evaluating any quals at all for unmatched rows, so
2948  * don't add them to ntuples.
2949  */
2950  }
2951  else
2952  {
2953  /*
2954  * Here, a complicating factor is that rescans may be cheaper than
2955  * first scans. If we never scan all the way to the end of the
2956  * inner rel, it might be (depending on the plan type) that we'd
2957  * never pay the whole inner first-scan run cost. However it is
2958  * difficult to estimate whether that will happen (and it could
2959  * not happen if there are any unmatched outer rows!), so be
2960  * conservative and always charge the whole first-scan cost once.
2961  * We consider this charge to correspond to the first unmatched
2962  * outer row, unless there isn't one in our estimate, in which
2963  * case blame it on the first matched row.
2964  */
2965 
2966  /* First, count all unmatched join tuples as being processed */
2967  ntuples += outer_unmatched_rows * inner_path_rows;
2968 
2969  /* Now add the forced full scan, and decrement appropriate count */
2970  run_cost += inner_run_cost;
2971  if (outer_unmatched_rows >= 1)
2972  outer_unmatched_rows -= 1;
2973  else
2974  outer_matched_rows -= 1;
2975 
2976  /* Add inner run cost for additional outer tuples having matches */
2977  if (outer_matched_rows > 0)
2978  run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
2979 
2980  /* Add inner run cost for additional unmatched outer tuples */
2981  if (outer_unmatched_rows > 0)
2982  run_cost += outer_unmatched_rows * inner_rescan_run_cost;
2983  }
2984  }
2985  else
2986  {
2987  /* Normal-case source costs were included in preliminary estimate */
2988 
2989  /* Compute number of tuples processed (not number emitted!) */
2990  ntuples = outer_path_rows * inner_path_rows;
2991  }
2992 
2993  /* CPU costs */
2994  cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
2995  startup_cost += restrict_qual_cost.startup;
2996  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
2997  run_cost += cpu_per_tuple * ntuples;
2998 
2999  /* tlist eval costs are paid per output row, not per tuple scanned */
3000  startup_cost += path->path.pathtarget->cost.startup;
3001  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
3002 
3003  path->path.startup_cost = startup_cost;
3004  path->path.total_cost = startup_cost + run_cost;
3005 }
PathTarget * pathtarget
Definition: pathnodes.h:1155
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:2449
bool enable_nestloop
Definition: costsize.c:140
Selectivity outer_match_frac
Definition: pathnodes.h:2426
Path * innerjoinpath
Definition: pathnodes.h:1544
int parallel_workers
Definition: pathnodes.h:1161
ParamPathInfo * param_info
Definition: pathnodes.h:1157
double Selectivity
Definition: nodes.h:666
Cost inner_rescan_run_cost
Definition: pathnodes.h:2559
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:4161
Cost startup_cost
Definition: pathnodes.h:1165
Cost disable_cost
Definition: costsize.c:128
List * joinrestrictinfo
Definition: pathnodes.h:1546
RelOptInfo * parent
Definition: pathnodes.h:1154
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5864
Path * outerjoinpath
Definition: pathnodes.h:1543
double rows
Definition: pathnodes.h:673
Cost total_cost
Definition: pathnodes.h:1166
Path path
Definition: pathnodes.h:1536
static bool has_indexed_join_quals(NestPath *joinpath)
Definition: costsize.c:4598
double rows
Definition: pathnodes.h:1164
QualCost cost
Definition: pathnodes.h:1086
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1114
Selectivity match_count
Definition: pathnodes.h:2427
JoinType jointype
Definition: pathnodes.h:1538
double clamp_row_est(double nrows)
Definition: costsize.c:196
double Cost
Definition: nodes.h:667

◆ get_parameterized_baserel_size()

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

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

4778 {
4779  List *allclauses;
4780  double nrows;
4781 
4782  /*
4783  * Estimate the number of rows returned by the parameterized scan, knowing
4784  * that it will apply all the extra join clauses as well as the rel's own
4785  * restriction clauses. Note that we force the clauses to be treated as
4786  * non-join clauses during selectivity estimation.
4787  */
4788  allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
4789  nrows = rel->tuples *
4791  allclauses,
4792  rel->relid, /* do not use 0! */
4793  JOIN_INNER,
4794  NULL);
4795  nrows = clamp_row_est(nrows);
4796  /* For safety, make sure result is not more than the base estimate */
4797  if (nrows > rel->rows)
4798  nrows = rel->rows;
4799  return nrows;
4800 }
double tuples
Definition: pathnodes.h:710
List * baserestrictinfo
Definition: pathnodes.h:734
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:567
Index relid
Definition: pathnodes.h:698
double rows
Definition: pathnodes.h:673
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
double clamp_row_est(double nrows)
Definition: costsize.c:196
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 4857 of file costsize.c.

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

Referenced by get_joinrel_parampathinfo().

4862 {
4863  double nrows;
4864 
4865  /*
4866  * Estimate the number of rows returned by the parameterized join as the
4867  * sizes of the input paths times the selectivity of the clauses that have
4868  * ended up at this join node.
4869  *
4870  * As with set_joinrel_size_estimates, the rowcount estimate could depend
4871  * on the pair of input paths provided, though ideally we'd get the same
4872  * estimate for any pair with the same parameterization.
4873  */
4874  nrows = calc_joinrel_size_estimate(root,
4875  rel,
4876  outer_path->parent,
4877  inner_path->parent,
4878  outer_path->rows,
4879  inner_path->rows,
4880  sjinfo,
4881  restrict_clauses);
4882  /* For safety, make sure result is not more than the base estimate */
4883  if (nrows > rel->rows)
4884  nrows = rel->rows;
4885  return nrows;
4886 }
RelOptInfo * parent
Definition: pathnodes.h:1154
double rows
Definition: pathnodes.h:673
double rows
Definition: pathnodes.h:1164
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:4898

◆ index_pages_fetched()

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

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

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

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

3602 {
3603  Cost startup_cost = 0;
3604  Cost run_cost = 0;
3605  double outer_path_rows = outer_path->rows;
3606  double inner_path_rows = inner_path->rows;
3607  double inner_path_rows_total = inner_path_rows;
3608  int num_hashclauses = list_length(hashclauses);
3609  int numbuckets;
3610  int numbatches;
3611  int num_skew_mcvs;
3612  size_t space_allowed; /* unused */
3613 
3614  /* cost of source data */
3615  startup_cost += outer_path->startup_cost;
3616  run_cost += outer_path->total_cost - outer_path->startup_cost;
3617  startup_cost += inner_path->total_cost;
3618 
3619  /*
3620  * Cost of computing hash function: must do it once per input tuple. We
3621  * charge one cpu_operator_cost for each column's hash function. Also,
3622  * tack on one cpu_tuple_cost per inner row, to model the costs of
3623  * inserting the row into the hashtable.
3624  *
3625  * XXX when a hashclause is more complex than a single operator, we really
3626  * should charge the extra eval costs of the left or right side, as
3627  * appropriate, here. This seems more work than it's worth at the moment.
3628  */
3629  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
3630  * inner_path_rows;
3631  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
3632 
3633  /*
3634  * If this is a parallel hash build, then the value we have for
3635  * inner_rows_total currently refers only to the rows returned by each
3636  * participant. For shared hash table size estimation, we need the total
3637  * number, so we need to undo the division.
3638  */
3639  if (parallel_hash)
3640  inner_path_rows_total *= get_parallel_divisor(inner_path);
3641 
3642  /*
3643  * Get hash table size that executor would use for inner relation.
3644  *
3645  * XXX for the moment, always assume that skew optimization will be
3646  * performed. As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
3647  * trying to determine that for sure.
3648  *
3649  * XXX at some point it might be interesting to try to account for skew
3650  * optimization in the cost estimate, but for now, we don't.
3651  */
3652  ExecChooseHashTableSize(inner_path_rows_total,
3653  inner_path->pathtarget->width,
3654  true, /* useskew */
3655  parallel_hash, /* try_combined_hash_mem */
3656  outer_path->parallel_workers,
3657  &space_allowed,
3658  &numbuckets,
3659  &numbatches,
3660  &num_skew_mcvs);
3661 
3662  /*
3663  * If inner relation is too big then we will need to "batch" the join,
3664  * which implies writing and reading most of the tuples to disk an extra
3665  * time. Charge seq_page_cost per page, since the I/O should be nice and
3666  * sequential. Writing the inner rel counts as startup cost, all the rest
3667  * as run cost.
3668  */
3669  if (numbatches > 1)
3670  {
3671  double outerpages = page_size(outer_path_rows,
3672  outer_path->pathtarget->width);
3673  double innerpages = page_size(inner_path_rows,
3674  inner_path->pathtarget->width);
3675 
3676  startup_cost += seq_page_cost * innerpages;
3677  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
3678  }
3679 
3680  /* CPU costs left for later */
3681 
3682  /* Public result fields */
3683  workspace->startup_cost = startup_cost;
3684  workspace->total_cost = startup_cost + run_cost;
3685  /* Save private data for final_cost_hashjoin */
3686  workspace->run_cost = run_cost;
3687  workspace->numbuckets = numbuckets;
3688  workspace->numbatches = numbatches;
3689  workspace->inner_rows_total = inner_path_rows_total;
3690 }
PathTarget * pathtarget
Definition: pathnodes.h:1155
int parallel_workers
Definition: pathnodes.h:1161
static double page_size(double tuples, int width)
Definition: costsize.c:5854
Cost startup_cost
Definition: pathnodes.h:1165
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5864
double cpu_operator_cost
Definition: costsize.c:122
double inner_rows_total
Definition: pathnodes.h:2570
Cost total_cost
Definition: pathnodes.h:1166
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:1164
static int list_length(const List *l)
Definition: pg_list.h:149
double cpu_tuple_cost
Definition: costsize.c:120
double seq_page_cost
Definition: costsize.c:118
double Cost
Definition: nodes.h:667

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

3044 {
3045  Cost startup_cost = 0;
3046  Cost run_cost = 0;
3047  double outer_path_rows = outer_path->rows;
3048  double inner_path_rows = inner_path->rows;
3049  Cost inner_run_cost;
3050  double outer_rows,
3051  inner_rows,
3052  outer_skip_rows,
3053  inner_skip_rows;
3054  Selectivity outerstartsel,
3055  outerendsel,
3056  innerstartsel,
3057  innerendsel;
3058  Path sort_path; /* dummy for result of cost_sort */
3059 
3060  /* Protect some assumptions below that rowcounts aren't zero */
3061  if (outer_path_rows <= 0)
3062  outer_path_rows = 1;
3063  if (inner_path_rows <= 0)
3064  inner_path_rows = 1;
3065 
3066  /*
3067  * A merge join will stop as soon as it exhausts either input stream
3068  * (unless it's an outer join, in which case the outer side has to be
3069  * scanned all the way anyway). Estimate fraction of the left and right
3070  * inputs that will actually need to be scanned. Likewise, we can
3071  * estimate the number of rows that will be skipped before the first join
3072  * pair is found, which should be factored into startup cost. We use only
3073  * the first (most significant) merge clause for this purpose. Since
3074  * mergejoinscansel() is a fairly expensive computation, we cache the
3075  * results in the merge clause RestrictInfo.
3076  */
3077  if (mergeclauses && jointype != JOIN_FULL)
3078  {
3079  RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
3080  List *opathkeys;
3081  List *ipathkeys;
3082  PathKey *opathkey;
3083  PathKey *ipathkey;
3084  MergeScanSelCache *cache;
3085 
3086  /* Get the input pathkeys to determine the sort-order details */
3087  opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
3088  ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
3089  Assert(opathkeys);
3090  Assert(ipathkeys);
3091  opathkey = (PathKey *) linitial(opathkeys);
3092  ipathkey = (PathKey *) linitial(ipathkeys);
3093  /* debugging check */
3094  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
3095  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
3096  opathkey->pk_strategy != ipathkey->pk_strategy ||
3097  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
3098  elog(ERROR, "left and right pathkeys do not match in mergejoin");
3099 
3100  /* Get the selectivity with caching */
3101  cache = cached_scansel(root, firstclause, opathkey);
3102 
3103  if (bms_is_subset(firstclause->left_relids,
3104  outer_path->parent->relids))
3105  {
3106  /* left side of clause is outer */
3107  outerstartsel = cache->leftstartsel;
3108  outerendsel = cache->leftendsel;
3109  innerstartsel = cache->rightstartsel;
3110  innerendsel = cache->rightendsel;
3111  }
3112  else
3113  {
3114  /* left side of clause is inner */
3115  outerstartsel = cache->rightstartsel;
3116  outerendsel = cache->rightendsel;
3117  innerstartsel = cache->leftstartsel;
3118  innerendsel = cache->leftendsel;
3119  }
3120  if (jointype == JOIN_LEFT ||
3121  jointype == JOIN_ANTI)
3122  {
3123  outerstartsel = 0.0;
3124  outerendsel = 1.0;
3125  }
3126  else if (jointype == JOIN_RIGHT)
3127  {
3128  innerstartsel = 0.0;
3129  innerendsel = 1.0;
3130  }
3131  }
3132  else
3133  {
3134  /* cope with clauseless or full mergejoin */
3135  outerstartsel = innerstartsel = 0.0;
3136  outerendsel = innerendsel = 1.0;
3137  }
3138 
3139  /*
3140  * Convert selectivities to row counts. We force outer_rows and
3141  * inner_rows to be at least 1, but the skip_rows estimates can be zero.
3142  */
3143  outer_skip_rows = rint(outer_path_rows * outerstartsel);
3144  inner_skip_rows = rint(inner_path_rows * innerstartsel);
3145  outer_rows = clamp_row_est(outer_path_rows * outerendsel);
3146  inner_rows = clamp_row_est(inner_path_rows * innerendsel);
3147 
3148  Assert(outer_skip_rows <= outer_rows);
3149  Assert(inner_skip_rows <= inner_rows);
3150 
3151  /*
3152  * Readjust scan selectivities to account for above rounding. This is
3153  * normally an insignificant effect, but when there are only a few rows in
3154  * the inputs, failing to do this makes for a large percentage error.
3155  */
3156  outerstartsel = outer_skip_rows / outer_path_rows;
3157  innerstartsel = inner_skip_rows / inner_path_rows;
3158  outerendsel = outer_rows / outer_path_rows;
3159  innerendsel = inner_rows / inner_path_rows;
3160 
3161  Assert(outerstartsel <= outerendsel);
3162  Assert(innerstartsel <= innerendsel);
3163 
3164  /* cost of source data */
3165 
3166  if (outersortkeys) /* do we need to sort outer? */
3167  {
3168  cost_sort(&sort_path,
3169  root,
3170  outersortkeys,
3171  outer_path->total_cost,
3172  outer_path_rows,
3173  outer_path->pathtarget->width,
3174  0.0,
3175  work_mem,
3176  -1.0);
3177  startup_cost += sort_path.startup_cost;
3178  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3179  * outerstartsel;
3180  run_cost += (sort_path.total_cost - sort_path.startup_cost)
3181  * (outerendsel - outerstartsel);
3182  }
3183  else
3184  {
3185  startup_cost += outer_path->startup_cost;
3186  startup_cost += (outer_path->total_cost - outer_path->startup_cost)
3187  * outerstartsel;
3188  run_cost += (outer_path->total_cost - outer_path->startup_cost)
3189  * (outerendsel - outerstartsel);
3190  }
3191 
3192  if (innersortkeys) /* do we need to sort inner? */
3193  {
3194  cost_sort(&sort_path,
3195  root,
3196  innersortkeys,
3197  inner_path->total_cost,
3198  inner_path_rows,
3199  inner_path->pathtarget->width,
3200  0.0,
3201  work_mem,
3202  -1.0);
3203  startup_cost += sort_path.startup_cost;
3204  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3205  * innerstartsel;
3206  inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
3207  * (innerendsel - innerstartsel);
3208  }
3209  else
3210  {
3211  startup_cost += inner_path->startup_cost;
3212  startup_cost += (inner_path->total_cost - inner_path->startup_cost)
3213  * innerstartsel;
3214  inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
3215  * (innerendsel - innerstartsel);
3216  }
3217 
3218  /*
3219  * We can't yet determine whether rescanning occurs, or whether
3220  * materialization of the inner input should be done. The minimum
3221  * possible inner input cost, regardless of rescan and materialization
3222  * considerations, is inner_run_cost. We include that in
3223  * workspace->total_cost, but not yet in run_cost.
3224  */
3225 
3226  /* CPU costs left for later */
3227 
3228  /* Public result fields */
3229  workspace->startup_cost = startup_cost;
3230  workspace->total_cost = startup_cost + run_cost + inner_run_cost;
3231  /* Save private data for final_cost_mergejoin */
3232  workspace->run_cost = run_cost;
3233  workspace->inner_run_cost = inner_run_cost;
3234  workspace->outer_rows = outer_rows;
3235  workspace->inner_rows = inner_rows;
3236  workspace->outer_skip_rows = outer_skip_rows;
3237  workspace->inner_skip_rows = inner_skip_rows;
3238 }
Selectivity leftendsel
Definition: pathnodes.h:2103
PathTarget * pathtarget
Definition: pathnodes.h:1155
static MergeScanSelCache * cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
Definition: costsize.c:3517
Relids left_relids
Definition: pathnodes.h:2033
double Selectivity
Definition: nodes.h:666
int pk_strategy
Definition: pathnodes.h:1053
#define linitial(l)
Definition: pg_list.h:174
bool pk_nulls_first
Definition: pathnodes.h:1054
#define ERROR
Definition: elog.h:45
Cost startup_cost
Definition: pathnodes.h:1165
RelOptInfo * parent
Definition: pathnodes.h:1154
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
Selectivity rightstartsel
Definition: pathnodes.h:2104
Relids relids
Definition: pathnodes.h:670
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:2032
int work_mem
Definition: globals.c:122
Cost total_cost
Definition: pathnodes.h:1166
double outer_skip_rows
Definition: pathnodes.h:2564
List * pathkeys
Definition: pathnodes.h:1168
#define Assert(condition)
Definition: c.h:804
double rows
Definition: pathnodes.h:1164
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1051
Oid pk_opfamily
Definition: pathnodes.h:1052
#define elog(elevel,...)
Definition: elog.h:227
double inner_skip_rows
Definition: pathnodes.h:2565
double clamp_row_est(double nrows)
Definition: costsize.c:196
Definition: pg_list.h:50
Selectivity rightendsel
Definition: pathnodes.h:2105
double Cost
Definition: nodes.h:667
Selectivity leftstartsel
Definition: pathnodes.h:2102

◆ initial_cost_nestloop()

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

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

2761 {
2762  Cost startup_cost = 0;
2763  Cost run_cost = 0;
2764  double outer_path_rows = outer_path->rows;
2765  Cost inner_rescan_start_cost;
2766  Cost inner_rescan_total_cost;
2767  Cost inner_run_cost;
2768  Cost inner_rescan_run_cost;
2769 
2770  /* estimate costs to rescan the inner relation */
2771  cost_rescan(root, inner_path,
2772  &inner_rescan_start_cost,
2773  &inner_rescan_total_cost);
2774 
2775  /* cost of source data */
2776 
2777  /*
2778  * NOTE: clearly, we must pay both outer and inner paths' startup_cost
2779  * before we can start returning tuples, so the join's startup cost is
2780  * their sum. We'll also pay the inner path's rescan startup cost
2781  * multiple times.
2782  */
2783  startup_cost += outer_path->startup_cost + inner_path->startup_cost;
2784  run_cost += outer_path->total_cost - outer_path->startup_cost;
2785  if (outer_path_rows > 1)
2786