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_incrementalsort
 
PGDLLIMPORT bool enable_hashagg
 
PGDLLIMPORT bool enable_hashagg_disk
 
PGDLLIMPORT bool enable_groupingsets_hash_disk
 
PGDLLIMPORT bool enable_nestloop
 
PGDLLIMPORT bool enable_material
 
PGDLLIMPORT bool enable_mergejoin
 
PGDLLIMPORT bool enable_hashjoin
 
PGDLLIMPORT bool enable_gathermerge
 
PGDLLIMPORT bool enable_partitionwise_join
 
PGDLLIMPORT bool enable_partitionwise_aggregate
 
PGDLLIMPORT bool enable_parallel_append
 
PGDLLIMPORT bool enable_parallel_hash
 
PGDLLIMPORT bool enable_partition_pruning
 
PGDLLIMPORT int constraint_exclusion
 

Macro Definition Documentation

◆ DEFAULT_CPU_INDEX_TUPLE_COST

#define DEFAULT_CPU_INDEX_TUPLE_COST   0.005

Definition at line 27 of file cost.h.

◆ DEFAULT_CPU_OPERATOR_COST

#define DEFAULT_CPU_OPERATOR_COST   0.0025

Definition at line 28 of file cost.h.

◆ DEFAULT_CPU_TUPLE_COST

#define DEFAULT_CPU_TUPLE_COST   0.01

Definition at line 26 of file cost.h.

◆ DEFAULT_EFFECTIVE_CACHE_SIZE

#define DEFAULT_EFFECTIVE_CACHE_SIZE   524288 /* measured in pages */

Definition at line 32 of file cost.h.

◆ DEFAULT_PARALLEL_SETUP_COST

#define DEFAULT_PARALLEL_SETUP_COST   1000.0

Definition at line 30 of file cost.h.

◆ DEFAULT_PARALLEL_TUPLE_COST

#define DEFAULT_PARALLEL_TUPLE_COST   0.1

Definition at line 29 of file cost.h.

◆ DEFAULT_RANDOM_PAGE_COST

#define DEFAULT_RANDOM_PAGE_COST   4.0

Definition at line 25 of file cost.h.

◆ DEFAULT_SEQ_PAGE_COST

#define DEFAULT_SEQ_PAGE_COST   1.0

Definition at line 24 of file cost.h.

Enumeration Type Documentation

◆ ConstraintExclusionType

Enumerator
CONSTRAINT_EXCLUSION_OFF 
CONSTRAINT_EXCLUSION_ON 
CONSTRAINT_EXCLUSION_PARTITION 

Definition at line 34 of file cost.h.

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

Function Documentation

◆ compute_bitmap_pages()

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

Definition at line 5732 of file costsize.c.

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

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

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

◆ compute_semi_anti_join_factors()

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

Definition at line 4371 of file costsize.c.

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

Referenced by add_paths_to_joinrel().

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

◆ cost_agg()

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

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

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

◆ cost_append()

void cost_append ( AppendPath path)

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

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

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

Referenced by bitmap_and_cost_est(), and create_bitmap_and_path().

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

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

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

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

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

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

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

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

◆ cost_bitmap_tree_node()

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

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

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

◆ cost_ctescan()

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

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

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

◆ cost_functionscan()

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

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

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

◆ cost_gather()

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

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

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

◆ cost_gather_merge()

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

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

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

◆ cost_group()

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

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

2575 {
2576  double output_tuples;
2577  Cost startup_cost;
2578  Cost total_cost;
2579 
2580  output_tuples = numGroups;
2581  startup_cost = input_startup_cost;
2582  total_cost = input_total_cost;
2583 
2584  /*
2585  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2586  * all columns get compared at most of the tuples.
2587  */
2588  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2589 
2590  /*
2591  * If there are quals (HAVING quals), account for their cost and
2592  * selectivity.
2593  */
2594  if (quals)
2595  {
2596  QualCost qual_cost;
2597 
2598  cost_qual_eval(&qual_cost, quals, root);
2599  startup_cost += qual_cost.startup;
2600  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2601 
2602  output_tuples = clamp_row_est(output_tuples *
2604  quals,
2605  0,
2606  JOIN_INNER,
2607  NULL));
2608  }
2609 
2610  path->rows = output_tuples;
2611  path->startup_cost = startup_cost;
2612  path->total_cost = total_cost;
2613 }
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4043
Cost startup_cost
Definition: pathnodes.h:1155
double cpu_operator_cost
Definition: costsize.c:115
Cost total_cost
Definition: pathnodes.h:1156
double rows
Definition: pathnodes.h:1154
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:69
double clamp_row_est(double nrows)
Definition: costsize.c:191
double Cost
Definition: nodes.h:663

◆ cost_incremental_sort()

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

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

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

◆ cost_index()

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

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

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

◆ cost_material()

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

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

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

◆ cost_merge_append()

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

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

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

◆ cost_namedtuplestorescan()

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

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

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

◆ cost_qual_eval()

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

Definition at line 4043 of file costsize.c.

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

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

4044 {
4045  cost_qual_eval_context context;
4046  ListCell *l;
4047 
4048  context.root = root;
4049  context.total.startup = 0;
4050  context.total.per_tuple = 0;
4051 
4052  /* We don't charge any cost for the implicit ANDing at top level ... */
4053 
4054  foreach(l, quals)
4055  {
4056  Node *qual = (Node *) lfirst(l);
4057 
4058  cost_qual_eval_walker(qual, &context);
4059  }
4060 
4061  *cost = context.total;
4062 }
PlannerInfo * root
Definition: costsize.c:148
Definition: nodes.h:529
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4083
#define lfirst(lc)
Definition: pg_list.h:190

◆ cost_qual_eval_node()

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

Definition at line 4069 of file costsize.c.

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

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

4070 {
4071  cost_qual_eval_context context;
4072 
4073  context.root = root;
4074  context.total.startup = 0;
4075  context.total.per_tuple = 0;
4076 
4077  cost_qual_eval_walker(qual, &context);
4078 
4079  *cost = context.total;
4080 }
PlannerInfo * root
Definition: costsize.c:148
Cost startup
Definition: pathnodes.h:45
Cost per_tuple
Definition: pathnodes.h:46
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4083

◆ cost_recursive_union()

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

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

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

◆ cost_resultscan()

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

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

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

◆ cost_samplescan()

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

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

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

◆ cost_seqscan()

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

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

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

◆ cost_sort()

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

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

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

◆ cost_subplan()

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

Definition at line 3843 of file costsize.c.

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

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

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

◆ cost_subqueryscan()

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

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

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

◆ cost_tablefuncscan()

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

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

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

◆ cost_tidscan()

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

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

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

◆ cost_valuesscan()

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

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

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

◆ cost_windowagg()

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

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

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

◆ final_cost_hashjoin()

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

Definition at line 3588 of file costsize.c.

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

Referenced by create_hashjoin_path().

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

◆ final_cost_mergejoin()

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

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

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

◆ final_cost_nestloop()

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

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

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

◆ get_parameterized_baserel_size()

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

Definition at line 4658 of file costsize.c.

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

Referenced by get_baserel_parampathinfo().

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

◆ get_parameterized_joinrel_size()

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

Definition at line 4739 of file costsize.c.

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

Referenced by get_joinrel_parampathinfo().

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

◆ index_pages_fetched()

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

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

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

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

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

◆ initial_cost_mergejoin()

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

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

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

◆ initial_cost_nestloop()

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

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

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

◆ set_baserel_size_estimates()

void set_baserel_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 4628 of file costsize.c.

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

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

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

◆ set_cte_size_estimates()

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

Definition at line 5308 of file costsize.c.

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

Referenced by set_cte_pathlist(), and set_worktable_pathlist().

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