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

Go to the source code of this file.

Macros

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

Enumerations

enum  ConstraintExclusionType { CONSTRAINT_EXCLUSION_OFF, CONSTRAINT_EXCLUSION_ON, CONSTRAINT_EXCLUSION_PARTITION }
 

Functions

double index_pages_fetched (double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
 
void cost_seqscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_samplescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_index (IndexPath *path, PlannerInfo *root, double loop_count, bool partial_path)
 
void cost_bitmap_heap_scan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, Path *bitmapqual, double loop_count)
 
void cost_bitmap_and_node (BitmapAndPath *path, PlannerInfo *root)
 
void cost_bitmap_or_node (BitmapOrPath *path, PlannerInfo *root)
 
void cost_bitmap_tree_node (Path *path, Cost *cost, Selectivity *selec)
 
void cost_tidscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
 
void cost_subqueryscan (SubqueryScanPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_functionscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_valuesscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_tablefuncscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_ctescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_namedtuplestorescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_resultscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_recursive_union (Path *runion, Path *nrterm, Path *rterm)
 
void cost_sort (Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_incremental_sort (Path *path, PlannerInfo *root, List *pathkeys, int presorted_keys, Cost input_startup_cost, Cost input_total_cost, double input_tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_append (AppendPath *path)
 
void cost_merge_append (Path *path, PlannerInfo *root, List *pathkeys, int n_streams, Cost input_startup_cost, Cost input_total_cost, double tuples)
 
void cost_material (Path *path, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
 
void cost_agg (Path *path, PlannerInfo *root, AggStrategy aggstrategy, const AggClauseCosts *aggcosts, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples, double input_width)
 
void cost_windowagg (Path *path, PlannerInfo *root, List *windowFuncs, int numPartCols, int numOrderCols, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_group (Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void initial_cost_nestloop (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, Path *outer_path, Path *inner_path, JoinPathExtraData *extra)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, JoinPathExtraData *extra)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, JoinPathExtraData *extra, bool parallel_hash)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void cost_gather (GatherPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, double *rows)
 
void cost_gather_merge (GatherMergePath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, Cost input_startup_cost, Cost input_total_cost, double *rows)
 
void cost_subplan (PlannerInfo *root, SubPlan *subplan, Plan *plan)
 
void cost_qual_eval (QualCost *cost, List *quals, PlannerInfo *root)
 
void cost_qual_eval_node (QualCost *cost, Node *qual, PlannerInfo *root)
 
void compute_semi_anti_join_factors (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, SpecialJoinInfo *sjinfo, List *restrictlist, SemiAntiJoinFactors *semifactors)
 
void set_baserel_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
double get_parameterized_baserel_size (PlannerInfo *root, RelOptInfo *rel, List *param_clauses)
 
double get_parameterized_joinrel_size (PlannerInfo *root, RelOptInfo *rel, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, List *restrict_clauses)
 
void set_joinrel_size_estimates (PlannerInfo *root, RelOptInfo *rel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo, List *restrictlist)
 
void set_subquery_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_function_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_values_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_cte_size_estimates (PlannerInfo *root, RelOptInfo *rel, double cte_rows)
 
void set_tablefunc_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_namedtuplestore_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_result_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_foreign_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
PathTargetset_pathtarget_cost_width (PlannerInfo *root, PathTarget *target)
 
double compute_bitmap_pages (PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
 

Variables

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

Macro Definition Documentation

◆ DEFAULT_CPU_INDEX_TUPLE_COST

#define DEFAULT_CPU_INDEX_TUPLE_COST   0.005

Definition at line 27 of file cost.h.

◆ DEFAULT_CPU_OPERATOR_COST

#define DEFAULT_CPU_OPERATOR_COST   0.0025

Definition at line 28 of file cost.h.

◆ DEFAULT_CPU_TUPLE_COST

#define DEFAULT_CPU_TUPLE_COST   0.01

Definition at line 26 of file cost.h.

◆ DEFAULT_EFFECTIVE_CACHE_SIZE

#define DEFAULT_EFFECTIVE_CACHE_SIZE   524288 /* measured in pages */

Definition at line 32 of file cost.h.

◆ DEFAULT_PARALLEL_SETUP_COST

#define DEFAULT_PARALLEL_SETUP_COST   1000.0

Definition at line 30 of file cost.h.

◆ DEFAULT_PARALLEL_TUPLE_COST

#define DEFAULT_PARALLEL_TUPLE_COST   0.1

Definition at line 29 of file cost.h.

◆ DEFAULT_RANDOM_PAGE_COST

#define DEFAULT_RANDOM_PAGE_COST   4.0

Definition at line 25 of file cost.h.

◆ DEFAULT_SEQ_PAGE_COST

#define DEFAULT_SEQ_PAGE_COST   1.0

Definition at line 24 of file cost.h.

Enumeration Type Documentation

◆ ConstraintExclusionType

Enumerator
CONSTRAINT_EXCLUSION_OFF 
CONSTRAINT_EXCLUSION_ON 
CONSTRAINT_EXCLUSION_PARTITION 

Definition at line 34 of file cost.h.

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

Function Documentation

◆ compute_bitmap_pages()

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

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

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

◆ compute_semi_anti_join_factors()

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

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

4401 {
4402  Selectivity jselec;
4403  Selectivity nselec;
4404  Selectivity avgmatch;
4405  SpecialJoinInfo norm_sjinfo;
4406  List *joinquals;
4407  ListCell *l;
4408 
4409  /*
4410  * In an ANTI join, we must ignore clauses that are "pushed down", since
4411  * those won't affect the match logic. In a SEMI join, we do not
4412  * distinguish joinquals from "pushed down" quals, so just use the whole
4413  * restrictinfo list. For other outer join types, we should consider only
4414  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
4415  */
4416  if (IS_OUTER_JOIN(jointype))
4417  {
4418  joinquals = NIL;
4419  foreach(l, restrictlist)
4420  {
4421  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4422 
4423  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
4424  joinquals = lappend(joinquals, rinfo);
4425  }
4426  }
4427  else
4428  joinquals = restrictlist;
4429 
4430  /*
4431  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
4432  */
4433  jselec = clauselist_selectivity(root,
4434  joinquals,
4435  0,
4436  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
4437  sjinfo);
4438 
4439  /*
4440  * Also get the normal inner-join selectivity of the join clauses.
4441  */
4442  norm_sjinfo.type = T_SpecialJoinInfo;
4443  norm_sjinfo.min_lefthand = outerrel->relids;
4444  norm_sjinfo.min_righthand = innerrel->relids;
4445  norm_sjinfo.syn_lefthand = outerrel->relids;
4446  norm_sjinfo.syn_righthand = innerrel->relids;
4447  norm_sjinfo.jointype = JOIN_INNER;
4448  /* we don't bother trying to make the remaining fields valid */
4449  norm_sjinfo.lhs_strict = false;
4450  norm_sjinfo.delay_upper_joins = false;
4451  norm_sjinfo.semi_can_btree = false;
4452  norm_sjinfo.semi_can_hash = false;
4453  norm_sjinfo.semi_operators = NIL;
4454  norm_sjinfo.semi_rhs_exprs = NIL;
4455 
4456  nselec = clauselist_selectivity(root,
4457  joinquals,
4458  0,
4459  JOIN_INNER,
4460  &norm_sjinfo);
4461 
4462  /* Avoid leaking a lot of ListCells */
4463  if (IS_OUTER_JOIN(jointype))
4464  list_free(joinquals);
4465 
4466  /*
4467  * jselec can be interpreted as the fraction of outer-rel rows that have
4468  * any matches (this is true for both SEMI and ANTI cases). And nselec is
4469  * the fraction of the Cartesian product that matches. So, the average
4470  * number of matches for each outer-rel row that has at least one match is
4471  * nselec * inner_rows / jselec.
4472  *
4473  * Note: it is correct to use the inner rel's "rows" count here, even
4474  * though we might later be considering a parameterized inner path with
4475  * fewer rows. This is because we have included all the join clauses in
4476  * the selectivity estimate.
4477  */
4478  if (jselec > 0) /* protect against zero divide */
4479  {
4480  avgmatch = nselec * innerrel->rows / jselec;
4481  /* Clamp to sane range */
4482  avgmatch = Max(1.0, avgmatch);
4483  }
4484  else
4485  avgmatch = 1.0;
4486 
4487  semifactors->outer_match_frac = jselec;
4488  semifactors->match_count = avgmatch;
4489 }
#define NIL
Definition: pg_list.h:65
Relids min_righthand
Definition: pathnodes.h:2175
Selectivity outer_match_frac
Definition: pathnodes.h:2404
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:744
double Selectivity
Definition: nodes.h:661
Relids syn_lefthand
Definition: pathnodes.h:2176
Relids syn_righthand
Definition: pathnodes.h:2177
List * semi_rhs_exprs
Definition: pathnodes.h:2185
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Relids relids
Definition: pathnodes.h:664
List * lappend(List *list, void *datum)
Definition: list.c:321
bool delay_upper_joins
Definition: pathnodes.h:2180
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2061
double rows
Definition: pathnodes.h:667
#define Max(x, y)
Definition: c.h:922
JoinType jointype
Definition: pathnodes.h:2178
Selectivity match_count
Definition: pathnodes.h:2405
List * semi_operators
Definition: pathnodes.h:2184
void list_free(List *list)
Definition: list.c:1376
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
Definition: pg_list.h:50
Relids min_lefthand
Definition: pathnodes.h:2174

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

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

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

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

◆ cost_append()

void cost_append ( AppendPath path)

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

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

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1096 of file costsize.c.

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

Referenced by create_bitmap_and_path().

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

◆ cost_bitmap_heap_scan()

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

Definition at line 952 of file costsize.c.

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

Referenced by bitmap_scan_cost_est(), and create_bitmap_heap_path().

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

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1140 of file costsize.c.

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

Referenced by create_bitmap_or_path().

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

◆ cost_bitmap_tree_node()

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

Definition at line 1053 of file costsize.c.

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

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

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

◆ cost_ctescan()

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

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

1512 {
1513  Cost startup_cost = 0;
1514  Cost run_cost = 0;
1515  QualCost qpqual_cost;
1516  Cost cpu_per_tuple;
1517 
1518  /* Should only be applied to base relations that are CTEs */
1519  Assert(baserel->relid > 0);
1520  Assert(baserel->rtekind == RTE_CTE);
1521 
1522  /* Mark the path with the correct row estimate */
1523  if (param_info)
1524  path->rows = param_info->ppi_rows;
1525  else
1526  path->rows = baserel->rows;
1527 
1528  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1529  cpu_per_tuple = cpu_tuple_cost;
1530 
1531  /* Add scanning CPU costs */
1532  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1533 
1534  startup_cost += qpqual_cost.startup;
1535  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1536  run_cost += cpu_per_tuple * baserel->tuples;
1537 
1538  /* tlist eval costs are paid per output row, not per tuple scanned */
1539  startup_cost += path->pathtarget->cost.startup;
1540  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1541 
1542  path->startup_cost = startup_cost;
1543  path->total_cost = startup_cost + run_cost;
1544 }
PathTarget * pathtarget
Definition: pathnodes.h:1144
double tuples
Definition: pathnodes.h:704
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1154
Index relid
Definition: pathnodes.h:692
RTEKind rtekind
Definition: pathnodes.h:694
double rows
Definition: pathnodes.h:667
Cost total_cost
Definition: pathnodes.h:1155
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4351
#define Assert(condition)
Definition: c.h:746
double rows
Definition: pathnodes.h:1153
QualCost cost
Definition: pathnodes.h:1075
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1103
double Cost
Definition: nodes.h:662

◆ cost_functionscan()

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

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

1345 {
1346  Cost startup_cost = 0;
1347  Cost run_cost = 0;
1348  QualCost qpqual_cost;
1349  Cost cpu_per_tuple;
1350  RangeTblEntry *rte;
1351  QualCost exprcost;
1352 
1353  /* Should only be applied to base relations that are functions */
1354  Assert(baserel->relid > 0);
1355  rte = planner_rt_fetch(baserel->relid, root);
1356  Assert(rte->rtekind == RTE_FUNCTION);
1357 
1358  /* Mark the path with the correct row estimate */
1359  if (param_info)
1360  path->rows = param_info->ppi_rows;
1361  else
1362  path->rows = baserel->rows;
1363 
1364  /*
1365  * Estimate costs of executing the function expression(s).
1366  *
1367  * Currently, nodeFunctionscan.c always executes the functions to
1368  * completion before returning any rows, and caches the results in a
1369  * tuplestore. So the function eval cost is all startup cost, and per-row
1370  * costs are minimal.
1371  *
1372  * XXX in principle we ought to charge tuplestore spill costs if the
1373  * number of rows is large. However, given how phony our rowcount
1374  * estimates for functions tend to be, there's not a lot of point in that
1375  * refinement right now.
1376  */
1377  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1378 
1379  startup_cost += exprcost.startup + exprcost.per_tuple;
1380 
1381  /* Add scanning CPU costs */
1382  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1383 
1384  startup_cost += qpqual_cost.startup;
1385  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1386  run_cost += cpu_per_tuple * baserel->tuples;
1387 
1388  /* tlist eval costs are paid per output row, not per tuple scanned */
1389  startup_cost += path->pathtarget->cost.startup;
1390  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1391 
1392  path->startup_cost = startup_cost;
1393  path->total_cost = startup_cost + run_cost;
1394 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4091
PathTarget * pathtarget
Definition: pathnodes.h:1144
double tuples
Definition: pathnodes.h:704
Definition: nodes.h:528
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1154
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:372
Index relid
Definition: pathnodes.h:692
double rows
Definition: pathnodes.h:667
Cost total_cost
Definition: pathnodes.h:1155
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4351
#define Assert(condition)
Definition: c.h:746
List * functions
Definition: parsenodes.h:1064
double rows
Definition: pathnodes.h:1153
QualCost cost
Definition: pathnodes.h:1075
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1103
RTEKind rtekind
Definition: parsenodes.h:977
double Cost
Definition: nodes.h:662

◆ cost_gather()

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

Definition at line 375 of file costsize.c.

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

Referenced by create_gather_path().

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

◆ cost_gather_merge()

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

Definition at line 413 of file costsize.c.

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

Referenced by create_gather_merge_path().

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

◆ cost_group()

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

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

2596 {
2597  double output_tuples;
2598  Cost startup_cost;
2599  Cost total_cost;
2600 
2601  output_tuples = numGroups;
2602  startup_cost = input_startup_cost;
2603  total_cost = input_total_cost;
2604 
2605  /*
2606  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2607  * all columns get compared at most of the tuples.
2608  */
2609  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2610 
2611  /*
2612  * If there are quals (HAVING quals), account for their cost and
2613  * selectivity.
2614  */
2615  if (quals)
2616  {
2617  QualCost qual_cost;
2618 
2619  cost_qual_eval(&qual_cost, quals, root);
2620  startup_cost += qual_cost.startup;
2621  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2622 
2623  output_tuples = clamp_row_est(output_tuples *
2625  quals,
2626  0,
2627  JOIN_INNER,
2628  NULL));
2629  }
2630 
2631  path->rows = output_tuples;
2632  path->startup_cost = startup_cost;
2633  path->total_cost = total_cost;
2634 }
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:4065
Cost startup_cost
Definition: pathnodes.h:1154
double cpu_operator_cost
Definition: costsize.c:122
Cost total_cost
Definition: pathnodes.h:1155
double rows
Definition: pathnodes.h:1153
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
double clamp_row_est(double nrows)
Definition: costsize.c:196
double Cost
Definition: nodes.h:662

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

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

Referenced by create_incremental_sort_path().

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

◆ cost_index()

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

Definition at line 488 of file costsize.c.

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

Referenced by create_index_path(), and reparameterize_path().

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

◆ cost_material()

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

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

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

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

2221 {
2222  Cost startup_cost = 0;
2223  Cost run_cost = 0;
2224  Cost comparison_cost;
2225  double N;
2226  double logN;
2227 
2228  /*
2229  * Avoid log(0)...
2230  */
2231  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2232  logN = LOG2(N);
2233 
2234  /* Assumed cost per tuple comparison */
2235  comparison_cost = 2.0 * cpu_operator_cost;
2236 
2237  /* Heap creation cost */
2238  startup_cost += comparison_cost * N * logN;
2239 
2240  /* Per-tuple heap maintenance cost */
2241  run_cost += tuples * comparison_cost * logN;
2242 
2243  /*
2244  * Although MergeAppend does not do any selection or projection, it's not
2245  * free; add a small per-tuple overhead.
2246  */
2247  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2248 
2249  path->startup_cost = startup_cost + input_startup_cost;
2250  path->total_cost = startup_cost + run_cost + input_total_cost;
2251 }
Cost startup_cost
Definition: pathnodes.h:1154
double cpu_operator_cost
Definition: costsize.c:122
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:108
Cost total_cost
Definition: pathnodes.h:1155
#define LOG2(x)
Definition: costsize.c:101
double cpu_tuple_cost
Definition: costsize.c:120
double Cost
Definition: nodes.h:662

◆ cost_namedtuplestorescan()

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

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

1553 {
1554  Cost startup_cost = 0;
1555  Cost run_cost = 0;
1556  QualCost qpqual_cost;
1557  Cost cpu_per_tuple;
1558 
1559  /* Should only be applied to base relations that are Tuplestores */
1560  Assert(baserel->relid > 0);
1561  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1562 
1563  /* Mark the path with the correct row estimate */
1564  if (param_info)
1565  path->rows = param_info->ppi_rows;
1566  else
1567  path->rows = baserel->rows;
1568 
1569  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1570  cpu_per_tuple = cpu_tuple_cost;
1571 
1572  /* Add scanning CPU costs */
1573  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1574 
1575  startup_cost += qpqual_cost.startup;
1576  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1577  run_cost += cpu_per_tuple * baserel->tuples;
1578 
1579  path->startup_cost = startup_cost;
1580  path->total_cost = startup_cost + run_cost;
1581 }
double tuples
Definition: pathnodes.h:704
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1154
Index relid
Definition: pathnodes.h:692
RTEKind rtekind
Definition: pathnodes.h:694
double rows
Definition: pathnodes.h:667
Cost total_cost
Definition: pathnodes.h:1155
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4351
#define Assert(condition)
Definition: c.h:746
double rows
Definition: pathnodes.h:1153
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1103
double Cost
Definition: nodes.h:662

◆ cost_qual_eval()

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

Definition at line 4065 of file costsize.c.

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

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

4066 {
4067  cost_qual_eval_context context;
4068  ListCell *l;
4069 
4070  context.root = root;
4071  context.total.startup = 0;
4072  context.total.per_tuple = 0;
4073 
4074  /* We don't charge any cost for the implicit ANDing at top level ... */
4075 
4076  foreach(l, quals)
4077  {
4078  Node *qual = (Node *) lfirst(l);
4079 
4080  cost_qual_eval_walker(qual, &context);
4081  }
4082 
4083  *cost = context.total;
4084 }
PlannerInfo * root
Definition: costsize.c:153
Definition: nodes.h:528
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:4105
#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 4091 of file costsize.c.

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

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

4092 {
4093  cost_qual_eval_context context;
4094 
4095  context.root = root;
4096  context.total.startup = 0;
4097  context.total.per_tuple = 0;
4098 
4099  cost_qual_eval_walker(qual, &context);
4100 
4101  *cost = context.total;
4102 }
PlannerInfo * root
Definition: costsize.c:153
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4105

◆ cost_recursive_union()

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

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

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

◆ cost_resultscan()

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

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

1590 {
1591  Cost startup_cost = 0;
1592  Cost run_cost = 0;
1593  QualCost qpqual_cost;
1594  Cost cpu_per_tuple;
1595 
1596  /* Should only be applied to RTE_RESULT base relations */
1597  Assert(baserel->relid > 0);
1598  Assert(baserel->rtekind == RTE_RESULT);
1599 
1600  /* Mark the path with the correct row estimate */
1601  if (param_info)
1602  path->rows = param_info->ppi_rows;
1603  else
1604  path->rows = baserel->rows;
1605 
1606  /* We charge qual cost plus cpu_tuple_cost */
1607  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1608 
1609  startup_cost += qpqual_cost.startup;
1610  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1611  run_cost += cpu_per_tuple * baserel->tuples;
1612 
1613  path->startup_cost = startup_cost;
1614  path->total_cost = startup_cost + run_cost;
1615 }
double tuples
Definition: pathnodes.h:704
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1154
Index relid
Definition: pathnodes.h:692
RTEKind rtekind
Definition: pathnodes.h:694
double rows
Definition: pathnodes.h:667
Cost total_cost
Definition: pathnodes.h:1155
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4351
#define Assert(condition)
Definition: c.h:746
double rows
Definition: pathnodes.h:1153
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1103
double Cost
Definition: nodes.h:662

◆ cost_samplescan()

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

Definition at line 300 of file costsize.c.

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

Referenced by create_samplescan_path().

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

◆ cost_seqscan()

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

Definition at line 223 of file costsize.c.

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

Referenced by create_seqscan_path().

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

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

1942 {
1943  Cost startup_cost;
1944  Cost run_cost;
1945 
1946  cost_tuplesort(&startup_cost, &run_cost,
1947  tuples, width,
1948  comparison_cost, sort_mem,
1949  limit_tuples);
1950 
1951  if (!enable_sort)
1952  startup_cost += disable_cost;
1953 
1954  startup_cost += input_cost;
1955 
1956  path->rows = tuples;
1957  path->startup_cost = startup_cost;
1958  path->total_cost = startup_cost + run_cost;
1959 }
bool enable_sort
Definition: costsize.c:137
Cost startup_cost
Definition: pathnodes.h:1154
Cost disable_cost
Definition: costsize.c:128
static void cost_tuplesort(Cost *startup_cost, Cost *run_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:1696
Cost total_cost
Definition: pathnodes.h:1155
double rows
Definition: pathnodes.h:1153
double Cost
Definition: nodes.h:662

◆ cost_subplan()

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

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

3866 {
3867  QualCost sp_cost;
3868 
3869  /* Figure any cost for evaluating the testexpr */
3870  cost_qual_eval(&sp_cost,
3871  make_ands_implicit((Expr *) subplan->testexpr),
3872  root);
3873 
3874  if (subplan->useHashTable)
3875  {
3876  /*
3877  * If we are using a hash table for the subquery outputs, then the
3878  * cost of evaluating the query is a one-time cost. We charge one
3879  * cpu_operator_cost per tuple for the work of loading the hashtable,
3880  * too.
3881  */
3882  sp_cost.startup += plan->total_cost +
3883  cpu_operator_cost * plan->plan_rows;
3884 
3885  /*
3886  * The per-tuple costs include the cost of evaluating the lefthand
3887  * expressions, plus the cost of probing the hashtable. We already
3888  * accounted for the lefthand expressions as part of the testexpr, and
3889  * will also have counted one cpu_operator_cost for each comparison
3890  * operator. That is probably too low for the probing cost, but it's
3891  * hard to make a better estimate, so live with it for now.
3892  */
3893  }
3894  else
3895  {
3896  /*
3897  * Otherwise we will be rescanning the subplan output on each
3898  * evaluation. We need to estimate how much of the output we will
3899  * actually need to scan. NOTE: this logic should agree with the
3900  * tuple_fraction estimates used by make_subplan() in
3901  * plan/subselect.c.
3902  */
3903  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
3904 
3905  if (subplan->subLinkType == EXISTS_SUBLINK)
3906  {
3907  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
3908  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
3909  }
3910  else if (subplan->subLinkType == ALL_SUBLINK ||
3911  subplan->subLinkType == ANY_SUBLINK)
3912  {
3913  /* assume we need 50% of the tuples */
3914  sp_cost.per_tuple += 0.50 * plan_run_cost;
3915  /* also charge a cpu_operator_cost per row examined */
3916  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
3917  }
3918  else
3919  {
3920  /* assume we need all tuples */
3921  sp_cost.per_tuple += plan_run_cost;
3922  }
3923 
3924  /*
3925  * Also account for subplan's startup cost. If the subplan is
3926  * uncorrelated or undirect correlated, AND its topmost node is one
3927  * that materializes its output, assume that we'll only need to pay
3928  * its startup cost once; otherwise assume we pay the startup cost
3929  * every time.
3930  */
3931  if (subplan->parParam == NIL &&
3933  sp_cost.startup += plan->startup_cost;
3934  else
3935  sp_cost.per_tuple += plan->startup_cost;
3936  }
3937 
3938  subplan->startup_cost = sp_cost.startup;
3939  subplan->per_call_cost = sp_cost.per_tuple;
3940 }
#define NIL
Definition: pg_list.h:65
double plan_rows
Definition: plannodes.h:123
SubLinkType subLinkType
Definition: primnodes.h:704
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4065
Cost startup_cost
Definition: plannodes.h:117
double cpu_operator_cost
Definition: costsize.c:122
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:718
Node * testexpr
Definition: primnodes.h:706
Cost per_call_cost
Definition: primnodes.h:733
List * parParam
Definition: primnodes.h:729
#define nodeTag(nodeptr)
Definition: nodes.h:533
Cost total_cost
Definition: plannodes.h:118
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:623
bool useHashTable
Definition: primnodes.h:718
Cost startup_cost
Definition: primnodes.h:732
double clamp_row_est(double nrows)
Definition: costsize.c:196
double Cost
Definition: nodes.h:662

◆ cost_subqueryscan()

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

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

1296 {
1297  Cost startup_cost;
1298  Cost run_cost;
1299  QualCost qpqual_cost;
1300  Cost cpu_per_tuple;
1301 
1302  /* Should only be applied to base relations that are subqueries */
1303  Assert(baserel->relid > 0);
1304  Assert(baserel->rtekind == RTE_SUBQUERY);
1305 
1306  /* Mark the path with the correct row estimate */
1307  if (param_info)
1308  path->path.rows = param_info->ppi_rows;
1309  else
1310  path->path.rows = baserel->rows;
1311 
1312  /*
1313  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1314  * any restriction clauses and tlist that will be attached to the
1315  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1316  * projection overhead.
1317  */
1318  path->path.startup_cost = path->subpath->startup_cost;
1319  path->path.total_cost = path->subpath->total_cost;
1320 
1321  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1322 
1323  startup_cost = qpqual_cost.startup;
1324  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1325  run_cost = cpu_per_tuple * baserel->tuples;
1326 
1327  /* tlist eval costs are paid per output row, not per tuple scanned */
1328  startup_cost += path->path.pathtarget->cost.startup;
1329  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1330 
1331  path->path.startup_cost += startup_cost;
1332  path->path.total_cost += startup_cost + run_cost;
1333 }
PathTarget * pathtarget
Definition: pathnodes.h:1144
double tuples
Definition: pathnodes.h:704
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1154
Index relid
Definition: pathnodes.h:692
RTEKind rtekind
Definition: pathnodes.h:694
double rows
Definition: pathnodes.h:667
Cost total_cost
Definition: pathnodes.h:1155
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4351
#define Assert(condition)
Definition: c.h:746
double rows
Definition: pathnodes.h:1153
QualCost cost
Definition: pathnodes.h:1075
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1103
double Cost
Definition: nodes.h:662

◆ cost_tablefuncscan()

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

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

1406 {
1407  Cost startup_cost = 0;
1408  Cost run_cost = 0;
1409  QualCost qpqual_cost;
1410  Cost cpu_per_tuple;
1411  RangeTblEntry *rte;
1412  QualCost exprcost;
1413 
1414  /* Should only be applied to base relations that are functions */
1415  Assert(baserel->relid > 0);
1416  rte = planner_rt_fetch(baserel->relid, root);
1417  Assert(rte->rtekind == RTE_TABLEFUNC);
1418 
1419  /* Mark the path with the correct row estimate */
1420  if (param_info)
1421  path->rows = param_info->ppi_rows;
1422  else
1423  path->rows = baserel->rows;
1424 
1425  /*
1426  * Estimate costs of executing the table func expression(s).
1427  *
1428  * XXX in principle we ought to charge tuplestore spill costs if the
1429  * number of rows is large. However, given how phony our rowcount
1430  * estimates for tablefuncs tend to be, there's not a lot of point in that
1431  * refinement right now.
1432  */
1433  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1434 
1435  startup_cost += exprcost.startup + exprcost.per_tuple;
1436 
1437  /* Add scanning CPU costs */
1438  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1439 
1440  startup_cost += qpqual_cost.startup;
1441  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1442  run_cost += cpu_per_tuple * baserel->tuples;
1443 
1444  /* tlist eval costs are paid per output row, not per tuple scanned */
1445  startup_cost += path->pathtarget->cost.startup;
1446  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1447 
1448  path->startup_cost = startup_cost;
1449  path->total_cost = startup_cost + run_cost;
1450 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4091
PathTarget * pathtarget
Definition: pathnodes.h:1144
double tuples
Definition: pathnodes.h:704
Definition: nodes.h:528
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
TableFunc * tablefunc
Definition: parsenodes.h:1070
Cost startup_cost
Definition: pathnodes.h:1154
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:372
Index relid
Definition: pathnodes.h:692
double rows
Definition: pathnodes.h:667
Cost total_cost
Definition: pathnodes.h:1155
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4351
#define Assert(condition)
Definition: c.h:746
double rows
Definition: pathnodes.h:1153
QualCost cost
Definition: pathnodes.h:1075
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1103
RTEKind rtekind
Definition: parsenodes.h:977
double Cost
Definition: nodes.h:662

◆ cost_tidscan()

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

Definition at line 1188 of file costsize.c.

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

Referenced by create_tidscan_path().

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

◆ cost_valuesscan()

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

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

1462 {
1463  Cost startup_cost = 0;
1464  Cost run_cost = 0;
1465  QualCost qpqual_cost;
1466  Cost cpu_per_tuple;
1467 
1468  /* Should only be applied to base relations that are values lists */
1469  Assert(baserel->relid > 0);
1470  Assert(baserel->rtekind == RTE_VALUES);
1471 
1472  /* Mark the path with the correct row estimate */
1473  if (param_info)
1474  path->rows = param_info->ppi_rows;
1475  else
1476  path->rows = baserel->rows;
1477 
1478  /*
1479  * For now, estimate list evaluation cost at one operator eval per list
1480  * (probably pretty bogus, but is it worth being smarter?)
1481  */
1482  cpu_per_tuple = cpu_operator_cost;
1483 
1484  /* Add scanning CPU costs */
1485  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1486 
1487  startup_cost += qpqual_cost.startup;
1488  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1489  run_cost += cpu_per_tuple * baserel->tuples;
1490 
1491  /* tlist eval costs are paid per output row, not per tuple scanned */
1492  startup_cost += path->pathtarget->cost.startup;
1493  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1494 
1495  path->startup_cost = startup_cost;
1496  path->total_cost = startup_cost + run_cost;
1497 }
PathTarget * pathtarget
Definition: pathnodes.h:1144
double tuples
Definition: pathnodes.h:704
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1154
double cpu_operator_cost
Definition: costsize.c:122
Index relid
Definition: pathnodes.h:692
RTEKind rtekind
Definition: pathnodes.h:694
double rows
Definition: pathnodes.h:667
Cost total_cost
Definition: pathnodes.h:1155
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4351
#define Assert(condition)
Definition: c.h:746
double rows
Definition: pathnodes.h:1153
QualCost cost
Definition: pathnodes.h:1075
double cpu_tuple_cost
Definition: costsize.c:120
double ppi_rows
Definition: pathnodes.h:1103
double Cost
Definition: nodes.h:662

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

2521 {
2522  Cost startup_cost;
2523  Cost total_cost;
2524  ListCell *lc;
2525 
2526  startup_cost = input_startup_cost;
2527  total_cost = input_total_cost;
2528 
2529  /*
2530  * Window functions are assumed to cost their stated execution cost, plus
2531  * the cost of evaluating their input expressions, per tuple. Since they
2532  * may in fact evaluate their inputs at multiple rows during each cycle,
2533  * this could be a drastic underestimate; but without a way to know how
2534  * many rows the window function will fetch, it's hard to do better. In
2535  * any case, it's a good estimate for all the built-in window functions,
2536  * so we'll just do this for now.
2537  */
2538  foreach(lc, windowFuncs)
2539  {
2540  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
2541  Cost wfunccost;
2542  QualCost argcosts;
2543 
2544  argcosts.startup = argcosts.per_tuple = 0;
2545  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
2546  &argcosts);
2547  startup_cost += argcosts.startup;
2548  wfunccost = argcosts.per_tuple;
2549 
2550  /* also add the input expressions' cost to per-input-row costs */
2551  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
2552  startup_cost += argcosts.startup;
2553  wfunccost += argcosts.per_tuple;
2554 
2555  /*
2556  * Add the filter's cost to per-input-row costs. XXX We should reduce
2557  * input expression costs according to filter selectivity.
2558  */
2559  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
2560  startup_cost += argcosts.startup;
2561  wfunccost += argcosts.per_tuple;
2562 
2563  total_cost += wfunccost * input_tuples;
2564  }
2565 
2566  /*
2567  * We also charge cpu_operator_cost per grouping column per tuple for
2568  * grouping comparisons, plus cpu_tuple_cost per tuple for general
2569  * overhead.
2570  *
2571  * XXX this neglects costs of spooling the data to disk when it overflows
2572  * work_mem. Sooner or later that should get accounted for.
2573  */
2574  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
2575  total_cost += cpu_tuple_cost * input_tuples;
2576 
2577  path->rows = input_tuples;
2578  path->startup_cost = startup_cost;
2579  path->total_cost = total_cost;
2580 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4091
List * args
Definition: primnodes.h:377
Definition: nodes.h:528
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:1905
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
Cost startup_cost
Definition: pathnodes.h:1154
#define lfirst_node(type, lc)
Definition: pg_list.h:172
double cpu_operator_cost
Definition: costsize.c:122
Oid winfnoid
Definition: primnodes.h:373
Cost total_cost
Definition: pathnodes.h:1155
Expr * aggfilter
Definition: primnodes.h:378
double rows
Definition: pathnodes.h:1153
double cpu_tuple_cost
Definition: costsize.c:120
double Cost
Definition: nodes.h:662

◆ final_cost_hashjoin()

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

Definition at line 3608 of file costsize.c.

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

Referenced by create_hashjoin_path().

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

◆ final_cost_mergejoin()

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

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

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

◆ final_cost_nestloop()

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

Definition at line 2736 of file costsize.c.

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

Referenced by create_nestloop_path().

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

◆ get_parameterized_baserel_size()

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

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

4682 {
4683  List *allclauses;
4684  double nrows;
4685 
4686  /*
4687  * Estimate the number of rows returned by the parameterized scan, knowing
4688  * that it will apply all the extra join clauses as well as the rel's own
4689  * restriction clauses. Note that we force the clauses to be treated as
4690  * non-join clauses during selectivity estimation.
4691  */
4692  allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
4693  nrows = rel->tuples *
4695  allclauses,
4696  rel->relid, /* do not use 0! */
4697  JOIN_INNER,
4698  NULL);
4699  nrows = clamp_row_est(nrows);
4700  /* For safety, make sure result is not more than the base estimate */
4701  if (nrows > rel->rows)
4702  nrows = rel->rows;
4703  return nrows;
4704 }
double tuples
Definition: pathnodes.h:704
List * baserestrictinfo
Definition: pathnodes.h:726
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:552
Index relid
Definition: pathnodes.h:692
double rows
Definition: pathnodes.h:667
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
double clamp_row_est(double nrows)
Definition: costsize.c:196
Definition: pg_list.h:50

◆ get_parameterized_joinrel_size()

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

Definition at line 4761 of file costsize.c.

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

Referenced by get_joinrel_parampathinfo().

4766 {
4767  double nrows;
4768 
4769  /*
4770  * Estimate the number of rows returned by the parameterized join as the
4771  * sizes of the input paths times the selectivity of the clauses that have
4772  * ended up at this join node.
4773  *
4774  * As with set_joinrel_size_estimates, the rowcount estimate could depend
4775  * on the pair of input paths provided, though ideally we'd get the same
4776  * estimate for any pair with the same parameterization.
4777  */
4778  nrows = calc_joinrel_size_estimate(root,
4779  rel,
4780  outer_path->parent,
4781  inner_path->parent,
4782  outer_path->rows,
4783  inner_path->rows,
4784  sjinfo,
4785  restrict_clauses);
4786  /* For safety, make sure result is not more than the base estimate */
4787  if (nrows > rel->rows)
4788  nrows = rel->rows;
4789  return nrows;
4790 }
RelOptInfo * parent
Definition: pathnodes.h:1143
double rows
Definition: pathnodes.h:667
double rows
Definition: pathnodes.h:1153
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:4802

◆ index_pages_fetched()

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

Definition at line 837 of file costsize.c.

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

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

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

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

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

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

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

◆ initial_cost_nestloop()

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

Definition at line 2661 of file costsize.c.

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

Referenced by try_nestloop_path(), and try_partial_nestloop_path().

2665 {
2666  Cost startup_cost = 0;
2667  Cost run_cost = 0;
2668  double outer_path_rows = outer_path->rows;
2669  Cost inner_rescan_start_cost;
2670  Cost inner_rescan_total_cost;
2671  Cost inner_run_cost;
2672  Cost inner_rescan_run_cost;
2673 
2674  /* estimate costs to rescan the inner relation */
2675  cost_rescan(root, inner_path,
2676  &inner_rescan_start_cost,
2677  &inner_rescan_total_cost);
2678 
2679  /* cost of source data */
2680 
2681  /*
2682  * NOTE: clearly, we must pay both outer and inner paths' startup_cost
2683  * before we can start returning tuples, so the join's startup cost is
2684  * their sum. We'll also pay the inner path's rescan startup cost
2685  * multiple times.
2686  */
2687  startup_cost += outer_path->startup_cost + inner_path->startup_cost;
2688  run_cost += outer_path->total_cost - outer_path->startup_cost;
2689  if (outer_path_rows > 1)
2690  run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
2691 
2692  inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
2693  inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
2694 
2695  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
2696  extra->inner_unique)
2697  {
2698  /*
2699  * With a SEMI or ANTI join, or if the innerrel is known unique, the
2700  * executor will stop after the first match.
2701  *
2702  * Getting decent estimates requires inspection of the join quals,
2703  * which we choose to postpone to final_cost_nestloop.
2704  */
2705 
2706  /* Save private data for final_cost_nestloop */
2707  workspace->inner_run_cost = inner_run_cost;
2708  workspace->inner_rescan_run_cost = inner_rescan_run_cost;
2709  }
2710  else
2711  {
2712  /* Normal case; we'll scan whole input rel for each outer row */
2713  run_cost += inner_run_cost;
2714  if (outer_path_rows > 1)
2715  run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
2716  }
2717 
2718  /* CPU costs left for later */
2719 
2720  /* Public result fields */
2721  workspace->startup_cost = startup_cost;
2722  workspace->total_cost = startup_cost + run_cost;
2723  /* Save private data for final_cost_nestloop */
2724  workspace->run_cost = run_cost;
2725 }
static void cost_rescan(PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:3958
Cost inner_rescan_run_cost
Definition: pathnodes.h:2537
Cost startup_cost
Definition: pathnodes.h:1154
Cost total_cost
Definition: pathnodes.h:1155
double rows
Definition: pathnodes.h:1153
double Cost
Definition: nodes.h:662

◆ set_baserel_size_estimates()

void set_baserel_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 4650 of file costsize.c.

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

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

4651 {
4652  double nrows;
4653 
4654  /* Should only be applied to base relations */
4655  Assert(rel->relid > 0);
4656 
4657  nrows = rel->tuples *
4659  rel->baserestrictinfo,
4660  0,
4661  JOIN_INNER,
4662  NULL);
4663 
4664  rel->rows = clamp_row_est(nrows);
4665 
4667 
4668  set_rel_width(root, rel);
4669 }
double tuples
Definition: pathnodes.h:704
List * baserestrictinfo
Definition: pathnodes.h:726
static void set_rel_width(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5464
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4065
Index relid
Definition: pathnodes.h:692
double rows
Definition: pathnodes.h:667
#define Assert(condition)
Definition: c.h:746
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
double clamp_row_est(double nrows)
Definition: costsize.c:196
QualCost baserestrictcost
Definition: pathnodes.h:727

◆ set_cte_size_estimates()

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

Definition at line 5330 of file costsize.c.

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

Referenced by set_cte_pathlist(), and set_worktable_pathlist().

5331 {
5332  RangeTblEntry *rte;
5333 
5334  /* Should only be applied to base relations that are CTE references */
5335  Assert(rel->relid > 0);
5336  rte = planner_rt_fetch(rel->relid, root);
5337  Assert(rte->rtekind == RTE_CTE);
5338 
5339  if (rte->self_reference)
5340  {
5341  /*
5342  * In a self-reference, arbitrarily assume the average worktable size
5343  * is about 10 times the nonrecursive term's size.
5344  */
5345  rel->tuples = 10 * cte_rows;
5346  }
5347  else
5348  {
5349  /* Otherwise just believe the CTE's rowcount estimate */
5350  rel->tuples = cte_rows;
5351  }
5352 
5353  /* Now estimate number of output rows, etc */
5354  set_baserel_size_estimates(root, rel);
5355 }
double tuples
Definition: pathnodes.h:704
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:372
Index relid
Definition: pathnodes.h:692