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_memoize
 
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 bool enable_async_append
 
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 6075 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().

6077 {
6078  Cost indexTotalCost;
6079  Selectivity indexSelectivity;
6080  double T;
6081  double pages_fetched;
6082  double tuples_fetched;
6083  double heap_pages;
6084  long maxentries;
6085 
6086  /*
6087  * Fetch total cost of obtaining the bitmap, as well as its total
6088  * selectivity.
6089  */
6090  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6091 
6092  /*
6093  * Estimate number of main-table pages fetched.
6094  */
6095  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6096 
6097  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
6098 
6099  /*
6100  * For a single scan, the number of heap pages that need to be fetched is
6101  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
6102  * re-reads needed).
6103  */
6104  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
6105 
6106  /*
6107  * Calculate the number of pages fetched from the heap. Then based on
6108  * current work_mem estimate get the estimated maxentries in the bitmap.
6109  * (Note that we always do this calculation based on the number of pages
6110  * that would be fetched in a single iteration, even if loop_count > 1.
6111  * That's correct, because only that number of entries will be stored in
6112  * the bitmap at one time.)
6113  */
6114  heap_pages = Min(pages_fetched, baserel->pages);
6115  maxentries = tbm_calculate_entries(work_mem * 1024L);
6116 
6117  if (loop_count > 1)
6118  {
6119  /*
6120  * For repeated bitmap scans, scale up the number of tuples fetched in
6121  * the Mackert and Lohman formula by the number of scans, so that we
6122  * estimate the number of pages fetched by all the scans. Then
6123  * pro-rate for one scan.
6124  */
6125  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6126  baserel->pages,
6127  get_indexpath_pages(bitmapqual),
6128  root);
6129  pages_fetched /= loop_count;
6130  }
6131 
6132  if (pages_fetched >= T)
6133  pages_fetched = T;
6134  else
6135  pages_fetched = ceil(pages_fetched);
6136 
6137  if (maxentries < heap_pages)
6138  {
6139  double exact_pages;
6140  double lossy_pages;
6141 
6142  /*
6143  * Crude approximation of the number of lossy pages. Because of the
6144  * way tbm_lossify() is coded, the number of lossy pages increases
6145  * very sharply as soon as we run short of memory; this formula has
6146  * that property and seems to perform adequately in testing, but it's
6147  * possible we could do better somehow.
6148  */
6149  lossy_pages = Max(0, heap_pages - maxentries / 2);
6150  exact_pages = heap_pages - lossy_pages;
6151 
6152  /*
6153  * If there are lossy pages then recompute the number of tuples
6154  * processed by the bitmap heap node. We assume here that the chance
6155  * of a given tuple coming from an exact page is the same as the
6156  * chance that a given page is exact. This might not be true, but
6157  * it's not clear how we can do any better.
6158  */
6159  if (lossy_pages > 0)
6160  tuples_fetched =
6161  clamp_row_est(indexSelectivity *
6162  (exact_pages / heap_pages) * baserel->tuples +
6163  (lossy_pages / heap_pages) * baserel->tuples);
6164  }
6165 
6166  if (cost)
6167  *cost = indexTotalCost;
6168  if (tuple)
6169  *tuple = tuples_fetched;
6170 
6171  return pages_fetched;
6172 }
#define Min(x, y)
Definition: c.h:986
double Selectivity
Definition: nodes.h:671
int work_mem
Definition: globals.c:124
#define Max(x, y)
Definition: c.h:980
static const uint32 T[65]
Definition: md5.c:119
BlockNumber pages
Definition: pathnodes.h:720
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:905
long tbm_calculate_entries(double maxbytes)
Definition: tidbitmap.c:1545
double clamp_row_est(double nrows)
Definition: costsize.c:199
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:840
double Cost
Definition: nodes.h:672
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1056
Cardinality tuples
Definition: pathnodes.h:721

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

4673 {
4674  Selectivity jselec;
4675  Selectivity nselec;
4676  Selectivity avgmatch;
4677  SpecialJoinInfo norm_sjinfo;
4678  List *joinquals;
4679  ListCell *l;
4680 
4681  /*
4682  * In an ANTI join, we must ignore clauses that are "pushed down", since
4683  * those won't affect the match logic. In a SEMI join, we do not
4684  * distinguish joinquals from "pushed down" quals, so just use the whole
4685  * restrictinfo list. For other outer join types, we should consider only
4686  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
4687  */
4688  if (IS_OUTER_JOIN(jointype))
4689  {
4690  joinquals = NIL;
4691  foreach(l, restrictlist)
4692  {
4693  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4694 
4695  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
4696  joinquals = lappend(joinquals, rinfo);
4697  }
4698  }
4699  else
4700  joinquals = restrictlist;
4701 
4702  /*
4703  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
4704  */
4705  jselec = clauselist_selectivity(root,
4706  joinquals,
4707  0,
4708  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
4709  sjinfo);
4710 
4711  /*
4712  * Also get the normal inner-join selectivity of the join clauses.
4713  */
4714  norm_sjinfo.type = T_SpecialJoinInfo;
4715  norm_sjinfo.min_lefthand = outerrel->relids;
4716  norm_sjinfo.min_righthand = innerrel->relids;
4717  norm_sjinfo.syn_lefthand = outerrel->relids;
4718  norm_sjinfo.syn_righthand = innerrel->relids;
4719  norm_sjinfo.jointype = JOIN_INNER;
4720  /* we don't bother trying to make the remaining fields valid */
4721  norm_sjinfo.lhs_strict = false;
4722  norm_sjinfo.delay_upper_joins = false;
4723  norm_sjinfo.semi_can_btree = false;
4724  norm_sjinfo.semi_can_hash = false;
4725  norm_sjinfo.semi_operators = NIL;
4726  norm_sjinfo.semi_rhs_exprs = NIL;
4727 
4728  nselec = clauselist_selectivity(root,
4729  joinquals,
4730  0,
4731  JOIN_INNER,
4732  &norm_sjinfo);
4733 
4734  /* Avoid leaking a lot of ListCells */
4735  if (IS_OUTER_JOIN(jointype))
4736  list_free(joinquals);
4737 
4738  /*
4739  * jselec can be interpreted as the fraction of outer-rel rows that have
4740  * any matches (this is true for both SEMI and ANTI cases). And nselec is
4741  * the fraction of the Cartesian product that matches. So, the average
4742  * number of matches for each outer-rel row that has at least one match is
4743  * nselec * inner_rows / jselec.
4744  *
4745  * Note: it is correct to use the inner rel's "rows" count here, even
4746  * though we might later be considering a parameterized inner path with
4747  * fewer rows. This is because we have included all the join clauses in
4748  * the selectivity estimate.
4749  */
4750  if (jselec > 0) /* protect against zero divide */
4751  {
4752  avgmatch = nselec * innerrel->rows / jselec;
4753  /* Clamp to sane range */
4754  avgmatch = Max(1.0, avgmatch);
4755  }
4756  else
4757  avgmatch = 1.0;
4758 
4759  semifactors->outer_match_frac = jselec;
4760  semifactors->match_count = avgmatch;
4761 }
#define NIL
Definition: pg_list.h:65
Relids min_righthand
Definition: pathnodes.h:2253
Selectivity outer_match_frac
Definition: pathnodes.h:2510
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:755
double Selectivity
Definition: nodes.h:671
Relids syn_lefthand
Definition: pathnodes.h:2254
Relids syn_righthand
Definition: pathnodes.h:2255
List * semi_rhs_exprs
Definition: pathnodes.h:2263
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Relids relids
Definition: pathnodes.h:681
List * lappend(List *list, void *datum)
Definition: list.c:336
bool delay_upper_joins
Definition: pathnodes.h:2258
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2139
#define Max(x, y)
Definition: c.h:980
Cardinality rows
Definition: pathnodes.h:684
JoinType jointype
Definition: pathnodes.h:2256
Selectivity match_count
Definition: pathnodes.h:2511
List * semi_operators
Definition: pathnodes.h:2262
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:2252

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

2566 {
2567  double output_tuples;
2568  Cost startup_cost;
2569  Cost total_cost;
2570  AggClauseCosts dummy_aggcosts;
2571 
2572  /* Use all-zero per-aggregate costs if NULL is passed */
2573  if (aggcosts == NULL)
2574  {
2575  Assert(aggstrategy == AGG_HASHED);
2576  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
2577  aggcosts = &dummy_aggcosts;
2578  }
2579 
2580  /*
2581  * The transCost.per_tuple component of aggcosts should be charged once
2582  * per input tuple, corresponding to the costs of evaluating the aggregate
2583  * transfns and their input expressions. The finalCost.per_tuple component
2584  * is charged once per output tuple, corresponding to the costs of
2585  * evaluating the finalfns. Startup costs are of course charged but once.
2586  *
2587  * If we are grouping, we charge an additional cpu_operator_cost per
2588  * grouping column per input tuple for grouping comparisons.
2589  *
2590  * We will produce a single output tuple if not grouping, and a tuple per
2591  * group otherwise. We charge cpu_tuple_cost for each output tuple.
2592  *
2593  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2594  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2595  * input path is already sorted appropriately, AGG_SORTED should be
2596  * preferred (since it has no risk of memory overflow). This will happen
2597  * as long as the computed total costs are indeed exactly equal --- but if
2598  * there's roundoff error we might do the wrong thing. So be sure that
2599  * the computations below form the same intermediate values in the same
2600  * order.
2601  */
2602  if (aggstrategy == AGG_PLAIN)
2603  {
2604  startup_cost = input_total_cost;
2605  startup_cost += aggcosts->transCost.startup;
2606  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2607  startup_cost += aggcosts->finalCost.startup;
2608  startup_cost += aggcosts->finalCost.per_tuple;
2609  /* we aren't grouping */
2610  total_cost = startup_cost + cpu_tuple_cost;
2611  output_tuples = 1;
2612  }
2613  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2614  {
2615  /* Here we are able to deliver output on-the-fly */
2616  startup_cost = input_startup_cost;
2617  total_cost = input_total_cost;
2618  if (aggstrategy == AGG_MIXED && !enable_hashagg)
2619  {
2620  startup_cost += disable_cost;
2621  total_cost += disable_cost;
2622  }
2623  /* calcs phrased this way to match HASHED case, see note above */
2624  total_cost += aggcosts->transCost.startup;
2625  total_cost += aggcosts->transCost.per_tuple * input_tuples;
2626  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2627  total_cost += aggcosts->finalCost.startup;
2628  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2629  total_cost += cpu_tuple_cost * numGroups;
2630  output_tuples = numGroups;
2631  }
2632  else
2633  {
2634  /* must be AGG_HASHED */
2635  startup_cost = input_total_cost;
2636  if (!enable_hashagg)
2637  startup_cost += disable_cost;
2638  startup_cost += aggcosts->transCost.startup;
2639  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2640  /* cost of computing hash value */
2641  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2642  startup_cost += aggcosts->finalCost.startup;
2643 
2644  total_cost = startup_cost;
2645  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2646  /* cost of retrieving from hash table */
2647  total_cost += cpu_tuple_cost * numGroups;
2648  output_tuples = numGroups;
2649  }
2650 
2651  /*
2652  * Add the disk costs of hash aggregation that spills to disk.
2653  *
2654  * Groups that go into the hash table stay in memory until finalized, so
2655  * spilling and reprocessing tuples doesn't incur additional invocations
2656  * of transCost or finalCost. Furthermore, the computed hash value is
2657  * stored with the spilled tuples, so we don't incur extra invocations of
2658  * the hash function.
2659  *
2660  * Hash Agg begins returning tuples after the first batch is complete.
2661  * Accrue writes (spilled tuples) to startup_cost and to total_cost;
2662  * accrue reads only to total_cost.
2663  */
2664  if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
2665  {
2666  double pages;
2667  double pages_written = 0.0;
2668  double pages_read = 0.0;
2669  double spill_cost;
2670  double hashentrysize;
2671  double nbatches;
2672  Size mem_limit;
2673  uint64 ngroups_limit;
2674  int num_partitions;
2675  int depth;
2676 
2677  /*
2678  * Estimate number of batches based on the computed limits. If less
2679  * than or equal to one, all groups are expected to fit in memory;
2680  * otherwise we expect to spill.
2681  */
2682  hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
2683  input_width,
2684  aggcosts->transitionSpace);
2685  hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
2686  &ngroups_limit, &num_partitions);
2687 
2688  nbatches = Max((numGroups * hashentrysize) / mem_limit,
2689  numGroups / ngroups_limit);
2690 
2691  nbatches = Max(ceil(nbatches), 1.0);
2692  num_partitions = Max(num_partitions, 2);
2693 
2694  /*
2695  * The number of partitions can change at different levels of
2696  * recursion; but for the purposes of this calculation assume it stays
2697  * constant.
2698  */
2699  depth = ceil(log(nbatches) / log(num_partitions));
2700 
2701  /*
2702  * Estimate number of pages read and written. For each level of
2703  * recursion, a tuple must be written and then later read.
2704  */
2705  pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
2706  pages_written = pages_read = pages * depth;
2707 
2708  /*
2709  * HashAgg has somewhat worse IO behavior than Sort on typical
2710  * hardware/OS combinations. Account for this with a generic penalty.
2711  */
2712  pages_read *= 2.0;
2713  pages_written *= 2.0;
2714 
2715  startup_cost += pages_written * random_page_cost;
2716  total_cost += pages_written * random_page_cost;
2717  total_cost += pages_read * seq_page_cost;
2718 
2719  /* account for CPU cost of spilling a tuple and reading it back */
2720  spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
2721  startup_cost += spill_cost;
2722  total_cost += spill_cost;
2723  }
2724 
2725  /*
2726  * If there are quals (HAVING quals), account for their cost and
2727  * selectivity.
2728  */
2729  if (quals)
2730  {
2731  QualCost qual_cost;
2732 
2733  cost_qual_eval(&qual_cost, quals, root);
2734  startup_cost += qual_cost.startup;
2735  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2736 
2737  output_tuples = clamp_row_est(output_tuples *
2739  quals,
2740  0,
2741  JOIN_INNER,
2742  NULL));
2743  }
2744 
2745  path->rows = output_tuples;
2746  path->startup_cost = startup_cost;
2747  path->total_cost = total_cost;
2748 }
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:120
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1676
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4308
Cost startup_cost
Definition: pathnodes.h:1193
Cost disable_cost
Definition: costsize.c:129
List * aggtransinfos
Definition: pathnodes.h:358
double cpu_operator_cost
Definition: costsize.c:123
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:6021
Cost total_cost
Definition: pathnodes.h:1194
#define Max(x, y)
Definition: c.h:980
#define Assert(condition)
Definition: c.h:804
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:121
bool enable_hashagg
Definition: costsize.c:140
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:1780
Size transitionSpace
Definition: pathnodes.h:60
Cardinality rows
Definition: pathnodes.h:1192
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:199
double seq_page_cost
Definition: costsize.c:119
double Cost
Definition: nodes.h:672

◆ cost_append()

void cost_append ( AppendPath path)

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

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

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

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

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

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

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

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

◆ cost_bitmap_tree_node()

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

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

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

◆ cost_ctescan()

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

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

1610 {
1611  Cost startup_cost = 0;
1612  Cost run_cost = 0;
1613  QualCost qpqual_cost;
1614  Cost cpu_per_tuple;
1615 
1616  /* Should only be applied to base relations that are CTEs */
1617  Assert(baserel->relid > 0);
1618  Assert(baserel->rtekind == RTE_CTE);
1619 
1620  /* Mark the path with the correct row estimate */
1621  if (param_info)
1622  path->rows = param_info->ppi_rows;
1623  else
1624  path->rows = baserel->rows;
1625 
1626  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1627  cpu_per_tuple = cpu_tuple_cost;
1628 
1629  /* Add scanning CPU costs */
1630  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1631 
1632  startup_cost += qpqual_cost.startup;
1633  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1634  run_cost += cpu_per_tuple * baserel->tuples;
1635 
1636  /* tlist eval costs are paid per output row, not per tuple scanned */
1637  startup_cost += path->pathtarget->cost.startup;
1638  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1639 
1640  path->startup_cost = startup_cost;
1641  path->total_cost = startup_cost + run_cost;
1642 }
PathTarget * pathtarget
Definition: pathnodes.h:1183
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
Index relid
Definition: pathnodes.h:709
RTEKind rtekind
Definition: pathnodes.h:711
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
QualCost cost
Definition: pathnodes.h:1112
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:672
Cardinality tuples
Definition: pathnodes.h:721

◆ cost_functionscan()

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

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

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

◆ cost_gather()

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

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

381 {
382  Cost startup_cost = 0;
383  Cost run_cost = 0;
384 
385  /* Mark the path with the correct row estimate */
386  if (rows)
387  path->path.rows = *rows;
388  else if (param_info)
389  path->path.rows = param_info->ppi_rows;
390  else
391  path->path.rows = rel->rows;
392 
393  startup_cost = path->subpath->startup_cost;
394 
395  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
396 
397  /* Parallel setup and communication cost. */
398  startup_cost += parallel_setup_cost;
399  run_cost += parallel_tuple_cost * path->path.rows;
400 
401  path->path.startup_cost = startup_cost;
402  path->path.total_cost = (startup_cost + run_cost);
403 }
double parallel_setup_cost
Definition: costsize.c:125
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup_cost
Definition: pathnodes.h:1193
Path * subpath
Definition: pathnodes.h:1560
Cost total_cost
Definition: pathnodes.h:1194
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:672
double parallel_tuple_cost
Definition: costsize.c:124

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

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

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

2837 {
2838  double output_tuples;
2839  Cost startup_cost;
2840  Cost total_cost;
2841 
2842  output_tuples = numGroups;
2843  startup_cost = input_startup_cost;
2844  total_cost = input_total_cost;
2845 
2846  /*
2847  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2848  * all columns get compared at most of the tuples.
2849  */
2850  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2851 
2852  /*
2853  * If there are quals (HAVING quals), account for their cost and
2854  * selectivity.
2855  */
2856  if (quals)
2857  {
2858  QualCost qual_cost;
2859 
2860  cost_qual_eval(&qual_cost, quals, root);
2861  startup_cost += qual_cost.startup;
2862  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2863 
2864  output_tuples = clamp_row_est(output_tuples *
2866  quals,
2867  0,
2868  JOIN_INNER,
2869  NULL));
2870  }
2871 
2872  path->rows = output_tuples;
2873  path->startup_cost = startup_cost;
2874  path->total_cost = total_cost;
2875 }
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:4308
Cost startup_cost
Definition: pathnodes.h:1193
double cpu_operator_cost
Definition: costsize.c:123
Cost total_cost
Definition: pathnodes.h:1194
Cardinality rows
Definition: pathnodes.h:1192
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:199
double Cost
Definition: nodes.h:672

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

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

◆ cost_index()

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

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

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

◆ cost_material()

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

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

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

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

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

◆ cost_namedtuplestorescan()

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

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

1651 {
1652  Cost startup_cost = 0;
1653  Cost run_cost = 0;
1654  QualCost qpqual_cost;
1655  Cost cpu_per_tuple;
1656 
1657  /* Should only be applied to base relations that are Tuplestores */
1658  Assert(baserel->relid > 0);
1659  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1660 
1661  /* Mark the path with the correct row estimate */
1662  if (param_info)
1663  path->rows = param_info->ppi_rows;
1664  else
1665  path->rows = baserel->rows;
1666 
1667  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1668  cpu_per_tuple = cpu_tuple_cost;
1669 
1670  /* Add scanning CPU costs */
1671  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1672 
1673  startup_cost += qpqual_cost.startup;
1674  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1675  run_cost += cpu_per_tuple * baserel->tuples;
1676 
1677  path->startup_cost = startup_cost;
1678  path->total_cost = startup_cost + run_cost;
1679 }
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
Index relid
Definition: pathnodes.h:709
RTEKind rtekind
Definition: pathnodes.h:711
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:672
Cardinality tuples
Definition: pathnodes.h:721

◆ cost_qual_eval()

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

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

4309 {
4310  cost_qual_eval_context context;
4311  ListCell *l;
4312 
4313  context.root = root;
4314  context.total.startup = 0;
4315  context.total.per_tuple = 0;
4316 
4317  /* We don't charge any cost for the implicit ANDing at top level ... */
4318 
4319  foreach(l, quals)
4320  {
4321  Node *qual = (Node *) lfirst(l);
4322 
4323  cost_qual_eval_walker(qual, &context);
4324  }
4325 
4326  *cost = context.total;
4327 }
PlannerInfo * root
Definition: costsize.c:156
Definition: nodes.h:538
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:4348
#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 4334 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().

4335 {
4336  cost_qual_eval_context context;
4337 
4338  context.root = root;
4339  context.total.startup = 0;
4340  context.total.per_tuple = 0;
4341 
4342  cost_qual_eval_walker(qual, &context);
4343 
4344  *cost = context.total;
4345 }
PlannerInfo * root
Definition: costsize.c:156
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:4348

◆ cost_recursive_union()

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

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

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

◆ cost_resultscan()

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

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

1688 {
1689  Cost startup_cost = 0;
1690  Cost run_cost = 0;
1691  QualCost qpqual_cost;
1692  Cost cpu_per_tuple;
1693 
1694  /* Should only be applied to RTE_RESULT base relations */
1695  Assert(baserel->relid > 0);
1696  Assert(baserel->rtekind == RTE_RESULT);
1697 
1698  /* Mark the path with the correct row estimate */
1699  if (param_info)
1700  path->rows = param_info->ppi_rows;
1701  else
1702  path->rows = baserel->rows;
1703 
1704  /* We charge qual cost plus cpu_tuple_cost */
1705  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1706 
1707  startup_cost += qpqual_cost.startup;
1708  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1709  run_cost += cpu_per_tuple * baserel->tuples;
1710 
1711  path->startup_cost = startup_cost;
1712  path->total_cost = startup_cost + run_cost;
1713 }
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
Index relid
Definition: pathnodes.h:709
RTEKind rtekind
Definition: pathnodes.h:711
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:672
Cardinality tuples
Definition: pathnodes.h:721

◆ cost_samplescan()

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

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

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

◆ cost_seqscan()

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

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

228 {
229  Cost startup_cost = 0;
230  Cost cpu_run_cost;
231  Cost disk_run_cost;
232  double spc_seq_page_cost;
233  QualCost qpqual_cost;
234  Cost cpu_per_tuple;
235 
236  /* Should only be applied to base relations */
237  Assert(baserel->relid > 0);
238  Assert(baserel->rtekind == RTE_RELATION);
239 
240  /* Mark the path with the correct row estimate */
241  if (param_info)
242  path->rows = param_info->ppi_rows;
243  else
244  path->rows = baserel->rows;
245 
246  if (!enable_seqscan)
247  startup_cost += disable_cost;
248 
249  /* fetch estimated page cost for tablespace containing table */
251  NULL,
252  &spc_seq_page_cost);
253 
254  /*
255  * disk costs
256  */
257  disk_run_cost = spc_seq_page_cost * baserel->pages;
258 
259  /* CPU costs */
260  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
261 
262  startup_cost += qpqual_cost.startup;
263  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
264  cpu_run_cost = cpu_per_tuple * baserel->tuples;
265  /* tlist eval costs are paid per output row, not per tuple scanned */
266  startup_cost += path->pathtarget->cost.startup;
267  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
268 
269  /* Adjust costing for parallelism, if used. */
270  if (path->parallel_workers > 0)
271  {
272  double parallel_divisor = get_parallel_divisor(path);
273 
274  /* The CPU cost is divided among all the workers. */
275  cpu_run_cost /= parallel_divisor;
276 
277  /*
278  * It may be possible to amortize some of the I/O cost, but probably
279  * not very much, because most operating systems already do aggressive
280  * prefetching. For now, we assume that the disk run cost can't be
281  * amortized at all.
282  */
283 
284  /*
285  * In the case of a parallel plan, the row count needs to represent
286  * the number of tuples processed per worker.
287  */
288  path->rows = clamp_row_est(path->rows / parallel_divisor);
289  }
290 
291  path->startup_cost = startup_cost;
292  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
293 }
PathTarget * pathtarget
Definition: pathnodes.h:1183
Oid reltablespace
Definition: pathnodes.h:710
int parallel_workers
Definition: pathnodes.h:1189
Cardinality ppi_rows
Definition: pathnodes.h:1142
bool enable_seqscan
Definition: costsize.c:133
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
Cost disable_cost
Definition: costsize.c:129
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6042
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:709
RTEKind rtekind
Definition: pathnodes.h:711
Cost total_cost
Definition: pathnodes.h:1194
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4623
BlockNumber pages
Definition: pathnodes.h:720
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
QualCost cost
Definition: pathnodes.h:1112
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double clamp_row_est(double nrows)
Definition: costsize.c:199
double Cost
Definition: nodes.h:672
Cardinality tuples
Definition: pathnodes.h:721

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

2041 {
2042  Cost startup_cost;
2043  Cost run_cost;
2044 
2045  cost_tuplesort(&startup_cost, &run_cost,
2046  tuples, width,
2047  comparison_cost, sort_mem,
2048  limit_tuples);
2049 
2050  if (!enable_sort)
2051  startup_cost += disable_cost;
2052 
2053  startup_cost += input_cost;
2054 
2055  path->rows = tuples;
2056  path->startup_cost = startup_cost;
2057  path->total_cost = startup_cost + run_cost;
2058 }
bool enable_sort
Definition: costsize.c:138
Cost startup_cost
Definition: pathnodes.h:1193
Cost disable_cost
Definition: costsize.c:129
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:1794
Cost total_cost
Definition: pathnodes.h:1194
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:672

◆ cost_subplan()

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

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

4104 {
4105  QualCost sp_cost;
4106 
4107  /* Figure any cost for evaluating the testexpr */
4108  cost_qual_eval(&sp_cost,
4109  make_ands_implicit((Expr *) subplan->testexpr),
4110  root);
4111 
4112  if (subplan->useHashTable)
4113  {
4114  /*
4115  * If we are using a hash table for the subquery outputs, then the
4116  * cost of evaluating the query is a one-time cost. We charge one
4117  * cpu_operator_cost per tuple for the work of loading the hashtable,
4118  * too.
4119  */
4120  sp_cost.startup += plan->total_cost +
4121  cpu_operator_cost * plan->plan_rows;
4122 
4123  /*
4124  * The per-tuple costs include the cost of evaluating the lefthand
4125  * expressions, plus the cost of probing the hashtable. We already
4126  * accounted for the lefthand expressions as part of the testexpr, and
4127  * will also have counted one cpu_operator_cost for each comparison
4128  * operator. That is probably too low for the probing cost, but it's
4129  * hard to make a better estimate, so live with it for now.
4130  */
4131  }
4132  else
4133  {
4134  /*
4135  * Otherwise we will be rescanning the subplan output on each
4136  * evaluation. We need to estimate how much of the output we will
4137  * actually need to scan. NOTE: this logic should agree with the
4138  * tuple_fraction estimates used by make_subplan() in
4139  * plan/subselect.c.
4140  */
4141  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4142 
4143  if (subplan->subLinkType == EXISTS_SUBLINK)
4144  {
4145  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4146  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4147  }
4148  else if (subplan->subLinkType == ALL_SUBLINK ||
4149  subplan->subLinkType == ANY_SUBLINK)
4150  {
4151  /* assume we need 50% of the tuples */
4152  sp_cost.per_tuple += 0.50 * plan_run_cost;
4153  /* also charge a cpu_operator_cost per row examined */
4154  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4155  }
4156  else
4157  {
4158  /* assume we need all tuples */
4159  sp_cost.per_tuple += plan_run_cost;
4160  }
4161 
4162  /*
4163  * Also account for subplan's startup cost. If the subplan is
4164  * uncorrelated or undirect correlated, AND its topmost node is one
4165  * that materializes its output, assume that we'll only need to pay
4166  * its startup cost once; otherwise assume we pay the startup cost
4167  * every time.
4168  */
4169  if (subplan->parParam == NIL &&
4171  sp_cost.startup += plan->startup_cost;
4172  else
4173  sp_cost.per_tuple += plan->startup_cost;
4174  }
4175 
4176  subplan->startup_cost = sp_cost.startup;
4177  subplan->per_call_cost = sp_cost.per_tuple;
4178 }
#define NIL
Definition: pg_list.h:65
SubLinkType subLinkType
Definition: primnodes.h:747
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:4308
Cost startup_cost
Definition: plannodes.h:117
double cpu_operator_cost
Definition: costsize.c:123
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
Node * testexpr
Definition: primnodes.h:749
Cost per_call_cost
Definition: primnodes.h:776
Cardinality plan_rows
Definition: plannodes.h:123
List * parParam
Definition: primnodes.h:772
#define nodeTag(nodeptr)
Definition: nodes.h:543
Cost total_cost
Definition: plannodes.h:118
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:637
bool useHashTable
Definition: primnodes.h:761
Cost startup_cost
Definition: primnodes.h:775
double clamp_row_est(double nrows)
Definition: costsize.c:199
double Cost
Definition: nodes.h:672

◆ cost_subqueryscan()

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

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

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

◆ cost_tablefuncscan()

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

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

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

◆ cost_tidrangescan()

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

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

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

◆ cost_tidscan()

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

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

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

◆ cost_valuesscan()

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

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

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

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

2762 {
2763  Cost startup_cost;
2764  Cost total_cost;
2765  ListCell *lc;
2766 
2767  startup_cost = input_startup_cost;
2768  total_cost = input_total_cost;
2769 
2770  /*
2771  * Window functions are assumed to cost their stated execution cost, plus
2772  * the cost of evaluating their input expressions, per tuple. Since they
2773  * may in fact evaluate their inputs at multiple rows during each cycle,
2774  * this could be a drastic underestimate; but without a way to know how
2775  * many rows the window function will fetch, it's hard to do better. In
2776  * any case, it's a good estimate for all the built-in window functions,
2777  * so we'll just do this for now.
2778  */
2779  foreach(lc, windowFuncs)
2780  {
2781  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
2782  Cost wfunccost;
2783  QualCost argcosts;
2784 
2785  argcosts.startup = argcosts.per_tuple = 0;
2786  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
2787  &argcosts);
2788  startup_cost += argcosts.startup;
2789  wfunccost = argcosts.per_tuple;
2790 
2791  /* also add the input expressions' cost to per-input-row costs */
2792  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
2793  startup_cost += argcosts.startup;
2794  wfunccost += argcosts.per_tuple;
2795 
2796  /*
2797  * Add the filter's cost to per-input-row costs. XXX We should reduce
2798  * input expression costs according to filter selectivity.
2799  */
2800  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
2801  startup_cost += argcosts.startup;
2802  wfunccost += argcosts.per_tuple;
2803 
2804  total_cost += wfunccost * input_tuples;
2805  }
2806 
2807  /*
2808  * We also charge cpu_operator_cost per grouping column per tuple for
2809  * grouping comparisons, plus cpu_tuple_cost per tuple for general
2810  * overhead.
2811  *
2812  * XXX this neglects costs of spooling the data to disk when it overflows
2813  * work_mem. Sooner or later that should get accounted for.
2814  */
2815  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
2816  total_cost += cpu_tuple_cost * input_tuples;
2817 
2818  path->rows = input_tuples;
2819  path->startup_cost = startup_cost;
2820  path->total_cost = total_cost;
2821 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4334
List * args
Definition: primnodes.h:390
Definition: nodes.h:538
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1967
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1193
#define lfirst_node(type, lc)
Definition: pg_list.h:172
double cpu_operator_cost
Definition: costsize.c:123
Oid winfnoid
Definition: primnodes.h:386
Cost total_cost
Definition: pathnodes.h:1194
Expr * aggfilter
Definition: primnodes.h:391
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality rows
Definition: pathnodes.h:1192
double Cost
Definition: nodes.h:672

◆ final_cost_hashjoin()

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

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

3852 {
3853  Path *outer_path = path->jpath.outerjoinpath;
3854  Path *inner_path = path->jpath.innerjoinpath;
3855  double outer_path_rows = outer_path->rows;
3856  double inner_path_rows = inner_path->rows;
3857  double inner_path_rows_total = workspace->inner_rows_total;
3858  List *hashclauses = path->path_hashclauses;
3859  Cost startup_cost = workspace->startup_cost;
3860  Cost run_cost = workspace->run_cost;
3861  int numbuckets = workspace->numbuckets;
3862  int numbatches = workspace->numbatches;
3863  Cost cpu_per_tuple;
3864  QualCost hash_qual_cost;
3865  QualCost qp_qual_cost;
3866  double hashjointuples;
3867  double virtualbuckets;
3868  Selectivity innerbucketsize;
3869  Selectivity innermcvfreq;
3870  ListCell *hcl;
3871 
3872  /* Mark the path with the correct row estimate */
3873  if (path->jpath.path.param_info)
3874  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3875  else
3876  path->jpath.path.rows = path->jpath.path.parent->rows;
3877 
3878  /* For partial paths, scale row estimate. */
3879  if (path->jpath.path.parallel_workers > 0)
3880  {
3881  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3882 
3883  path->jpath.path.rows =
3884  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3885  }
3886 
3887  /*
3888  * We could include disable_cost in the preliminary estimate, but that
3889  * would amount to optimizing for the case where the join method is
3890  * disabled, which doesn't seem like the way to bet.
3891  */
3892  if (!enable_hashjoin)
3893  startup_cost += disable_cost;
3894 
3895  /* mark the path with estimated # of batches */
3896  path->num_batches = numbatches;
3897 
3898  /* store the total number of tuples (sum of partial row estimates) */
3899  path->inner_rows_total = inner_path_rows_total;
3900 
3901  /* and compute the number of "virtual" buckets in the whole join */
3902  virtualbuckets = (double) numbuckets * (double) numbatches;
3903 
3904  /*
3905  * Determine bucketsize fraction and MCV frequency for the inner relation.
3906  * We use the smallest bucketsize or MCV frequency estimated for any
3907  * individual hashclause; this is undoubtedly conservative.
3908  *
3909  * BUT: if inner relation has been unique-ified, we can assume it's good
3910  * for hashing. This is important both because it's the right answer, and
3911  * because we avoid contaminating the cache with a value that's wrong for
3912  * non-unique-ified paths.
3913  */
3914  if (IsA(inner_path, UniquePath))
3915  {
3916  innerbucketsize = 1.0 / virtualbuckets;
3917  innermcvfreq = 0.0;
3918  }
3919  else
3920  {
3921  innerbucketsize = 1.0;
3922  innermcvfreq = 1.0;
3923  foreach(hcl, hashclauses)
3924  {
3925  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
3926  Selectivity thisbucketsize;
3927  Selectivity thismcvfreq;
3928 
3929  /*
3930  * First we have to figure out which side of the hashjoin clause
3931  * is the inner side.
3932  *
3933  * Since we tend to visit the same clauses over and over when
3934  * planning a large query, we cache the bucket stats estimates in
3935  * the RestrictInfo node to avoid repeated lookups of statistics.
3936  */
3937  if (bms_is_subset(restrictinfo->right_relids,
3938  inner_path->parent->relids))
3939  {
3940  /* righthand side is inner */
3941  thisbucketsize = restrictinfo->right_bucketsize;
3942  if (thisbucketsize < 0)
3943  {
3944  /* not cached yet */
3946  get_rightop(restrictinfo->clause),
3947  virtualbuckets,
3948  &restrictinfo->right_mcvfreq,
3949  &restrictinfo->right_bucketsize);
3950  thisbucketsize = restrictinfo->right_bucketsize;
3951  }
3952  thismcvfreq = restrictinfo->right_mcvfreq;
3953  }
3954  else
3955  {
3956  Assert(bms_is_subset(restrictinfo->left_relids,
3957  inner_path->parent->relids));
3958  /* lefthand side is inner */
3959  thisbucketsize = restrictinfo->left_bucketsize;
3960  if (thisbucketsize < 0)
3961  {
3962  /* not cached yet */
3964  get_leftop(restrictinfo->clause),
3965  virtualbuckets,
3966  &restrictinfo->left_mcvfreq,
3967  &restrictinfo->left_bucketsize);
3968  thisbucketsize = restrictinfo->left_bucketsize;
3969  }
3970  thismcvfreq = restrictinfo->left_mcvfreq;
3971  }
3972 
3973  if (innerbucketsize > thisbucketsize)
3974  innerbucketsize = thisbucketsize;
3975  if (innermcvfreq > thismcvfreq)
3976  innermcvfreq = thismcvfreq;
3977  }
3978  }
3979 
3980  /*
3981  * If the bucket holding the inner MCV would exceed hash_mem, we don't
3982  * want to hash unless there is really no other alternative, so apply
3983  * disable_cost. (The executor normally copes with excessive memory usage
3984  * by splitting batches, but obviously it cannot separate equal values
3985  * that way, so it will be unable to drive the batch size below hash_mem
3986  * when this is true.)
3987  */
3988  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
3989  inner_path->pathtarget->width) > get_hash_memory_limit())
3990  startup_cost += disable_cost;
3991 
3992  /*
3993  * Compute cost of the hashquals and qpquals (other restriction clauses)
3994  * separately.
3995  */
3996  cost_qual_eval(&hash_qual_cost, hashclauses, root);
3997  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3998  qp_qual_cost.startup -= hash_qual_cost.startup;
3999  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4000 
4001  /* CPU costs */
4002 
4003  if (path->jpath.jointype == JOIN_SEMI ||
4004  path->jpath.jointype == JOIN_ANTI ||
4005  extra->inner_unique)
4006  {
4007  double outer_matched_rows;
4008  Selectivity inner_scan_frac;
4009 
4010  /*
4011  * With a SEMI or ANTI join, or if the innerrel is known unique, the
4012  * executor will stop after the first match.
4013  *
4014  * For an outer-rel row that has at least one match, we can expect the
4015  * bucket scan to stop after a fraction 1/(match_count+1) of the
4016  * bucket's rows, if the matches are evenly distributed. Since they
4017  * probably aren't quite evenly distributed, we apply a fuzz factor of
4018  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
4019  * to clamp inner_scan_frac to at most 1.0; but since match_count is
4020  * at least 1, no such clamp is needed now.)
4021  */
4022  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
4023  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4024 
4025  startup_cost += hash_qual_cost.startup;
4026  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4027  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
4028 
4029  /*
4030  * For unmatched outer-rel rows, the picture is quite a lot different.
4031  * In the first place, there is no reason to assume that these rows
4032  * preferentially hit heavily-populated buckets; instead assume they
4033  * are uncorrelated with the inner distribution and so they see an
4034  * average bucket size of inner_path_rows / virtualbuckets. In the
4035  * second place, it seems likely that they will have few if any exact
4036  * hash-code matches and so very few of the tuples in the bucket will
4037  * actually require eval of the hash quals. We don't have any good
4038  * way to estimate how many will, but for the moment assume that the
4039  * effective cost per bucket entry is one-tenth what it is for
4040  * matchable tuples.
4041  */
4042  run_cost += hash_qual_cost.per_tuple *
4043  (outer_path_rows - outer_matched_rows) *
4044  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
4045 
4046  /* Get # of tuples that will pass the basic join */
4047  if (path->jpath.jointype == JOIN_ANTI)
4048  hashjointuples = outer_path_rows - outer_matched_rows;
4049  else
4050  hashjointuples = outer_matched_rows;
4051  }
4052  else
4053  {
4054  /*
4055  * The number of tuple comparisons needed is the number of outer
4056  * tuples times the typical number of tuples in a hash bucket, which
4057  * is the inner relation size times its bucketsize fraction. At each
4058  * one, we need to evaluate the hashjoin quals. But actually,
4059  * charging the full qual eval cost at each tuple is pessimistic,
4060  * since we don't evaluate the quals unless the hash values match
4061  * exactly. For lack of a better idea, halve the cost estimate to
4062  * allow for that.
4063  */
4064  startup_cost += hash_qual_cost.startup;
4065  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4066  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
4067 
4068  /*
4069  * Get approx # tuples passing the hashquals. We use
4070  * approx_tuple_count here because we need an estimate done with
4071  * JOIN_INNER semantics.
4072  */
4073  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
4074  }
4075 
4076  /*
4077  * For each tuple that gets through the hashjoin proper, we charge
4078  * cpu_tuple_cost plus the cost of evaluating additional restriction
4079  * clauses that are to be applied at the join. (This is pessimistic since
4080  * not all of the quals may get evaluated at each tuple.)
4081  */
4082  startup_cost += qp_qual_cost.startup;
4083  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4084  run_cost += cpu_per_tuple * hashjointuples;
4085 
4086  /* tlist eval costs are paid per output row, not per tuple scanned */
4087  startup_cost += path->jpath.path.pathtarget->cost.startup;
4088  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4089 
4090  path->jpath.path.startup_cost = startup_cost;
4091  path->jpath.path.total_cost = startup_cost + run_cost;
4092 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:589
JoinPath jpath
Definition: pathnodes.h:1667
PathTarget * pathtarget
Definition: pathnodes.h:1183
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:2533
int num_batches
Definition: pathnodes.h:1669
Selectivity right_mcvfreq
Definition: pathnodes.h:2123
Selectivity outer_match_frac
Definition: pathnodes.h:2510
Path * innerjoinpath
Definition: pathnodes.h:1591
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4867
int parallel_workers
Definition: pathnodes.h:1189
ParamPathInfo * param_info
Definition: pathnodes.h:1185
Relids left_relids
Definition: pathnodes.h:2086
double Selectivity
Definition: nodes.h:671
Cardinality ppi_rows
Definition: pathnodes.h:1142
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:4308
Cost startup_cost
Definition: pathnodes.h:1193
Cost disable_cost
Definition: costsize.c:129
List * joinrestrictinfo
Definition: pathnodes.h:1593
RelOptInfo * parent
Definition: pathnodes.h:1182
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:6042
Relids relids
Definition: pathnodes.h:681
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:73
Expr * clause
Definition: pathnodes.h:2056
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:6021
Path * outerjoinpath
Definition: pathnodes.h:1590
Cardinality inner_rows_total
Definition: pathnodes.h:1670
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:85
Cost total_cost
Definition: pathnodes.h:1194
Selectivity left_bucketsize
Definition: pathnodes.h:2120
Relids right_relids
Definition: pathnodes.h:2087
Path path
Definition: pathnodes.h:1583
#define Assert(condition)
Definition: c.h:804
Cardinality rows
Definition: pathnodes.h:684
Selectivity left_mcvfreq
Definition: pathnodes.h:2122
QualCost cost
Definition: pathnodes.h:1112
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3401
double cpu_tuple_cost
Definition: costsize.c:121
bool enable_hashjoin
Definition: costsize.c:145
Selectivity match_count
Definition: pathnodes.h:2511
Selectivity right_bucketsize
Definition: pathnodes.h:2121
JoinType jointype
Definition: pathnodes.h:1585
void estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
Definition: selfuncs.c:3751
Cardinality inner_rows_total
Definition: pathnodes.h:2654
List * path_hashclauses
Definition: pathnodes.h:1668
Cardinality rows
Definition: pathnodes.h:1192
double clamp_row_est(double nrows)
Definition: costsize.c:199
Definition: pg_list.h:50
double Cost
Definition: nodes.h:672

◆ final_cost_mergejoin()

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

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

3416 {
3417  Path *outer_path = path->jpath.outerjoinpath;
3418  Path *inner_path = path->jpath.innerjoinpath;
3419  double inner_path_rows = inner_path->rows;
3420  List *mergeclauses = path->path_mergeclauses;
3421  List *innersortkeys = path->innersortkeys;
3422  Cost startup_cost = workspace->startup_cost;
3423  Cost run_cost = workspace->run_cost;
3424  Cost inner_run_cost = workspace->inner_run_cost;
3425  double outer_rows = workspace->outer_rows;
3426  double inner_rows = workspace->inner_rows;
3427  double outer_skip_rows = workspace->outer_skip_rows;
3428  double inner_skip_rows = workspace->inner_skip_rows;
3429  Cost cpu_per_tuple,
3430  bare_inner_cost,
3431  mat_inner_cost;
3432  QualCost merge_qual_cost;
3433  QualCost qp_qual_cost;
3434  double mergejointuples,
3435  rescannedtuples;
3436  double rescanratio;
3437 
3438  /* Protect some assumptions below that rowcounts aren't zero */
3439  if (inner_path_rows <= 0)
3440  inner_path_rows = 1;
3441 
3442  /* Mark the path with the correct row estimate */
3443  if (path->jpath.path.param_info)
3444  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3445  else
3446  path->jpath.path.rows = path->jpath.path.parent->rows;
3447 
3448  /* For partial paths, scale row estimate. */
3449  if (path->jpath.path.parallel_workers > 0)
3450  {
3451  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3452 
3453  path->jpath.path.rows =
3454  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3455  }
3456 
3457  /*
3458  * We could include disable_cost in the preliminary estimate, but that
3459  * would amount to optimizing for the case where the join method is
3460  * disabled, which doesn't seem like the way to bet.
3461  */
3462  if (!enable_mergejoin)
3463  startup_cost += disable_cost;
3464 
3465  /*
3466  * Compute cost of the mergequals and qpquals (other restriction clauses)
3467  * separately.
3468  */
3469  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
3470  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3471  qp_qual_cost.startup -= merge_qual_cost.startup;
3472  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
3473 
3474  /*
3475  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3476  * executor will stop scanning for matches after the first match. When
3477  * all the joinclauses are merge clauses, this means we don't ever need to
3478  * back up the merge, and so we can skip mark/restore overhead.
3479  */
3480  if ((path->jpath.jointype == JOIN_SEMI ||
3481  path->jpath.jointype == JOIN_ANTI ||
3482  extra->inner_unique) &&
3485  path->skip_mark_restore = true;
3486  else
3487  path->skip_mark_restore = false;
3488 
3489  /*
3490  * Get approx # tuples passing the mergequals. We use approx_tuple_count
3491  * here because we need an estimate done with JOIN_INNER semantics.
3492  */
3493  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
3494 
3495  /*
3496  * When there are equal merge keys in the outer relation, the mergejoin
3497  * must rescan any matching tuples in the inner relation. This means
3498  * re-fetching inner tuples; we have to estimate how often that happens.
3499  *
3500  * For regular inner and outer joins, the number of re-fetches can be
3501  * estimated approximately as size of merge join output minus size of
3502  * inner relation. Assume that the distinct key values are 1, 2, ..., and
3503  * denote the number of values of each key in the outer relation as m1,
3504  * m2, ...; in the inner relation, n1, n2, ... Then we have
3505  *
3506  * size of join = m1 * n1 + m2 * n2 + ...
3507  *
3508  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
3509  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
3510  * relation
3511  *
3512  * This equation works correctly for outer tuples having no inner match
3513  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
3514  * are effectively subtracting those from the number of rescanned tuples,
3515  * when we should not. Can we do better without expensive selectivity
3516  * computations?
3517  *
3518  * The whole issue is moot if we are working from a unique-ified outer
3519  * input, or if we know we don't need to mark/restore at all.
3520  */
3521  if (IsA(outer_path, UniquePath) || path->skip_mark_restore)
3522  rescannedtuples = 0;
3523  else
3524  {
3525  rescannedtuples = mergejointuples - inner_path_rows;
3526  /* Must clamp because of possible underestimate */
3527  if (rescannedtuples < 0)
3528  rescannedtuples = 0;
3529  }
3530 
3531  /*
3532  * We'll inflate various costs this much to account for rescanning. Note
3533  * that this is to be multiplied by something involving inner_rows, or
3534  * another number related to the portion of the inner rel we'll scan.
3535  */
3536  rescanratio = 1.0 + (rescannedtuples / inner_rows);
3537 
3538  /*
3539  * Decide whether we want to materialize the inner input to shield it from
3540  * mark/restore and performing re-fetches. Our cost model for regular
3541  * re-fetches is that a re-fetch costs the same as an original fetch,
3542  * which is probably an overestimate; but on the other hand we ignore the
3543  * bookkeeping costs of mark/restore. Not clear if it's worth developing
3544  * a more refined model. So we just need to inflate the inner run cost by
3545  * rescanratio.
3546  */
3547  bare_inner_cost = inner_run_cost * rescanratio;
3548 
3549  /*
3550  * When we interpose a Material node the re-fetch cost is assumed to be
3551  * just cpu_operator_cost per tuple, independently of the underlying
3552  * plan's cost; and we charge an extra cpu_operator_cost per original
3553  * fetch as well. Note that we're assuming the materialize node will
3554  * never spill to disk, since it only has to remember tuples back to the
3555  * last mark. (If there are a huge number of duplicates, our other cost
3556  * factors will make the path so expensive that it probably won't get
3557  * chosen anyway.) So we don't use cost_rescan here.
3558  *
3559  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3560  * of the generated Material node.
3561  */
3562  mat_inner_cost = inner_run_cost +
3563  cpu_operator_cost * inner_rows * rescanratio;
3564 
3565  /*
3566  * If we don't need mark/restore at all, we don't need materialization.
3567  */
3568  if (path->skip_mark_restore)
3569  path->materialize_inner = false;
3570 
3571  /*
3572  * Prefer materializing if it looks cheaper, unless the user has asked to
3573  * suppress materialization.
3574  */
3575  else if (enable_material && mat_inner_cost < bare_inner_cost)
3576  path->materialize_inner = true;
3577 
3578  /*
3579  * Even if materializing doesn't look cheaper, we *must* do it if the
3580  * inner path is to be used directly (without sorting) and it doesn't
3581  * support mark/restore.
3582  *
3583  * Since the inner side must be ordered, and only Sorts and IndexScans can
3584  * create order to begin with, and they both support mark/restore, you
3585  * might think there's no problem --- but you'd be wrong. Nestloop and
3586  * merge joins can *preserve* the order of their inputs, so they can be
3587  * selected as the input of a mergejoin, and they don't support
3588  * mark/restore at present.
3589  *
3590  * We don't test the value of enable_material here, because
3591  * materialization is required for correctness in this case, and turning
3592  * it off does not entitle us to deliver an invalid plan.
3593  */
3594  else if (innersortkeys == NIL &&
3595  !ExecSupportsMarkRestore(inner_path))
3596  path->materialize_inner = true;
3597 
3598  /*
3599  * Also, force materializing if the inner path is to be sorted and the
3600  * sort is expected to spill to disk. This is because the final merge
3601  * pass can be done on-the-fly if it doesn't have to support mark/restore.
3602  * We don't try to adjust the cost estimates for this consideration,
3603  * though.
3604  *
3605  * Since materialization is a performance optimization in this case,
3606  * rather than necessary for correctness, we skip it if enable_material is
3607  * off.
3608  */
3609  else if (enable_material && innersortkeys != NIL &&
3610  relation_byte_size(inner_path_rows,
3611  inner_path->pathtarget->width) >
3612  (work_mem * 1024L))
3613  path->materialize_inner = true;
3614  else
3615  path->materialize_inner = false;
3616 
3617  /* Charge the right incremental cost for the chosen case */
3618  if (path->materialize_inner)
3619  run_cost += mat_inner_cost;
3620  else
3621  run_cost += bare_inner_cost;
3622 
3623  /* CPU costs */
3624 
3625  /*
3626  * The number of tuple comparisons needed is approximately number of outer
3627  * rows plus number of inner rows plus number of rescanned tuples (can we
3628  * refine this?). At each one, we need to evaluate the mergejoin quals.
3629  */
3630  startup_cost += merge_qual_cost.startup;
3631  startup_cost += merge_qual_cost.per_tuple *
3632  (outer_skip_rows + inner_skip_rows * rescanratio);
3633  run_cost += merge_qual_cost.per_tuple *
3634  ((outer_rows - outer_skip_rows) +
3635  (inner_rows - inner_skip_rows) * rescanratio);
3636 
3637  /*
3638  * For each tuple that gets through the mergejoin proper, we charge
3639  * cpu_tuple_cost plus the cost of evaluating additional restriction
3640  * clauses that are to be applied at the join. (This is pessimistic since
3641  * not all of the quals may get evaluated at each tuple.)
3642  *
3643  * Note: we could adjust for SEMI/ANTI joins skipping some qual
3644  * evaluations here, but it's probably not worth the trouble.
3645  */
3646  startup_cost += qp_qual_cost.startup;
3647  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3648  run_cost += cpu_per_tuple * mergejointuples;
3649 
3650  /* tlist eval costs are paid per output row, not per tuple scanned */
3651  startup_cost += path->jpath.path.pathtarget->cost.startup;
3652  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3653 
3654  path->jpath.path.startup_cost = startup_cost;
3655  path->jpath.path.total_cost = startup_cost + run_cost;
3656 }
#define NIL
Definition: pg_list.h:65
List * path_mergeclauses
Definition: pathnodes.h:1649
#define IsA(nodeptr, _type_)
Definition: nodes.h:589
PathTarget * pathtarget
Definition: pathnodes.h:1183
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:419
bool materialize_inner
Definition: pathnodes.h:1653
Path * innerjoinpath
Definition: pathnodes.h:1591
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4867
int parallel_workers
Definition: pathnodes.h:1189
ParamPathInfo * param_info
Definition: pathnodes.h:1185
Cardinality outer_skip_rows
Definition: pathnodes.h:2648
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
bool skip_mark_restore
Definition: pathnodes.h:1652
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4308
Cost startup_cost
Definition: pathnodes.h:1193
Cost disable_cost
Definition: costsize.c:129
List * joinrestrictinfo
Definition: pathnodes.h:1593
RelOptInfo * parent
Definition: pathnodes.h:1182
Cardinality inner_rows
Definition: pathnodes.h:2647
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6042
double cpu_operator_cost
Definition: costsize.c:123
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:6021
Path * outerjoinpath
Definition: pathnodes.h:1590
int work_mem
Definition: globals.c:124
Cost total_cost
Definition: pathnodes.h:1194
bool enable_mergejoin
Definition: costsize.c:144
Path path
Definition: pathnodes.h:1583
Cardinality rows
Definition: pathnodes.h:684
QualCost cost
Definition: pathnodes.h:1112
static int list_length(const List *l)
Definition: pg_list.h:149
List * innersortkeys
Definition: pathnodes.h:1651
Cardinality inner_skip_rows
Definition: pathnodes.h:2649
double cpu_tuple_cost
Definition: costsize.c:121
JoinType jointype
Definition: pathnodes.h:1585
Cardinality outer_rows
Definition: pathnodes.h:2646
JoinPath jpath
Definition: pathnodes.h:1648
Cardinality rows
Definition: pathnodes.h:1192
double clamp_row_est(double nrows)
Definition: costsize.c:199
Definition: pg_list.h:50
double Cost
Definition: nodes.h:672
bool enable_material
Definition: costsize.c:142

◆ final_cost_nestloop()

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

Definition at line 2977 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, NestPath::jpath, 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().

2980 {
2981  Path *outer_path = path->jpath.outerjoinpath;
2982  Path *inner_path = path->jpath.innerjoinpath;
2983  double outer_path_rows = outer_path->rows;
2984  double inner_path_rows = inner_path->rows;
2985  Cost startup_cost = workspace->startup_cost;
2986  Cost run_cost = workspace->run_cost;
2987  Cost cpu_per_tuple;
2988  QualCost restrict_qual_cost;
2989  double ntuples;
2990 
2991  /* Protect some assumptions below that rowcounts aren't zero */
2992  if (outer_path_rows <= 0)
2993  outer_path_rows = 1;
2994  if (inner_path_rows <= 0)
2995  inner_path_rows = 1;
2996  /* Mark the path with the correct row estimate */
2997  if (path->jpath.path.param_info)
2998  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2999  else
3000  path->jpath.path.rows = path->jpath.path.parent->rows;
3001 
3002  /* For partial paths, scale row estimate. */
3003  if (path->jpath.path.parallel_workers > 0)
3004  {
3005  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3006 
3007  path->jpath.path.rows =
3008  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3009  }
3010 
3011  /*
3012  * We could include disable_cost in the preliminary estimate, but that
3013  * would amount to optimizing for the case where the join method is
3014  * disabled, which doesn't seem like the way to bet.
3015  */
3016  if (!enable_nestloop)
3017  startup_cost += disable_cost;
3018 
3019  /* cost of inner-relation source data (we already dealt with outer rel) */
3020 
3021  if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
3022  extra->inner_unique)
3023  {
3024  /*
3025  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3026  * executor will stop after the first match.
3027  */
3028  Cost inner_run_cost = workspace->inner_run_cost;
3029  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
3030  double outer_matched_rows;
3031  double outer_unmatched_rows;
3032  Selectivity inner_scan_frac;
3033 
3034  /*
3035  * For an outer-rel row that has at least one match, we can expect the
3036  * inner scan to stop after a fraction 1/(match_count+1) of the inner
3037  * rows, if the matches are evenly distributed. Since they probably
3038  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
3039  * that fraction. (If we used a larger fuzz factor, we'd have to
3040  * clamp inner_scan_frac to at most 1.0; but since match_count is at
3041  * least 1, no such clamp is needed now.)
3042  */
3043  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3044  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
3045  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3046 
3047  /*
3048  * Compute number of tuples processed (not number emitted!). First,
3049  * account for successfully-matched outer rows.
3050  */
3051  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
3052 
3053  /*
3054  * Now we need to estimate the actual costs of scanning the inner
3055  * relation, which may be quite a bit less than N times inner_run_cost
3056  * due to early scan stops. We consider two cases. If the inner path
3057  * is an indexscan using all the joinquals as indexquals, then an
3058  * unmatched outer row results in an indexscan returning no rows,
3059  * which is probably quite cheap. Otherwise, the executor will have
3060  * to scan the whole inner rel for an unmatched row; not so cheap.
3061  */
3062  if (has_indexed_join_quals(path))
3063  {
3064  /*
3065  * Successfully-matched outer rows will only require scanning
3066  * inner_scan_frac of the inner relation. In this case, we don't
3067  * need to charge the full inner_run_cost even when that's more
3068  * than inner_rescan_run_cost, because we can assume that none of
3069  * the inner scans ever scan the whole inner relation. So it's
3070  * okay to assume that all the inner scan executions can be
3071  * fractions of the full cost, even if materialization is reducing
3072  * the rescan cost. At this writing, it's impossible to get here
3073  * for a materialized inner scan, so inner_run_cost and
3074  * inner_rescan_run_cost will be the same anyway; but just in
3075  * case, use inner_run_cost for the first matched tuple and
3076  * inner_rescan_run_cost for additional ones.
3077  */
3078  run_cost += inner_run_cost * inner_scan_frac;
3079  if (outer_matched_rows > 1)
3080  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
3081 
3082  /*
3083  * Add the cost of inner-scan executions for unmatched outer rows.
3084  * We estimate this as the same cost as returning the first tuple
3085  * of a nonempty scan. We consider that these are all rescans,
3086  * since we used inner_run_cost once already.
3087  */
3088  run_cost += outer_unmatched_rows *
3089  inner_rescan_run_cost / inner_path_rows;
3090 
3091  /*
3092  * We won't be evaluating any quals at all for unmatched rows, so
3093  * don't add them to ntuples.
3094  */
3095  }
3096  else
3097  {
3098  /*
3099  * Here, a complicating factor is that rescans may be cheaper than
3100  * first scans. If we never scan all the way to the end of the
3101  * inner rel, it might be (depending on the plan type) that we'd
3102  * never pay the whole inner first-scan run cost. However it is
3103  * difficult to estimate whether that will happen (and it could
3104  * not happen if there are any unmatched outer rows!), so be
3105  * conservative and always charge the whole first-scan cost once.
3106  * We consider this charge to correspond to the first unmatched
3107  * outer row, unless there isn't one in our estimate, in which
3108  * case blame it on the first matched row.
3109  */
3110 
3111  /* First, count all unmatched join tuples as being processed */
3112  ntuples += outer_unmatched_rows * inner_path_rows;
3113 
3114  /* Now add the forced full scan, and decrement appropriate count */
3115  run_cost += inner_run_cost;
3116  if (outer_unmatched_rows >= 1)
3117  outer_unmatched_rows -= 1;
3118  else
3119  outer_matched_rows -= 1;
3120 
3121  /* Add inner run cost for additional outer tuples having matches */
3122  if (outer_matched_rows > 0)
3123  run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
3124 
3125  /* Add inner run cost for additional unmatched outer tuples */
3126  if (outer_unmatched_rows > 0)
3127  run_cost += outer_unmatched_rows * inner_rescan_run_cost;
3128  }
3129  }
3130  else
3131  {
3132  /* Normal-case source costs were included in preliminary estimate */
3133 
3134  /* Compute number of tuples processed (not number emitted!) */
3135  ntuples = outer_path_rows * inner_path_rows;
3136  }
3137 
3138  /* CPU costs */
3139  cost_qual_eval(&restrict_qual_cost, path->jpath.joinrestrictinfo, root);
3140  startup_cost += restrict_qual_cost.startup;
3141  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
3142  run_cost += cpu_per_tuple * ntuples;
3143 
3144  /* tlist eval costs are paid per output row, not per tuple scanned */
3145  startup_cost += path->jpath.path.pathtarget->cost.startup;
3146  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3147 
3148  path->jpath.path.startup_cost = startup_cost;
3149  path->jpath.path.total_cost = startup_cost + run_cost;
3150 }
PathTarget * pathtarget
Definition: pathnodes.h:1183
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:2533
bool enable_nestloop
Definition: costsize.c:141
Selectivity outer_match_frac
Definition: pathnodes.h:2510
Path * innerjoinpath
Definition: pathnodes.h:1591
static bool has_indexed_join_quals(NestPath *path)
Definition: costsize.c:4774
int parallel_workers
Definition: pathnodes.h:1189
ParamPathInfo * param_info
Definition: pathnodes.h:1185
double Selectivity
Definition: nodes.h:671
Cardinality ppi_rows
Definition: pathnodes.h:1142
Cost inner_rescan_run_cost
Definition: pathnodes.h:2643
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:4308
Cost startup_cost
Definition: pathnodes.h:1193
Cost disable_cost
Definition: costsize.c:129
List * joinrestrictinfo
Definition: pathnodes.h:1593
RelOptInfo * parent
Definition: pathnodes.h:1182
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6042
JoinPath jpath
Definition: pathnodes.h:1608
Path * outerjoinpath
Definition: pathnodes.h:1590
Cost total_cost
Definition: pathnodes.h:1194
Path path
Definition: pathnodes.h:1583
Cardinality rows
Definition: pathnodes.h:684
QualCost cost
Definition: pathnodes.h:1112
double cpu_tuple_cost
Definition: costsize.c:121
Selectivity match_count
Definition: pathnodes.h:2511
JoinType jointype
Definition: pathnodes.h:1585
Cardinality rows
Definition: pathnodes.h:1192
double clamp_row_est(double nrows)
Definition: costsize.c:199
double Cost
Definition: nodes.h:672

◆ get_parameterized_baserel_size()

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

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

4955 {
4956  List *allclauses;
4957  double nrows;
4958 
4959  /*
4960  * Estimate the number of rows returned by the parameterized scan, knowing
4961  * that it will apply all the extra join clauses as well as the rel's own
4962  * restriction clauses. Note that we force the clauses to be treated as
4963  * non-join clauses during selectivity estimation.
4964  */
4965  allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
4966  nrows = rel->tuples *
4968  allclauses,
4969  rel->relid, /* do not use 0! */
4970  JOIN_INNER,
4971  NULL);
4972  nrows = clamp_row_est(nrows);
4973  /* For safety, make sure result is not more than the base estimate */
4974  if (nrows > rel->rows)
4975  nrows = rel->rows;
4976  return nrows;
4977 }
List * baserestrictinfo
Definition: pathnodes.h:745
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:567
Index relid
Definition: pathnodes.h:709
Cardinality rows
Definition: pathnodes.h:684
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:199
Definition: pg_list.h:50
Cardinality tuples
Definition: pathnodes.h:721

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

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

Referenced by get_joinrel_parampathinfo().

5039 {
5040  double nrows;
5041 
5042  /*
5043  * Estimate the number of rows returned by the parameterized join as the
5044  * sizes of the input paths times the selectivity of the clauses that have
5045  * ended up at this join node.
5046  *
5047  * As with set_joinrel_size_estimates, the rowcount estimate could depend
5048  * on the pair of input paths provided, though ideally we'd get the same
5049  * estimate for any pair with the same parameterization.
5050  */
5051  nrows = calc_joinrel_size_estimate(root,
5052  rel,
5053  outer_path->parent,
5054  inner_path->parent,
5055  outer_path->rows,
5056  inner_path->rows,
5057  sjinfo,
5058  restrict_clauses);
5059  /* For safety, make sure result is not more than the base estimate */
5060  if (nrows > rel->rows)
5061  nrows = rel->rows;
5062  return nrows;
5063 }
RelOptInfo * parent
Definition: pathnodes.h:1182
Cardinality rows
Definition: pathnodes.h:684
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:5075
Cardinality rows
Definition: pathnodes.h:1192

◆ index_pages_fetched()

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

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

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

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

3747 {
3748  Cost startup_cost = 0;
3749  Cost run_cost = 0;
3750  double outer_path_rows = outer_path->rows;
3751  double inner_path_rows = inner_path->rows;
3752  double inner_path_rows_total = inner_path_rows;
3753  int num_hashclauses = list_length(hashclauses);
3754  int numbuckets;
3755  int numbatches;
3756  int num_skew_mcvs;
3757  size_t space_allowed; /* unused */
3758 
3759  /* cost of source data */
3760  startup_cost += outer_path->startup_cost;
3761  run_cost += outer_path->total_cost - outer_path->startup_cost;
3762  startup_cost += inner_path->total_cost;
3763 
3764  /*
3765  * Cost of computing hash function: must do it once per input tuple. We
3766  * charge one cpu_operator_cost for each column's hash function. Also,
3767  * tack on one cpu_tuple_cost per inner row, to model the costs of
3768  * inserting the row into the hashtable.
3769  *
3770  * XXX when a hashclause is more complex than a single operator, we really
3771  * should charge the extra eval costs of the left or right side, as
3772  * appropriate, here. This seems more work than it's worth at the moment.
3773  */
3774  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
3775  * inner_path_rows;
3776  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
3777 
3778  /*
3779  * If this is a parallel hash build, then the value we have for
3780  * inner_rows_total currently refers only to the rows returned by each
3781  * participant. For shared hash table size estimation, we need the total
3782  * number, so we need to undo the division.
3783  */
3784  if (parallel_hash)
3785  inner_path_rows_total *= get_parallel_divisor(inner_path);
3786 
3787  /*
3788  * Get hash table size that executor would use for inner relation.
3789  *
3790  * XXX for the moment, always assume that skew optimization will be
3791  * performed. As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
3792  * trying to determine that for sure.
3793  *
3794  * XXX at some point it might be interesting to try to account for skew
3795  * optimization in the cost estimate, but for now, we don't.
3796  */
3797  ExecChooseHashTableSize(inner_path_rows_total,
3798  inner_path->pathtarget->width,
3799  true, /* useskew */
3800  parallel_hash, /* try_combined_hash_mem */
3801  outer_path->parallel_workers,
3802  &space_allowed,
3803  &numbuckets,
3804  &numbatches,
3805  &num_skew_mcvs);
3806 
3807  /*
3808  * If inner relation is too big then we will need to "batch" the join,
3809  * which implies writing and reading most of the tuples to disk an extra
3810  * time. Charge seq_page_cost per page, since the I/O should be nice and
3811  * sequential. Writing the inner rel counts as startup cost, all the rest
3812  * as run cost.
3813  */
3814  if (numbatches > 1)
3815  {
3816  double outerpages = page_size(outer_path_rows,
3817  outer_path->pathtarget->width);
3818  double innerpages = page_size(inner_path_rows,
3819  inner_path->pathtarget->width);
3820 
3821  startup_cost += seq_page_cost * innerpages;
3822  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
3823  }
3824 
3825  /* CPU costs left for later */
3826 
3827  /* Public result fields */
3828  workspace->startup_cost = startup_cost;
3829  workspace->total_cost = startup_cost + run_cost;
3830  /* Save private data for final_cost_hashjoin */
3831  workspace->run_cost = run_cost;
3832  workspace->numbuckets = numbuckets;
3833  workspace->numbatches = numbatches;
3834  workspace->inner_rows_total = inner_path_rows_total;
3835 }
PathTarget * pathtarget
Definition: pathnodes.h:1183
int parallel_workers
Definition: pathnodes.h:1189
static double page_size(double tuples, int width)
Definition: costsize.c:6032
Cost startup_cost
Definition: pathnodes.h:1193
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6042
double cpu_operator_cost
Definition: costsize.c:123
Cost total_cost
Definition: pathnodes.h:1194
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
static int list_length(const List *l)
Definition: pg_list.h:149
double cpu_tuple_cost
Definition: costsize.c:121
Cardinality inner_rows_total
Definition: pathnodes.h:2654
Cardinality rows
Definition: pathnodes.h:1192
double seq_page_cost
Definition: costsize.c:119
double Cost
Definition: nodes.h:672

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

3189 {
3190  Cost startup_cost = 0;
3191  Cost run_cost = 0;
3192  double outer_path_rows = outer_path->rows;
3193  double inner_path_rows = inner_path->rows;
3194  Cost inner_run_cost;
3195  double outer_rows,
3196  inner_rows,
3197  outer_skip_rows,
3198  inner_skip_rows;
3199  Selectivity outerstartsel,
3200  outerendsel,
3201  innerstartsel,
3202  innerendsel;
3203  Path sort_path; /* dummy for result of cost_sort */
3204 
3205  /* Protect some assumptions below that rowcounts aren't zero */
3206  if (outer_path_rows <= 0)
3207  outer_path_rows = 1;
3208  if (inner_path_rows <= 0)
3209  inner_path_rows = 1;
3210 
3211  /*
3212  * A merge join will stop as soon as it exhausts either input stream
3213  * (unless it's an outer join, in which case the outer side has to be
3214  * scanned all the way anyway). Estimate fraction of the left and right
3215  * inputs that will actually need to be scanned. Likewise, we can
3216  * estimate the number of rows that will be skipped before the first join
3217  * pair is found, which should be factored into startup cost. We use only
3218  * the first (most significant) merge clause for this purpose. Since
3219  * mergejoinscansel() is a fairly expensive computation, we cache the
3220  * results in the merge clause RestrictInfo.
3221  */
3222  if (mergeclauses && jointype != JOIN_FULL)
3223  {
3224  RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
3225  List *opathkeys;
3226  List *ipathkeys;
3227  PathKey *opathkey;
3228  PathKey *ipathkey;
3229  MergeScanSelCache *cache;
3230 
3231  /* Get the input pathkeys to determine the sort-order details */
3232  opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
3233  ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
3234  Assert(opathkeys);
3235  Assert(ipathkeys);
3236  opathkey = (PathKey *) linitial(opathkeys);
3237  ipathkey = (PathKey *) linitial(ipathkeys);
3238  /* debugging check */
3239  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
3240  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
3241  opathkey->pk_strategy != ipathkey->pk_strategy ||
3242  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
3243  elog(ERROR, "left and right pathkeys do not match in mergejoin");
3244 
3245  /* Get the selectivity with caching */
3246  cache = cached_scansel(root, firstclause, opathkey);
3247 
3248  if (bms_is_subset(firstclause->left_relids,
3249  outer_path->parent->relids))
3250  {
3251  /* left side of clause is outer */
3252  outerstartsel = cache->leftstartsel;
3253  outerendsel = cache->leftendsel;
3254  innerstartsel = cache->rightstartsel;
3255  innerendsel = cache->rightendsel;
3256  }
3257  else
3258  {
3259  /* left side of clause is inner */
3260  outerstartsel = cache->rightstartsel;
3261  outerendsel = cache->rightendsel;
3262  innerstartsel = cache->leftstartsel;
3263  innerendsel = cache->leftendsel;
3264  }
3265  if (jointype == JOIN_LEFT ||
3266  jointype == JOIN_ANTI)
3267  {
3268  outerstartsel = 0.0;
3269  outerendsel = 1.0;
3270  }
3271  else if (jointype == JOIN_RIGHT)
3272  {
3273  innerstartsel = 0.0;
3274  innerendsel = 1.0;
3275  }
3276  }
3277  else
3278  {
3279  /* cope with clauseless or full mergejoin */
3280  outerstartsel = innerstartsel = 0.0;
3281  outerendsel = innerendsel = 1.0;
3282  }
3283 
3284  /*
3285  * Convert selectivities to row counts. We force outer_rows and
3286  * inner_rows to be at least 1, but the skip_rows estimates can be zero.
3287  */
3288  outer_skip_rows = rint(outer_path_rows * outerstartsel);
3289  inner_skip_rows = rint(inner_path_rows * innerstartsel);
3290  outer_rows = clamp_row_est(outer_path_rows * outerendsel);
3291  inner_rows = clamp_row_est(inner_path_rows * innerendsel);
3292 
3293  Assert(outer_skip_rows <= outer_rows);
3294  Assert(inner_skip_rows <= inner_rows);
3295 
3296  /*
3297  * Readjust scan selectivities to account for above rounding. This is
3298  * normally an insignificant effect, but when there are only a few rows in
3299  * the inputs, failing to do this makes for a large percentage error.
3300  */
3301  outerstartsel = outer_skip_rows / outer_path_rows;
3302  innerstartsel = inner_skip_rows / inner_path_rows;
3303  outerendsel = outer_rows / outer_path_rows;
3304  innerendsel = inner_rows / inner_path_rows;
3305 
3306  Assert(outerstartsel <= outerendsel);
3307  Assert(innerstartsel <= innerendsel);
3308 
3309  /* cost of source data */
3310 
3311  if (outersortkeys) /* do we need to sort outer? */
3312  {
3313  cost_sort(&sort_path,
3314  root,
3315  outersortkeys,
3316  outer_path->total_cost,
3317  outer_path_rows,
3318  outer_path->pathtarget->width,
3319  0.0,
3320  work_mem,
3321  -1.0);
3322  startup_cost += sort_path.startup_cost;
3323  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3324  * outerstartsel;
3325  run_cost += (sort_path.total_cost - sort_path.startup_cost)
3326  * (outerendsel - outerstartsel);
3327  }
3328  else
3329  {
3330  startup_cost += outer_path->startup_cost;
3331  startup_cost += (outer_path->total_cost - outer_path->startup_cost)
3332  * outerstartsel;
3333  run_cost += (outer_path->total_cost - outer_path->startup_cost)
3334  * (outerendsel - outerstartsel);
3335  }
3336 
3337  if (innersortkeys) /* do we need to sort inner? */
3338  {
3339  cost_sort(&sort_path,
3340  root,
3341  innersortkeys,
3342  inner_path->total_cost,
3343  inner_path_rows,
3344  inner_path->pathtarget->width,
3345  0.0,
3346  work_mem,
3347  -1.0);
3348  startup_cost += sort_path.startup_cost;
3349  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3350  * innerstartsel;
3351  inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
3352  * (innerendsel - innerstartsel);
3353  }
3354  else
3355  {
3356  startup_cost += inner_path->startup_cost;
3357  startup_cost += (inner_path->total_cost - inner_path->startup_cost)
3358  * innerstartsel;
3359  inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
3360  * (innerendsel - innerstartsel);
3361  }
3362 
3363  /*
3364  * We can't yet determine whether rescanning occurs, or whether
3365  * materialization of the inner input should be done. The minimum
3366  * possible inner input cost, regardless of rescan and materialization
3367  * considerations, is inner_run_cost. We include that in
3368  * workspace->total_cost, but not yet in run_cost.
3369  */
3370 
3371  /* CPU costs left for later */
3372 
3373  /* Public result fields */
3374  workspace->startup_cost = startup_cost;
3375  workspace->total_cost = startup_cost + run_cost + inner_run_cost;
3376  /* Save private data for final_cost_mergejoin */
3377  workspace->run_cost = run_cost;
3378  workspace->inner_run_cost = inner_run_cost;
3379  workspace->outer_rows = outer_rows;
3380  workspace->inner_rows = inner_rows;
3381  workspace->outer_skip_rows = outer_skip_rows;
3382  workspace->inner_skip_rows = inner_skip_rows;
3383 }
Selectivity leftendsel
Definition: pathnodes.h:2159
PathTarget * pathtarget
Definition: pathnodes.h:1183
static MergeScanSelCache * cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
Definition: costsize.c:3662
Relids left_relids
Definition: pathnodes.h:2086
Cardinality outer_skip_rows
Definition: pathnodes.h:2648
double Selectivity
Definition: nodes.h:671
int pk_strategy
Definition: pathnodes.h:1068
#define linitial(l)
Definition: pg_list.h:174
bool pk_nulls_first
Definition: pathnodes.h:1069
#define ERROR
Definition: elog.h:46
Cost startup_cost
Definition: pathnodes.h:1193
RelOptInfo * parent
Definition: pathnodes.h:1182
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
Cardinality inner_rows
Definition: pathnodes.h:2647
Selectivity rightstartsel
Definition: pathnodes.h:2160
Relids relids
Definition: pathnodes.h:681
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:2036
int work_mem
Definition: globals.c:124
Cost total_cost
Definition: pathnodes.h:1194
List * pathkeys
Definition: pathnodes.h:1196
#define Assert(condition)
Definition: c.h:804
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1066
Cardinality inner_skip_rows
Definition: pathnodes.h:2649
Oid pk_opfamily
Definition: pathnodes.h:1067
#define elog(elevel,...)
Definition: elog.h:232
Cardinality outer_rows
Definition: pathnodes.h:2646
Cardinality rows
Definition: pathnodes.h:1192
double clamp_row_est(double nrows)
Definition: costsize.c:199
Definition: pg_list.h:50
Selectivity rightendsel
Definition: pathnodes.h:2161
double Cost
Definition: nodes.h:672
Selectivity leftstartsel
Definition: pathnodes.h:2158

◆ initial_cost_nestloop()

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