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_RECURSIVE_WORKTABLE_FACTOR   10.0
 
#define DEFAULT_EFFECTIVE_CACHE_SIZE   524288 /* measured in pages */
 

Enumerations

enum  ConstraintExclusionType { CONSTRAINT_EXCLUSION_OFF , CONSTRAINT_EXCLUSION_ON , CONSTRAINT_EXCLUSION_PARTITION }
 

Functions

double index_pages_fetched (double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
 
void cost_seqscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_samplescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_index (IndexPath *path, PlannerInfo *root, double loop_count, bool partial_path)
 
void cost_bitmap_heap_scan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, Path *bitmapqual, double loop_count)
 
void cost_bitmap_and_node (BitmapAndPath *path, PlannerInfo *root)
 
void cost_bitmap_or_node (BitmapOrPath *path, PlannerInfo *root)
 
void cost_bitmap_tree_node (Path *path, Cost *cost, Selectivity *selec)
 
void cost_tidscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
 
void cost_tidrangescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidrangequals, ParamPathInfo *param_info)
 
void cost_subqueryscan (SubqueryScanPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, bool trivial_pathtarget)
 
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 *apath)
 
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, WindowClause *winclause, 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 *rel, ParamPathInfo *param_info, double *rows)
 
void cost_gather_merge (GatherMergePath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, Cost input_startup_cost, Cost input_total_cost, double *rows)
 
void cost_subplan (PlannerInfo *root, SubPlan *subplan, Plan *plan)
 
void cost_qual_eval (QualCost *cost, List *quals, PlannerInfo *root)
 
void cost_qual_eval_node (QualCost *cost, Node *qual, PlannerInfo *root)
 
void compute_semi_anti_join_factors (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, SpecialJoinInfo *sjinfo, List *restrictlist, SemiAntiJoinFactors *semifactors)
 
void set_baserel_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
double get_parameterized_baserel_size (PlannerInfo *root, RelOptInfo *rel, List *param_clauses)
 
double get_parameterized_joinrel_size (PlannerInfo *root, RelOptInfo *rel, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, List *restrict_clauses)
 
void set_joinrel_size_estimates (PlannerInfo *root, RelOptInfo *rel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo, List *restrictlist)
 
void set_subquery_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_function_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_values_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_cte_size_estimates (PlannerInfo *root, RelOptInfo *rel, double cte_rows)
 
void set_tablefunc_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_namedtuplestore_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_result_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_foreign_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
PathTargetset_pathtarget_cost_width (PlannerInfo *root, PathTarget *target)
 
double compute_bitmap_pages (PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
 

Variables

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

Macro Definition Documentation

◆ DEFAULT_CPU_INDEX_TUPLE_COST

#define DEFAULT_CPU_INDEX_TUPLE_COST   0.005

Definition at line 27 of file cost.h.

◆ DEFAULT_CPU_OPERATOR_COST

#define DEFAULT_CPU_OPERATOR_COST   0.0025

Definition at line 28 of file cost.h.

◆ DEFAULT_CPU_TUPLE_COST

#define DEFAULT_CPU_TUPLE_COST   0.01

Definition at line 26 of file cost.h.

◆ DEFAULT_EFFECTIVE_CACHE_SIZE

#define DEFAULT_EFFECTIVE_CACHE_SIZE   524288 /* measured in pages */

Definition at line 34 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_RECURSIVE_WORKTABLE_FACTOR

#define DEFAULT_RECURSIVE_WORKTABLE_FACTOR   10.0

Definition at line 33 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 36 of file cost.h.

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

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

6402 {
6403  Cost indexTotalCost;
6404  Selectivity indexSelectivity;
6405  double T;
6406  double pages_fetched;
6407  double tuples_fetched;
6408  double heap_pages;
6409  long maxentries;
6410 
6411  /*
6412  * Fetch total cost of obtaining the bitmap, as well as its total
6413  * selectivity.
6414  */
6415  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6416 
6417  /*
6418  * Estimate number of main-table pages fetched.
6419  */
6420  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6421 
6422  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
6423 
6424  /*
6425  * For a single scan, the number of heap pages that need to be fetched is
6426  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
6427  * re-reads needed).
6428  */
6429  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
6430 
6431  /*
6432  * Calculate the number of pages fetched from the heap. Then based on
6433  * current work_mem estimate get the estimated maxentries in the bitmap.
6434  * (Note that we always do this calculation based on the number of pages
6435  * that would be fetched in a single iteration, even if loop_count > 1.
6436  * That's correct, because only that number of entries will be stored in
6437  * the bitmap at one time.)
6438  */
6439  heap_pages = Min(pages_fetched, baserel->pages);
6440  maxentries = tbm_calculate_entries(work_mem * 1024L);
6441 
6442  if (loop_count > 1)
6443  {
6444  /*
6445  * For repeated bitmap scans, scale up the number of tuples fetched in
6446  * the Mackert and Lohman formula by the number of scans, so that we
6447  * estimate the number of pages fetched by all the scans. Then
6448  * pro-rate for one scan.
6449  */
6450  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6451  baserel->pages,
6452  get_indexpath_pages(bitmapqual),
6453  root);
6454  pages_fetched /= loop_count;
6455  }
6456 
6457  if (pages_fetched >= T)
6458  pages_fetched = T;
6459  else
6460  pages_fetched = ceil(pages_fetched);
6461 
6462  if (maxentries < heap_pages)
6463  {
6464  double exact_pages;
6465  double lossy_pages;
6466 
6467  /*
6468  * Crude approximation of the number of lossy pages. Because of the
6469  * way tbm_lossify() is coded, the number of lossy pages increases
6470  * very sharply as soon as we run short of memory; this formula has
6471  * that property and seems to perform adequately in testing, but it's
6472  * possible we could do better somehow.
6473  */
6474  lossy_pages = Max(0, heap_pages - maxentries / 2);
6475  exact_pages = heap_pages - lossy_pages;
6476 
6477  /*
6478  * If there are lossy pages then recompute the number of tuples
6479  * processed by the bitmap heap node. We assume here that the chance
6480  * of a given tuple coming from an exact page is the same as the
6481  * chance that a given page is exact. This might not be true, but
6482  * it's not clear how we can do any better.
6483  */
6484  if (lossy_pages > 0)
6485  tuples_fetched =
6486  clamp_row_est(indexSelectivity *
6487  (exact_pages / heap_pages) * baserel->tuples +
6488  (lossy_pages / heap_pages) * baserel->tuples);
6489  }
6490 
6491  if (cost)
6492  *cost = indexTotalCost;
6493  if (tuple)
6494  *tuple = tuples_fetched;
6495 
6496  return pages_fetched;
6497 }
#define Min(x, y)
Definition: c.h:993
#define Max(x, y)
Definition: c.h:987
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:870
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1086
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:935
double clamp_row_est(double nrows)
Definition: costsize.c:203
int work_mem
Definition: globals.c:127
static const uint32 T[65]
Definition: md5.c:119
double Cost
Definition: nodes.h:262
double Selectivity
Definition: nodes.h:261
Cardinality tuples
Definition: pathnodes.h:928
BlockNumber pages
Definition: pathnodes.h:927
long tbm_calculate_entries(double maxbytes)
Definition: tidbitmap.c:1545

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

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

4983 {
4984  Selectivity jselec;
4985  Selectivity nselec;
4986  Selectivity avgmatch;
4987  SpecialJoinInfo norm_sjinfo;
4988  List *joinquals;
4989  ListCell *l;
4990 
4991  /*
4992  * In an ANTI join, we must ignore clauses that are "pushed down", since
4993  * those won't affect the match logic. In a SEMI join, we do not
4994  * distinguish joinquals from "pushed down" quals, so just use the whole
4995  * restrictinfo list. For other outer join types, we should consider only
4996  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
4997  */
4998  if (IS_OUTER_JOIN(jointype))
4999  {
5000  joinquals = NIL;
5001  foreach(l, restrictlist)
5002  {
5003  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5004 
5005  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5006  joinquals = lappend(joinquals, rinfo);
5007  }
5008  }
5009  else
5010  joinquals = restrictlist;
5011 
5012  /*
5013  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
5014  */
5015  jselec = clauselist_selectivity(root,
5016  joinquals,
5017  0,
5018  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
5019  sjinfo);
5020 
5021  /*
5022  * Also get the normal inner-join selectivity of the join clauses.
5023  */
5024  norm_sjinfo.type = T_SpecialJoinInfo;
5025  norm_sjinfo.min_lefthand = outerrel->relids;
5026  norm_sjinfo.min_righthand = innerrel->relids;
5027  norm_sjinfo.syn_lefthand = outerrel->relids;
5028  norm_sjinfo.syn_righthand = innerrel->relids;
5029  norm_sjinfo.jointype = JOIN_INNER;
5030  norm_sjinfo.ojrelid = 0;
5031  norm_sjinfo.commute_above_l = NULL;
5032  norm_sjinfo.commute_above_r = NULL;
5033  norm_sjinfo.commute_below_l = NULL;
5034  norm_sjinfo.commute_below_r = NULL;
5035  /* we don't bother trying to make the remaining fields valid */
5036  norm_sjinfo.lhs_strict = false;
5037  norm_sjinfo.semi_can_btree = false;
5038  norm_sjinfo.semi_can_hash = false;
5039  norm_sjinfo.semi_operators = NIL;
5040  norm_sjinfo.semi_rhs_exprs = NIL;
5041 
5042  nselec = clauselist_selectivity(root,
5043  joinquals,
5044  0,
5045  JOIN_INNER,
5046  &norm_sjinfo);
5047 
5048  /* Avoid leaking a lot of ListCells */
5049  if (IS_OUTER_JOIN(jointype))
5050  list_free(joinquals);
5051 
5052  /*
5053  * jselec can be interpreted as the fraction of outer-rel rows that have
5054  * any matches (this is true for both SEMI and ANTI cases). And nselec is
5055  * the fraction of the Cartesian product that matches. So, the average
5056  * number of matches for each outer-rel row that has at least one match is
5057  * nselec * inner_rows / jselec.
5058  *
5059  * Note: it is correct to use the inner rel's "rows" count here, even
5060  * though we might later be considering a parameterized inner path with
5061  * fewer rows. This is because we have included all the join clauses in
5062  * the selectivity estimate.
5063  */
5064  if (jselec > 0) /* protect against zero divide */
5065  {
5066  avgmatch = nselec * innerrel->rows / jselec;
5067  /* Clamp to sane range */
5068  avgmatch = Max(1.0, avgmatch);
5069  }
5070  else
5071  avgmatch = 1.0;
5072 
5073  semifactors->outer_match_frac = jselec;
5074  semifactors->match_count = avgmatch;
5075 }
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:102
List * lappend(List *list, void *datum)
Definition: list.c:338
void list_free(List *list)
Definition: list.c:1545
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:348
@ JOIN_SEMI
Definition: nodes.h:318
@ JOIN_INNER
Definition: nodes.h:304
@ JOIN_ANTI
Definition: nodes.h:319
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2683
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define NIL
Definition: pg_list.h:68
Definition: pg_list.h:54
Relids relids
Definition: pathnodes.h:856
Cardinality rows
Definition: pathnodes.h:862
Selectivity outer_match_frac
Definition: pathnodes.h:3170
Selectivity match_count
Definition: pathnodes.h:3171
Relids commute_above_r
Definition: pathnodes.h:2860
Relids syn_lefthand
Definition: pathnodes.h:2855
Relids min_righthand
Definition: pathnodes.h:2854
List * semi_rhs_exprs
Definition: pathnodes.h:2868
Relids commute_above_l
Definition: pathnodes.h:2859
JoinType jointype
Definition: pathnodes.h:2857
Relids commute_below_l
Definition: pathnodes.h:2861
Relids min_lefthand
Definition: pathnodes.h:2853
Relids syn_righthand
Definition: pathnodes.h:2856
Relids commute_below_r
Definition: pathnodes.h:2862
List * semi_operators
Definition: pathnodes.h:2867

References clauselist_selectivity(), SpecialJoinInfo::commute_above_l, SpecialJoinInfo::commute_above_r, SpecialJoinInfo::commute_below_l, SpecialJoinInfo::commute_below_r, 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, SpecialJoinInfo::ojrelid, 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, and SpecialJoinInfo::syn_righthand.

Referenced by add_paths_to_joinrel().

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

2628 {
2629  double output_tuples;
2630  Cost startup_cost;
2631  Cost total_cost;
2632  AggClauseCosts dummy_aggcosts;
2633 
2634  /* Use all-zero per-aggregate costs if NULL is passed */
2635  if (aggcosts == NULL)
2636  {
2637  Assert(aggstrategy == AGG_HASHED);
2638  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
2639  aggcosts = &dummy_aggcosts;
2640  }
2641 
2642  /*
2643  * The transCost.per_tuple component of aggcosts should be charged once
2644  * per input tuple, corresponding to the costs of evaluating the aggregate
2645  * transfns and their input expressions. The finalCost.per_tuple component
2646  * is charged once per output tuple, corresponding to the costs of
2647  * evaluating the finalfns. Startup costs are of course charged but once.
2648  *
2649  * If we are grouping, we charge an additional cpu_operator_cost per
2650  * grouping column per input tuple for grouping comparisons.
2651  *
2652  * We will produce a single output tuple if not grouping, and a tuple per
2653  * group otherwise. We charge cpu_tuple_cost for each output tuple.
2654  *
2655  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2656  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2657  * input path is already sorted appropriately, AGG_SORTED should be
2658  * preferred (since it has no risk of memory overflow). This will happen
2659  * as long as the computed total costs are indeed exactly equal --- but if
2660  * there's roundoff error we might do the wrong thing. So be sure that
2661  * the computations below form the same intermediate values in the same
2662  * order.
2663  */
2664  if (aggstrategy == AGG_PLAIN)
2665  {
2666  startup_cost = input_total_cost;
2667  startup_cost += aggcosts->transCost.startup;
2668  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2669  startup_cost += aggcosts->finalCost.startup;
2670  startup_cost += aggcosts->finalCost.per_tuple;
2671  /* we aren't grouping */
2672  total_cost = startup_cost + cpu_tuple_cost;
2673  output_tuples = 1;
2674  }
2675  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2676  {
2677  /* Here we are able to deliver output on-the-fly */
2678  startup_cost = input_startup_cost;
2679  total_cost = input_total_cost;
2680  if (aggstrategy == AGG_MIXED && !enable_hashagg)
2681  {
2682  startup_cost += disable_cost;
2683  total_cost += disable_cost;
2684  }
2685  /* calcs phrased this way to match HASHED case, see note above */
2686  total_cost += aggcosts->transCost.startup;
2687  total_cost += aggcosts->transCost.per_tuple * input_tuples;
2688  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2689  total_cost += aggcosts->finalCost.startup;
2690  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2691  total_cost += cpu_tuple_cost * numGroups;
2692  output_tuples = numGroups;
2693  }
2694  else
2695  {
2696  /* must be AGG_HASHED */
2697  startup_cost = input_total_cost;
2698  if (!enable_hashagg)
2699  startup_cost += disable_cost;
2700  startup_cost += aggcosts->transCost.startup;
2701  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2702  /* cost of computing hash value */
2703  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2704  startup_cost += aggcosts->finalCost.startup;
2705 
2706  total_cost = startup_cost;
2707  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2708  /* cost of retrieving from hash table */
2709  total_cost += cpu_tuple_cost * numGroups;
2710  output_tuples = numGroups;
2711  }
2712 
2713  /*
2714  * Add the disk costs of hash aggregation that spills to disk.
2715  *
2716  * Groups that go into the hash table stay in memory until finalized, so
2717  * spilling and reprocessing tuples doesn't incur additional invocations
2718  * of transCost or finalCost. Furthermore, the computed hash value is
2719  * stored with the spilled tuples, so we don't incur extra invocations of
2720  * the hash function.
2721  *
2722  * Hash Agg begins returning tuples after the first batch is complete.
2723  * Accrue writes (spilled tuples) to startup_cost and to total_cost;
2724  * accrue reads only to total_cost.
2725  */
2726  if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
2727  {
2728  double pages;
2729  double pages_written = 0.0;
2730  double pages_read = 0.0;
2731  double spill_cost;
2732  double hashentrysize;
2733  double nbatches;
2734  Size mem_limit;
2735  uint64 ngroups_limit;
2736  int num_partitions;
2737  int depth;
2738 
2739  /*
2740  * Estimate number of batches based on the computed limits. If less
2741  * than or equal to one, all groups are expected to fit in memory;
2742  * otherwise we expect to spill.
2743  */
2744  hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
2745  input_width,
2746  aggcosts->transitionSpace);
2747  hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
2748  &ngroups_limit, &num_partitions);
2749 
2750  nbatches = Max((numGroups * hashentrysize) / mem_limit,
2751  numGroups / ngroups_limit);
2752 
2753  nbatches = Max(ceil(nbatches), 1.0);
2754  num_partitions = Max(num_partitions, 2);
2755 
2756  /*
2757  * The number of partitions can change at different levels of
2758  * recursion; but for the purposes of this calculation assume it stays
2759  * constant.
2760  */
2761  depth = ceil(log(nbatches) / log(num_partitions));
2762 
2763  /*
2764  * Estimate number of pages read and written. For each level of
2765  * recursion, a tuple must be written and then later read.
2766  */
2767  pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
2768  pages_written = pages_read = pages * depth;
2769 
2770  /*
2771  * HashAgg has somewhat worse IO behavior than Sort on typical
2772  * hardware/OS combinations. Account for this with a generic penalty.
2773  */
2774  pages_read *= 2.0;
2775  pages_written *= 2.0;
2776 
2777  startup_cost += pages_written * random_page_cost;
2778  total_cost += pages_written * random_page_cost;
2779  total_cost += pages_read * seq_page_cost;
2780 
2781  /* account for CPU cost of spilling a tuple and reading it back */
2782  spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
2783  startup_cost += spill_cost;
2784  total_cost += spill_cost;
2785  }
2786 
2787  /*
2788  * If there are quals (HAVING quals), account for their cost and
2789  * selectivity.
2790  */
2791  if (quals)
2792  {
2793  QualCost qual_cost;
2794 
2795  cost_qual_eval(&qual_cost, quals, root);
2796  startup_cost += qual_cost.startup;
2797  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2798 
2799  output_tuples = clamp_row_est(output_tuples *
2801  quals,
2802  0,
2803  JOIN_INNER,
2804  NULL));
2805  }
2806 
2807  path->rows = output_tuples;
2808  path->startup_cost = startup_cost;
2809  path->total_cost = total_cost;
2810 }
#define MemSet(start, val, len)
Definition: c.h:1009
size_t Size
Definition: c.h:594
double random_page_cost
Definition: costsize.c:121
double cpu_operator_cost
Definition: costsize.c:124
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:6346
double cpu_tuple_cost
Definition: costsize.c:122
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4612
double seq_page_cost
Definition: costsize.c:120
bool enable_hashagg
Definition: costsize.c:142
Cost disable_cost
Definition: costsize.c:131
Assert(fmt[strlen(fmt) - 1] !='\n')
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1695
void hash_agg_set_limits(double hashentrysize, double input_groups, int used_bits, Size *mem_limit, uint64 *ngroups_limit, int *num_partitions)
Definition: nodeAgg.c:1799
@ AGG_SORTED
Definition: nodes.h:365
@ AGG_HASHED
Definition: nodes.h:366
@ AGG_MIXED
Definition: nodes.h:367
@ AGG_PLAIN
Definition: nodes.h:364
static int list_length(const List *l)
Definition: pg_list.h:152
QualCost finalCost
Definition: pathnodes.h:61
Size transitionSpace
Definition: pathnodes.h:62
QualCost transCost
Definition: pathnodes.h:60
Cardinality rows
Definition: pathnodes.h:1628
Cost startup_cost
Definition: pathnodes.h:1629
Cost total_cost
Definition: pathnodes.h:1630
List * aggtransinfos
Definition: pathnodes.h:509
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47

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

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

◆ cost_append()

void cost_append ( AppendPath apath)

Definition at line 2203 of file costsize.c.

2204 {
2205  ListCell *l;
2206 
2207  apath->path.startup_cost = 0;
2208  apath->path.total_cost = 0;
2209  apath->path.rows = 0;
2210 
2211  if (apath->subpaths == NIL)
2212  return;
2213 
2214  if (!apath->path.parallel_aware)
2215  {
2216  List *pathkeys = apath->path.pathkeys;
2217 
2218  if (pathkeys == NIL)
2219  {
2220  Path *firstsubpath = (Path *) linitial(apath->subpaths);
2221 
2222  /*
2223  * For an unordered, non-parallel-aware Append we take the startup
2224  * cost as the startup cost of the first subpath.
2225  */
2226  apath->path.startup_cost = firstsubpath->startup_cost;
2227 
2228  /* Compute rows and costs as sums of subplan rows and costs. */
2229  foreach(l, apath->subpaths)
2230  {
2231  Path *subpath = (Path *) lfirst(l);
2232 
2233  apath->path.rows += subpath->rows;
2234  apath->path.total_cost += subpath->total_cost;
2235  }
2236  }
2237  else
2238  {
2239  /*
2240  * For an ordered, non-parallel-aware Append we take the startup
2241  * cost as the sum of the subpath startup costs. This ensures
2242  * that we don't underestimate the startup cost when a query's
2243  * LIMIT is such that several of the children have to be run to
2244  * satisfy it. This might be overkill --- another plausible hack
2245  * would be to take the Append's startup cost as the maximum of
2246  * the child startup costs. But we don't want to risk believing
2247  * that an ORDER BY LIMIT query can be satisfied at small cost
2248  * when the first child has small startup cost but later ones
2249  * don't. (If we had the ability to deal with nonlinear cost
2250  * interpolation for partial retrievals, we would not need to be
2251  * so conservative about this.)
2252  *
2253  * This case is also different from the above in that we have to
2254  * account for possibly injecting sorts into subpaths that aren't
2255  * natively ordered.
2256  */
2257  foreach(l, apath->subpaths)
2258  {
2259  Path *subpath = (Path *) lfirst(l);
2260  Path sort_path; /* dummy for result of cost_sort */
2261 
2262  if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
2263  {
2264  /*
2265  * We'll need to insert a Sort node, so include costs for
2266  * that. We can use the parent's LIMIT if any, since we
2267  * certainly won't pull more than that many tuples from
2268  * any child.
2269  */
2270  cost_sort(&sort_path,
2271  NULL, /* doesn't currently need root */
2272  pathkeys,
2273  subpath->total_cost,
2274  subpath->rows,
2275  subpath->pathtarget->width,
2276  0.0,
2277  work_mem,
2278  apath->limit_tuples);
2279  subpath = &sort_path;
2280  }
2281 
2282  apath->path.rows += subpath->rows;
2283  apath->path.startup_cost += subpath->startup_cost;
2284  apath->path.total_cost += subpath->total_cost;
2285  }
2286  }
2287  }
2288  else /* parallel-aware */
2289  {
2290  int i = 0;
2291  double parallel_divisor = get_parallel_divisor(&apath->path);
2292 
2293  /* Parallel-aware Append never produces ordered output. */
2294  Assert(apath->path.pathkeys == NIL);
2295 
2296  /* Calculate startup cost. */
2297  foreach(l, apath->subpaths)
2298  {
2299  Path *subpath = (Path *) lfirst(l);
2300 
2301  /*
2302  * Append will start returning tuples when the child node having
2303  * lowest startup cost is done setting up. We consider only the
2304  * first few subplans that immediately get a worker assigned.
2305  */
2306  if (i == 0)
2307  apath->path.startup_cost = subpath->startup_cost;
2308  else if (i < apath->path.parallel_workers)
2309  apath->path.startup_cost = Min(apath->path.startup_cost,
2310  subpath->startup_cost);
2311 
2312  /*
2313  * Apply parallel divisor to subpaths. Scale the number of rows
2314  * for each partial subpath based on the ratio of the parallel
2315  * divisor originally used for the subpath to the one we adopted.
2316  * Also add the cost of partial paths to the total cost, but
2317  * ignore non-partial paths for now.
2318  */
2319  if (i < apath->first_partial_path)
2320  apath->path.rows += subpath->rows / parallel_divisor;
2321  else
2322  {
2323  double subpath_parallel_divisor;
2324 
2325  subpath_parallel_divisor = get_parallel_divisor(subpath);
2326  apath->path.rows += subpath->rows * (subpath_parallel_divisor /
2327  parallel_divisor);
2328  apath->path.total_cost += subpath->total_cost;
2329  }
2330 
2331  apath->path.rows = clamp_row_est(apath->path.rows);
2332 
2333  i++;
2334  }
2335 
2336  /* Add cost for non-partial subpaths. */
2337  apath->path.total_cost +=
2339  apath->first_partial_path,
2340  apath->path.parallel_workers);
2341  }
2342 
2343  /*
2344  * Although Append does not do any selection or projection, it's not free;
2345  * add a small per-tuple overhead.
2346  */
2347  apath->path.total_cost +=
2349 }
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:110
static Cost append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
Definition: costsize.c:2127
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6367
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:2096
int i
Definition: isn.c:73
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:340
#define lfirst(lc)
Definition: pg_list.h:172
#define linitial(l)
Definition: pg_list.h:178
int first_partial_path
Definition: pathnodes.h:1902
Cardinality limit_tuples
Definition: pathnodes.h:1903
List * subpaths
Definition: pathnodes.h:1900
List * pathkeys
Definition: pathnodes.h:1633
int parallel_workers
Definition: pathnodes.h:1625
bool parallel_aware
Definition: pathnodes.h:1621

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::rows, Path::startup_cost, subpath(), AppendPath::subpaths, Path::total_cost, and work_mem.

Referenced by create_append_path().

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1129 of file costsize.c.

1130 {
1131  Cost totalCost;
1132  Selectivity selec;
1133  ListCell *l;
1134 
1135  /*
1136  * We estimate AND selectivity on the assumption that the inputs are
1137  * independent. This is probably often wrong, but we don't have the info
1138  * to do better.
1139  *
1140  * The runtime cost of the BitmapAnd itself is estimated at 100x
1141  * cpu_operator_cost for each tbm_intersect needed. Probably too small,
1142  * definitely too simplistic?
1143  */
1144  totalCost = 0.0;
1145  selec = 1.0;
1146  foreach(l, path->bitmapquals)
1147  {
1148  Path *subpath = (Path *) lfirst(l);
1149  Cost subCost;
1150  Selectivity subselec;
1151 
1152  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1153 
1154  selec *= subselec;
1155 
1156  totalCost += subCost;
1157  if (l != list_head(path->bitmapquals))
1158  totalCost += 100.0 * cpu_operator_cost;
1159  }
1160  path->bitmapselectivity = selec;
1161  path->path.rows = 0; /* per above, not used */
1162  path->path.startup_cost = totalCost;
1163  path->path.total_cost = totalCost;
1164 }
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
Selectivity bitmapselectivity
Definition: pathnodes.h:1766
List * bitmapquals
Definition: pathnodes.h:1765

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

Referenced by create_bitmap_and_path().

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

988 {
989  Cost startup_cost = 0;
990  Cost run_cost = 0;
991  Cost indexTotalCost;
992  QualCost qpqual_cost;
993  Cost cpu_per_tuple;
994  Cost cost_per_page;
995  Cost cpu_run_cost;
996  double tuples_fetched;
997  double pages_fetched;
998  double spc_seq_page_cost,
999  spc_random_page_cost;
1000  double T;
1001 
1002  /* Should only be applied to base relations */
1003  Assert(IsA(baserel, RelOptInfo));
1004  Assert(baserel->relid > 0);
1005  Assert(baserel->rtekind == RTE_RELATION);
1006 
1007  /* Mark the path with the correct row estimate */
1008  if (param_info)
1009  path->rows = param_info->ppi_rows;
1010  else
1011  path->rows = baserel->rows;
1012 
1013  if (!enable_bitmapscan)
1014  startup_cost += disable_cost;
1015 
1016  pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
1017  loop_count, &indexTotalCost,
1018  &tuples_fetched);
1019 
1020  startup_cost += indexTotalCost;
1021  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
1022 
1023  /* Fetch estimated page costs for tablespace containing table. */
1025  &spc_random_page_cost,
1026  &spc_seq_page_cost);
1027 
1028  /*
1029  * For small numbers of pages we should charge spc_random_page_cost
1030  * apiece, while if nearly all the table's pages are being read, it's more
1031  * appropriate to charge spc_seq_page_cost apiece. The effect is
1032  * nonlinear, too. For lack of a better idea, interpolate like this to
1033  * determine the cost per page.
1034  */
1035  if (pages_fetched >= 2.0)
1036  cost_per_page = spc_random_page_cost -
1037  (spc_random_page_cost - spc_seq_page_cost)
1038  * sqrt(pages_fetched / T);
1039  else
1040  cost_per_page = spc_random_page_cost;
1041 
1042  run_cost += pages_fetched * cost_per_page;
1043 
1044  /*
1045  * Estimate CPU costs per tuple.
1046  *
1047  * Often the indexquals don't need to be rechecked at each tuple ... but
1048  * not always, especially not if there are enough tuples involved that the
1049  * bitmaps become lossy. For the moment, just assume they will be
1050  * rechecked always. This means we charge the full freight for all the
1051  * scan clauses.
1052  */
1053  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1054 
1055  startup_cost += qpqual_cost.startup;
1056  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1057  cpu_run_cost = cpu_per_tuple * tuples_fetched;
1058 
1059  /* Adjust costing for parallelism, if used. */
1060  if (path->parallel_workers > 0)
1061  {
1062  double parallel_divisor = get_parallel_divisor(path);
1063 
1064  /* The CPU cost is divided among all the workers. */
1065  cpu_run_cost /= parallel_divisor;
1066 
1067  path->rows = clamp_row_est(path->rows / parallel_divisor);
1068  }
1069 
1070 
1071  run_cost += cpu_run_cost;
1072 
1073  /* tlist eval costs are paid per output row, not per tuple scanned */
1074  startup_cost += path->pathtarget->cost.startup;
1075  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1076 
1077  path->startup_cost = startup_cost;
1078  path->total_cost = startup_cost + run_cost;
1079 }
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:4933
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
Definition: costsize.c:6400
bool enable_bitmapscan
Definition: costsize.c:138
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
@ RTE_RELATION
Definition: parsenodes.h:1006
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Cardinality ppi_rows
Definition: pathnodes.h:1548
Index relid
Definition: pathnodes.h:903
Oid reltablespace
Definition: pathnodes.h:905
RTEKind rtekind
Definition: pathnodes.h:907

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

Referenced by bitmap_scan_cost_est(), and create_bitmap_heap_path().

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1173 of file costsize.c.

1174 {
1175  Cost totalCost;
1176  Selectivity selec;
1177  ListCell *l;
1178 
1179  /*
1180  * We estimate OR selectivity on the assumption that the inputs are
1181  * non-overlapping, since that's often the case in "x IN (list)" type
1182  * situations. Of course, we clamp to 1.0 at the end.
1183  *
1184  * The runtime cost of the BitmapOr itself is estimated at 100x
1185  * cpu_operator_cost for each tbm_union needed. Probably too small,
1186  * definitely too simplistic? We are aware that the tbm_unions are
1187  * optimized out when the inputs are BitmapIndexScans.
1188  */
1189  totalCost = 0.0;
1190  selec = 0.0;
1191  foreach(l, path->bitmapquals)
1192  {
1193  Path *subpath = (Path *) lfirst(l);
1194  Cost subCost;
1195  Selectivity subselec;
1196 
1197  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1198 
1199  selec += subselec;
1200 
1201  totalCost += subCost;
1202  if (l != list_head(path->bitmapquals) &&
1203  !IsA(subpath, IndexPath))
1204  totalCost += 100.0 * cpu_operator_cost;
1205  }
1206  path->bitmapselectivity = Min(selec, 1.0);
1207  path->path.rows = 0; /* per above, not used */
1208  path->path.startup_cost = totalCost;
1209  path->path.total_cost = totalCost;
1210 }
Selectivity bitmapselectivity
Definition: pathnodes.h:1779
List * bitmapquals
Definition: pathnodes.h:1778

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

◆ cost_bitmap_tree_node()

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

Definition at line 1086 of file costsize.c.

1087 {
1088  if (IsA(path, IndexPath))
1089  {
1090  *cost = ((IndexPath *) path)->indextotalcost;
1091  *selec = ((IndexPath *) path)->indexselectivity;
1092 
1093  /*
1094  * Charge a small amount per retrieved tuple to reflect the costs of
1095  * manipulating the bitmap. This is mostly to make sure that a bitmap
1096  * scan doesn't look to be the same cost as an indexscan to retrieve a
1097  * single tuple.
1098  */
1099  *cost += 0.1 * cpu_operator_cost * path->rows;
1100  }
1101  else if (IsA(path, BitmapAndPath))
1102  {
1103  *cost = path->total_cost;
1104  *selec = ((BitmapAndPath *) path)->bitmapselectivity;
1105  }
1106  else if (IsA(path, BitmapOrPath))
1107  {
1108  *cost = path->total_cost;
1109  *selec = ((BitmapOrPath *) path)->bitmapselectivity;
1110  }
1111  else
1112  {
1113  elog(ERROR, "unrecognized node type: %d", nodeTag(path));
1114  *cost = *selec = 0; /* keep compiler quiet */
1115  }
1116 }
#define ERROR
Definition: elog.h:39
#define nodeTag(nodeptr)
Definition: nodes.h:133

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

◆ cost_ctescan()

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

Definition at line 1670 of file costsize.c.

1672 {
1673  Cost startup_cost = 0;
1674  Cost run_cost = 0;
1675  QualCost qpqual_cost;
1676  Cost cpu_per_tuple;
1677 
1678  /* Should only be applied to base relations that are CTEs */
1679  Assert(baserel->relid > 0);
1680  Assert(baserel->rtekind == RTE_CTE);
1681 
1682  /* Mark the path with the correct row estimate */
1683  if (param_info)
1684  path->rows = param_info->ppi_rows;
1685  else
1686  path->rows = baserel->rows;
1687 
1688  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1689  cpu_per_tuple = cpu_tuple_cost;
1690 
1691  /* Add scanning CPU costs */
1692  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1693 
1694  startup_cost += qpqual_cost.startup;
1695  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1696  run_cost += cpu_per_tuple * baserel->tuples;
1697 
1698  /* tlist eval costs are paid per output row, not per tuple scanned */
1699  startup_cost += path->pathtarget->cost.startup;
1700  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1701 
1702  path->startup_cost = startup_cost;
1703  path->total_cost = startup_cost + run_cost;
1704 }
@ RTE_CTE
Definition: parsenodes.h:1012

References Assert(), cpu_tuple_cost, get_restriction_qual_cost(), 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().

◆ cost_functionscan()

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

Definition at line 1503 of file costsize.c.

1505 {
1506  Cost startup_cost = 0;
1507  Cost run_cost = 0;
1508  QualCost qpqual_cost;
1509  Cost cpu_per_tuple;
1510  RangeTblEntry *rte;
1511  QualCost exprcost;
1512 
1513  /* Should only be applied to base relations that are functions */
1514  Assert(baserel->relid > 0);
1515  rte = planner_rt_fetch(baserel->relid, root);
1516  Assert(rte->rtekind == RTE_FUNCTION);
1517 
1518  /* Mark the path with the correct row estimate */
1519  if (param_info)
1520  path->rows = param_info->ppi_rows;
1521  else
1522  path->rows = baserel->rows;
1523 
1524  /*
1525  * Estimate costs of executing the function expression(s).
1526  *
1527  * Currently, nodeFunctionscan.c always executes the functions to
1528  * completion before returning any rows, and caches the results in a
1529  * tuplestore. So the function eval cost is all startup cost, and per-row
1530  * costs are minimal.
1531  *
1532  * XXX in principle we ought to charge tuplestore spill costs if the
1533  * number of rows is large. However, given how phony our rowcount
1534  * estimates for functions tend to be, there's not a lot of point in that
1535  * refinement right now.
1536  */
1537  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1538 
1539  startup_cost += exprcost.startup + exprcost.per_tuple;
1540 
1541  /* Add scanning CPU costs */
1542  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1543 
1544  startup_cost += qpqual_cost.startup;
1545  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1546  run_cost += cpu_per_tuple * baserel->tuples;
1547 
1548  /* tlist eval costs are paid per output row, not per tuple scanned */
1549  startup_cost += path->pathtarget->cost.startup;
1550  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1551 
1552  path->startup_cost = startup_cost;
1553  path->total_cost = startup_cost + run_cost;
1554 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4638
@ RTE_FUNCTION
Definition: parsenodes.h:1009
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:555
Definition: nodes.h:129
List * functions
Definition: parsenodes.h:1140
RTEKind rtekind
Definition: parsenodes.h:1025

References Assert(), cost_qual_eval_node(), cpu_tuple_cost, RangeTblEntry::functions, get_restriction_qual_cost(), 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().

◆ cost_gather()

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

Definition at line 408 of file costsize.c.

411 {
412  Cost startup_cost = 0;
413  Cost run_cost = 0;
414 
415  /* Mark the path with the correct row estimate */
416  if (rows)
417  path->path.rows = *rows;
418  else if (param_info)
419  path->path.rows = param_info->ppi_rows;
420  else
421  path->path.rows = rel->rows;
422 
423  startup_cost = path->subpath->startup_cost;
424 
425  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
426 
427  /* Parallel setup and communication cost. */
428  startup_cost += parallel_setup_cost;
429  run_cost += parallel_tuple_cost * path->path.rows;
430 
431  path->path.startup_cost = startup_cost;
432  path->path.total_cost = (startup_cost + run_cost);
433 }
double parallel_setup_cost
Definition: costsize.c:126
double parallel_tuple_cost
Definition: costsize.c:125
Path * subpath
Definition: pathnodes.h:2010

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

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

450 {
451  Cost startup_cost = 0;
452  Cost run_cost = 0;
453  Cost comparison_cost;
454  double N;
455  double logN;
456 
457  /* Mark the path with the correct row estimate */
458  if (rows)
459  path->path.rows = *rows;
460  else if (param_info)
461  path->path.rows = param_info->ppi_rows;
462  else
463  path->path.rows = rel->rows;
464 
465  if (!enable_gathermerge)
466  startup_cost += disable_cost;
467 
468  /*
469  * Add one to the number of workers to account for the leader. This might
470  * be overgenerous since the leader will do less work than other workers
471  * in typical cases, but we'll go with it for now.
472  */
473  Assert(path->num_workers > 0);
474  N = (double) path->num_workers + 1;
475  logN = LOG2(N);
476 
477  /* Assumed cost per tuple comparison */
478  comparison_cost = 2.0 * cpu_operator_cost;
479 
480  /* Heap creation cost */
481  startup_cost += comparison_cost * N * logN;
482 
483  /* Per-tuple heap maintenance cost */
484  run_cost += path->path.rows * comparison_cost * logN;
485 
486  /* small cost for heap management, like cost_merge_append */
487  run_cost += cpu_operator_cost * path->path.rows;
488 
489  /*
490  * Parallel setup and communication cost. Since Gather Merge, unlike
491  * Gather, requires us to block until a tuple is available from every
492  * worker, we bump the IPC cost up a little bit as compared with Gather.
493  * For lack of a better idea, charge an extra 5%.
494  */
495  startup_cost += parallel_setup_cost;
496  run_cost += parallel_tuple_cost * path->path.rows * 1.05;
497 
498  path->path.startup_cost = startup_cost + input_startup_cost;
499  path->path.total_cost = (startup_cost + run_cost + input_total_cost);
500 }
#define LOG2(x)
Definition: costsize.c:103
bool enable_gathermerge
Definition: costsize.c:148

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

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

3140 {
3141  double output_tuples;
3142  Cost startup_cost;
3143  Cost total_cost;
3144 
3145  output_tuples = numGroups;
3146  startup_cost = input_startup_cost;
3147  total_cost = input_total_cost;
3148 
3149  /*
3150  * Charge one cpu_operator_cost per comparison per input tuple. We assume
3151  * all columns get compared at most of the tuples.
3152  */
3153  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
3154 
3155  /*
3156  * If there are quals (HAVING quals), account for their cost and
3157  * selectivity.
3158  */
3159  if (quals)
3160  {
3161  QualCost qual_cost;
3162 
3163  cost_qual_eval(&qual_cost, quals, root);
3164  startup_cost += qual_cost.startup;
3165  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
3166 
3167  output_tuples = clamp_row_est(output_tuples *
3169  quals,
3170  0,
3171  JOIN_INNER,
3172  NULL));
3173  }
3174 
3175  path->rows = output_tuples;
3176  path->startup_cost = startup_cost;
3177  path->total_cost = total_cost;
3178 }

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

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

1963 {
1964  Cost startup_cost,
1965  run_cost,
1966  input_run_cost = input_total_cost - input_startup_cost;
1967  double group_tuples,
1968  input_groups;
1969  Cost group_startup_cost,
1970  group_run_cost,
1971  group_input_run_cost;
1972  List *presortedExprs = NIL;
1973  ListCell *l;
1974  bool unknown_varno = false;
1975 
1976  Assert(presorted_keys > 0 && presorted_keys < list_length(pathkeys));
1977 
1978  /*
1979  * We want to be sure the cost of a sort is never estimated as zero, even
1980  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1981  */
1982  if (input_tuples < 2.0)
1983  input_tuples = 2.0;
1984 
1985  /* Default estimate of number of groups, capped to one group per row. */
1986  input_groups = Min(input_tuples, DEFAULT_NUM_DISTINCT);
1987 
1988  /*
1989  * Extract presorted keys as list of expressions.
1990  *
1991  * We need to be careful about Vars containing "varno 0" which might have
1992  * been introduced by generate_append_tlist, which would confuse
1993  * estimate_num_groups (in fact it'd fail for such expressions). See
1994  * recurse_set_operations which has to deal with the same issue.
1995  *
1996  * Unlike recurse_set_operations we can't access the original target list
1997  * here, and even if we could it's not very clear how useful would that be
1998  * for a set operation combining multiple tables. So we simply detect if
1999  * there are any expressions with "varno 0" and use the default
2000  * DEFAULT_NUM_DISTINCT in that case.
2001  *
2002  * We might also use either 1.0 (a single group) or input_tuples (each row
2003  * being a separate group), pretty much the worst and best case for
2004  * incremental sort. But those are extreme cases and using something in
2005  * between seems reasonable. Furthermore, generate_append_tlist is used
2006  * for set operations, which are likely to produce mostly unique output
2007  * anyway - from that standpoint the DEFAULT_NUM_DISTINCT is defensive
2008  * while maintaining lower startup cost.
2009  */
2010  foreach(l, pathkeys)
2011  {
2012  PathKey *key = (PathKey *) lfirst(l);
2013  EquivalenceMember *member = (EquivalenceMember *)
2014  linitial(key->pk_eclass->ec_members);
2015 
2016  /*
2017  * Check if the expression contains Var with "varno 0" so that we
2018  * don't call estimate_num_groups in that case.
2019  */
2020  if (bms_is_member(0, pull_varnos(root, (Node *) member->em_expr)))
2021  {
2022  unknown_varno = true;
2023  break;
2024  }
2025 
2026  /* expression not containing any Vars with "varno 0" */
2027  presortedExprs = lappend(presortedExprs, member->em_expr);
2028 
2029  if (foreach_current_index(l) + 1 >= presorted_keys)
2030  break;
2031  }
2032 
2033  /* Estimate the number of groups with equal presorted keys. */
2034  if (!unknown_varno)
2035  input_groups = estimate_num_groups(root, presortedExprs, input_tuples,
2036  NULL, NULL);
2037 
2038  group_tuples = input_tuples / input_groups;
2039  group_input_run_cost = input_run_cost / input_groups;
2040 
2041  /*
2042  * Estimate the average cost of sorting of one group where presorted keys
2043  * are equal.
2044  */
2045  cost_tuplesort(&group_startup_cost, &group_run_cost,
2046  group_tuples, width, comparison_cost, sort_mem,
2047  limit_tuples);
2048 
2049  /*
2050  * Startup cost of incremental sort is the startup cost of its first group
2051  * plus the cost of its input.
2052  */
2053  startup_cost = group_startup_cost + input_startup_cost +
2054  group_input_run_cost;
2055 
2056  /*
2057  * After we started producing tuples from the first group, the cost of
2058  * producing all the tuples is given by the cost to finish processing this
2059  * group, plus the total cost to process the remaining groups, plus the
2060  * remaining cost of input.
2061  */
2062  run_cost = group_run_cost + (group_run_cost + group_startup_cost) *
2063  (input_groups - 1) + group_input_run_cost * (input_groups - 1);
2064 
2065  /*
2066  * Incremental sort adds some overhead by itself. Firstly, it has to
2067  * detect the sort groups. This is roughly equal to one extra copy and
2068  * comparison per tuple.
2069  */
2070  run_cost += (cpu_tuple_cost + comparison_cost) * input_tuples;
2071 
2072  /*
2073  * Additionally, we charge double cpu_tuple_cost for each input group to
2074  * account for the tuplesort_reset that's performed after each group.
2075  */
2076  run_cost += 2.0 * cpu_tuple_cost * input_groups;
2077 
2078  path->rows = input_tuples;
2079  path->startup_cost = startup_cost;
2080  path->total_cost = startup_cost + run_cost;
2081 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:460
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:1856
#define foreach_current_index(cell)
Definition: pg_list.h:403
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition: selfuncs.c:3386
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:52
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:108

References Assert(), bms_is_member(), cost_tuplesort(), cpu_tuple_cost, DEFAULT_NUM_DISTINCT, EquivalenceMember::em_expr, estimate_num_groups(), foreach_current_index, sort-test::key, lappend(), lfirst, linitial, list_length(), Min, NIL, pull_varnos(), Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by create_incremental_sort_path().

◆ cost_index()

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

Definition at line 521 of file costsize.c.

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

References RelOptInfo::allvisfrac, Assert(), clamp_row_est(), compute_parallel_worker(), 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, Path::parallel_aware, Path::parallel_workers, IndexPath::path, Path::pathtype, QualCost::per_tuple, 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_index_path(), and reparameterize_path().

◆ cost_material()

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

Definition at line 2425 of file costsize.c.

2428 {
2429  Cost startup_cost = input_startup_cost;
2430  Cost run_cost = input_total_cost - input_startup_cost;
2431  double nbytes = relation_byte_size(tuples, width);
2432  long work_mem_bytes = work_mem * 1024L;
2433 
2434  path->rows = tuples;
2435 
2436  /*
2437  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2438  * reflect bookkeeping overhead. (This rate must be more than what
2439  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2440  * if it is exactly the same then there will be a cost tie between
2441  * nestloop with A outer, materialized B inner and nestloop with B outer,
2442  * materialized A inner. The extra cost ensures we'll prefer
2443  * materializing the smaller rel.) Note that this is normally a good deal
2444  * less than cpu_tuple_cost; which is OK because a Material plan node
2445  * doesn't do qual-checking or projection, so it's got less overhead than
2446  * most plan nodes.
2447  */
2448  run_cost += 2 * cpu_operator_cost * tuples;
2449 
2450  /*
2451  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2452  * This cost is assumed to be evenly spread through the plan run phase,
2453  * which isn't exactly accurate but our cost model doesn't allow for
2454  * nonuniform costs within the run phase.
2455  */
2456  if (nbytes > work_mem_bytes)
2457  {
2458  double npages = ceil(nbytes / BLCKSZ);
2459 
2460  run_cost += seq_page_cost * npages;
2461  }
2462 
2463  path->startup_cost = startup_cost;
2464  path->total_cost = startup_cost + run_cost;
2465 }

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

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

2380 {
2381  Cost startup_cost = 0;
2382  Cost run_cost = 0;
2383  Cost comparison_cost;
2384  double N;
2385  double logN;
2386 
2387  /*
2388  * Avoid log(0)...
2389  */
2390  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2391  logN = LOG2(N);
2392 
2393  /* Assumed cost per tuple comparison */
2394  comparison_cost = 2.0 * cpu_operator_cost;
2395 
2396  /* Heap creation cost */
2397  startup_cost += comparison_cost * N * logN;
2398 
2399  /* Per-tuple heap maintenance cost */
2400  run_cost += tuples * comparison_cost * logN;
2401 
2402  /*
2403  * Although MergeAppend does not do any selection or projection, it's not
2404  * free; add a small per-tuple overhead.
2405  */
2406  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2407 
2408  path->startup_cost = startup_cost + input_startup_cost;
2409  path->total_cost = startup_cost + run_cost + input_total_cost;
2410 }

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

◆ cost_namedtuplestorescan()

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

Definition at line 1711 of file costsize.c.

1713 {
1714  Cost startup_cost = 0;
1715  Cost run_cost = 0;
1716  QualCost qpqual_cost;
1717  Cost cpu_per_tuple;
1718 
1719  /* Should only be applied to base relations that are Tuplestores */
1720  Assert(baserel->relid > 0);
1721  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1722 
1723  /* Mark the path with the correct row estimate */
1724  if (param_info)
1725  path->rows = param_info->ppi_rows;
1726  else
1727  path->rows = baserel->rows;
1728 
1729  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1730  cpu_per_tuple = cpu_tuple_cost;
1731 
1732  /* Add scanning CPU costs */
1733  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1734 
1735  startup_cost += qpqual_cost.startup;
1736  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1737  run_cost += cpu_per_tuple * baserel->tuples;
1738 
1739  path->startup_cost = startup_cost;
1740  path->total_cost = startup_cost + run_cost;
1741 }
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1013

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

◆ cost_qual_eval()

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

Definition at line 4612 of file costsize.c.

4613 {
4614  cost_qual_eval_context context;
4615  ListCell *l;
4616 
4617  context.root = root;
4618  context.total.startup = 0;
4619  context.total.per_tuple = 0;
4620 
4621  /* We don't charge any cost for the implicit ANDing at top level ... */
4622 
4623  foreach(l, quals)
4624  {
4625  Node *qual = (Node *) lfirst(l);
4626 
4627  cost_qual_eval_walker(qual, &context);
4628  }
4629 
4630  *cost = context.total;
4631 }
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4652
PlannerInfo * root
Definition: costsize.c:159

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

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

◆ cost_qual_eval_node()

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

◆ cost_recursive_union()

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

Definition at line 1785 of file costsize.c.

1786 {
1787  Cost startup_cost;
1788  Cost total_cost;
1789  double total_rows;
1790 
1791  /* We probably have decent estimates for the non-recursive term */
1792  startup_cost = nrterm->startup_cost;
1793  total_cost = nrterm->total_cost;
1794  total_rows = nrterm->rows;
1795 
1796  /*
1797  * We arbitrarily assume that about 10 recursive iterations will be
1798  * needed, and that we've managed to get a good fix on the cost and output
1799  * size of each one of them. These are mighty shaky assumptions but it's
1800  * hard to see how to do better.
1801  */
1802  total_cost += 10 * rterm->total_cost;
1803  total_rows += 10 * rterm->rows;
1804 
1805  /*
1806  * Also charge cpu_tuple_cost per row to account for the costs of
1807  * manipulating the tuplestores. (We don't worry about possible
1808  * spill-to-disk costs.)
1809  */
1810  total_cost += cpu_tuple_cost * total_rows;
1811 
1812  runion->startup_cost = startup_cost;
1813  runion->total_cost = total_cost;
1814  runion->rows = total_rows;
1815  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1816  rterm->pathtarget->width);
1817 }

References cpu_tuple_cost, Max, Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by create_recursiveunion_path().

◆ cost_resultscan()

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

Definition at line 1748 of file costsize.c.

1750 {
1751  Cost startup_cost = 0;
1752  Cost run_cost = 0;
1753  QualCost qpqual_cost;
1754  Cost cpu_per_tuple;
1755 
1756  /* Should only be applied to RTE_RESULT base relations */
1757  Assert(baserel->relid > 0);
1758  Assert(baserel->rtekind == RTE_RESULT);
1759 
1760  /* Mark the path with the correct row estimate */
1761  if (param_info)
1762  path->rows = param_info->ppi_rows;
1763  else
1764  path->rows = baserel->rows;
1765 
1766  /* We charge qual cost plus cpu_tuple_cost */
1767  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1768 
1769  startup_cost += qpqual_cost.startup;
1770  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1771  run_cost += cpu_per_tuple * baserel->tuples;
1772 
1773  path->startup_cost = startup_cost;
1774  path->total_cost = startup_cost + run_cost;
1775 }
@ RTE_RESULT
Definition: parsenodes.h:1014

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

◆ cost_samplescan()

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

Definition at line 333 of file costsize.c.

335 {
336  Cost startup_cost = 0;
337  Cost run_cost = 0;
338  RangeTblEntry *rte;
339  TableSampleClause *tsc;
340  TsmRoutine *tsm;
341  double spc_seq_page_cost,
342  spc_random_page_cost,
343  spc_page_cost;
344  QualCost qpqual_cost;
345  Cost cpu_per_tuple;
346 
347  /* Should only be applied to base relations with tablesample clauses */
348  Assert(baserel->relid > 0);
349  rte = planner_rt_fetch(baserel->relid, root);
350  Assert(rte->rtekind == RTE_RELATION);
351  tsc = rte->tablesample;
352  Assert(tsc != NULL);
353  tsm = GetTsmRoutine(tsc->tsmhandler);
354 
355  /* Mark the path with the correct row estimate */
356  if (param_info)
357  path->rows = param_info->ppi_rows;
358  else
359  path->rows = baserel->rows;
360 
361  /* fetch estimated page cost for tablespace containing table */
363  &spc_random_page_cost,
364  &spc_seq_page_cost);
365 
366  /* if NextSampleBlock is used, assume random access, else sequential */
367  spc_page_cost = (tsm->NextSampleBlock != NULL) ?
368  spc_random_page_cost : spc_seq_page_cost;
369 
370  /*
371  * disk costs (recall that baserel->pages has already been set to the
372  * number of pages the sampling method will visit)
373  */
374  run_cost += spc_page_cost * baserel->pages;
375 
376  /*
377  * CPU costs (recall that baserel->tuples has already been set to the
378  * number of tuples the sampling method will select). Note that we ignore
379  * execution cost of the TABLESAMPLE parameter expressions; they will be
380  * evaluated only once per scan, and in most usages they'll likely be
381  * simple constants anyway. We also don't charge anything for the
382  * calculations the sampling method might do internally.
383  */
384  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
385 
386  startup_cost += qpqual_cost.startup;
387  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
388  run_cost += cpu_per_tuple * baserel->tuples;
389  /* tlist eval costs are paid per output row, not per tuple scanned */
390  startup_cost += path->pathtarget->cost.startup;
391  run_cost += path->pathtarget->cost.per_tuple * path->rows;
392 
393  path->startup_cost = startup_cost;
394  path->total_cost = startup_cost + run_cost;
395 }
struct TableSampleClause * tablesample
Definition: parsenodes.h:1067
NextSampleBlock_function NextSampleBlock
Definition: tsmapi.h:73
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27

References Assert(), cpu_tuple_cost, get_restriction_qual_cost(), get_tablespace_page_costs(), GetTsmRoutine(), TsmRoutine::NextSampleBlock, RelOptInfo::pages, 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().

◆ cost_seqscan()

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

Definition at line 256 of file costsize.c.

258 {
259  Cost startup_cost = 0;
260  Cost cpu_run_cost;
261  Cost disk_run_cost;
262  double spc_seq_page_cost;
263  QualCost qpqual_cost;
264  Cost cpu_per_tuple;
265 
266  /* Should only be applied to base relations */
267  Assert(baserel->relid > 0);
268  Assert(baserel->rtekind == RTE_RELATION);
269 
270  /* Mark the path with the correct row estimate */
271  if (param_info)
272  path->rows = param_info->ppi_rows;
273  else
274  path->rows = baserel->rows;
275 
276  if (!enable_seqscan)
277  startup_cost += disable_cost;
278 
279  /* fetch estimated page cost for tablespace containing table */
281  NULL,
282  &spc_seq_page_cost);
283 
284  /*
285  * disk costs
286  */
287  disk_run_cost = spc_seq_page_cost * baserel->pages;
288 
289  /* CPU costs */
290  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
291 
292  startup_cost += qpqual_cost.startup;
293  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
294  cpu_run_cost = cpu_per_tuple * baserel->tuples;
295  /* tlist eval costs are paid per output row, not per tuple scanned */
296  startup_cost += path->pathtarget->cost.startup;
297  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
298 
299  /* Adjust costing for parallelism, if used. */
300  if (path->parallel_workers > 0)
301  {
302  double parallel_divisor = get_parallel_divisor(path);
303 
304  /* The CPU cost is divided among all the workers. */
305  cpu_run_cost /= parallel_divisor;
306 
307  /*
308  * It may be possible to amortize some of the I/O cost, but probably
309  * not very much, because most operating systems already do aggressive
310  * prefetching. For now, we assume that the disk run cost can't be
311  * amortized at all.
312  */
313 
314  /*
315  * In the case of a parallel plan, the row count needs to represent
316  * the number of tuples processed per worker.
317  */
318  path->rows = clamp_row_est(path->rows / parallel_divisor);
319  }
320 
321  path->startup_cost = startup_cost;
322  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
323 }
bool enable_seqscan
Definition: costsize.c:135

References Assert(), clamp_row_est(), cpu_tuple_cost, disable_cost, enable_seqscan, get_parallel_divisor(), get_restriction_qual_cost(), get_tablespace_page_costs(), RelOptInfo::pages, Path::parallel_workers, 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().

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

2101 {
2102  Cost startup_cost;
2103  Cost run_cost;
2104 
2105  cost_tuplesort(&startup_cost, &run_cost,
2106  tuples, width,
2107  comparison_cost, sort_mem,
2108  limit_tuples);
2109 
2110  if (!enable_sort)
2111  startup_cost += disable_cost;
2112 
2113  startup_cost += input_cost;
2114 
2115  path->rows = tuples;
2116  path->startup_cost = startup_cost;
2117  path->total_cost = startup_cost + run_cost;
2118 }
bool enable_sort
Definition: costsize.c:140

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

◆ cost_subplan()

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

Definition at line 4407 of file costsize.c.

4408 {
4409  QualCost sp_cost;
4410 
4411  /* Figure any cost for evaluating the testexpr */
4412  cost_qual_eval(&sp_cost,
4413  make_ands_implicit((Expr *) subplan->testexpr),
4414  root);
4415 
4416  if (subplan->useHashTable)
4417  {
4418  /*
4419  * If we are using a hash table for the subquery outputs, then the
4420  * cost of evaluating the query is a one-time cost. We charge one
4421  * cpu_operator_cost per tuple for the work of loading the hashtable,
4422  * too.
4423  */
4424  sp_cost.startup += plan->total_cost +
4425  cpu_operator_cost * plan->plan_rows;
4426 
4427  /*
4428  * The per-tuple costs include the cost of evaluating the lefthand
4429  * expressions, plus the cost of probing the hashtable. We already
4430  * accounted for the lefthand expressions as part of the testexpr, and
4431  * will also have counted one cpu_operator_cost for each comparison
4432  * operator. That is probably too low for the probing cost, but it's
4433  * hard to make a better estimate, so live with it for now.
4434  */
4435  }
4436  else
4437  {
4438  /*
4439  * Otherwise we will be rescanning the subplan output on each
4440  * evaluation. We need to estimate how much of the output we will
4441  * actually need to scan. NOTE: this logic should agree with the
4442  * tuple_fraction estimates used by make_subplan() in
4443  * plan/subselect.c.
4444  */
4445  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4446 
4447  if (subplan->subLinkType == EXISTS_SUBLINK)
4448  {
4449  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4450  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4451  }
4452  else if (subplan->subLinkType == ALL_SUBLINK ||
4453  subplan->subLinkType == ANY_SUBLINK)
4454  {
4455  /* assume we need 50% of the tuples */
4456  sp_cost.per_tuple += 0.50 * plan_run_cost;
4457  /* also charge a cpu_operator_cost per row examined */
4458  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4459  }
4460  else
4461  {
4462  /* assume we need all tuples */
4463  sp_cost.per_tuple += plan_run_cost;
4464  }
4465 
4466  /*
4467  * Also account for subplan's startup cost. If the subplan is
4468  * uncorrelated or undirect correlated, AND its topmost node is one
4469  * that materializes its output, assume that we'll only need to pay
4470  * its startup cost once; otherwise assume we pay the startup cost
4471  * every time.
4472  */
4473  if (subplan->parParam == NIL &&
4475  sp_cost.startup += plan->startup_cost;
4476  else
4477  sp_cost.per_tuple += plan->startup_cost;
4478  }
4479 
4480  subplan->startup_cost = sp_cost.startup;
4481  subplan->per_call_cost = sp_cost.per_tuple;
4482 }
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:637
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:722
#define plan(x)
Definition: pg_regress.c:162
@ ANY_SUBLINK
Definition: primnodes.h:934
@ ALL_SUBLINK
Definition: primnodes.h:933
@ EXISTS_SUBLINK
Definition: primnodes.h:932
bool useHashTable
Definition: primnodes.h:1014
Node * testexpr
Definition: primnodes.h:1002
List * parParam
Definition: primnodes.h:1025
Cost startup_cost
Definition: primnodes.h:1028
Cost per_call_cost
Definition: primnodes.h:1029
SubLinkType subLinkType
Definition: primnodes.h:1000

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, QualCost::startup, SubPlan::startup_cost, SubPlan::subLinkType, SubPlan::testexpr, and SubPlan::useHashTable.

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

◆ cost_subqueryscan()

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

Definition at line 1423 of file costsize.c.

1426 {
1427  Cost startup_cost;
1428  Cost run_cost;
1429  List *qpquals;
1430  QualCost qpqual_cost;
1431  Cost cpu_per_tuple;
1432 
1433  /* Should only be applied to base relations that are subqueries */
1434  Assert(baserel->relid > 0);
1435  Assert(baserel->rtekind == RTE_SUBQUERY);
1436 
1437  /*
1438  * We compute the rowcount estimate as the subplan's estimate times the
1439  * selectivity of relevant restriction clauses. In simple cases this will
1440  * come out the same as baserel->rows; but when dealing with parallelized
1441  * paths we must do it like this to get the right answer.
1442  */
1443  if (param_info)
1444  qpquals = list_concat_copy(param_info->ppi_clauses,
1445  baserel->baserestrictinfo);
1446  else
1447  qpquals = baserel->baserestrictinfo;
1448 
1449  path->path.rows = clamp_row_est(path->subpath->rows *
1451  qpquals,
1452  0,
1453  JOIN_INNER,
1454  NULL));
1455 
1456  /*
1457  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1458  * any restriction clauses and tlist that will be attached to the
1459  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1460  * projection overhead.
1461  */
1462  path->path.startup_cost = path->subpath->startup_cost;
1463  path->path.total_cost = path->subpath->total_cost;
1464 
1465  /*
1466  * However, if there are no relevant restriction clauses and the
1467  * pathtarget is trivial, then we expect that setrefs.c will optimize away
1468  * the SubqueryScan plan node altogether, so we should just make its cost
1469  * and rowcount equal to the input path's.
1470  *
1471  * Note: there are some edge cases where createplan.c will apply a
1472  * different targetlist to the SubqueryScan node, thus falsifying our
1473  * current estimate of whether the target is trivial, and making the cost
1474  * estimate (though not the rowcount) wrong. It does not seem worth the
1475  * extra complication to try to account for that exactly, especially since
1476  * that behavior falsifies other cost estimates as well.
1477  */
1478  if (qpquals == NIL && trivial_pathtarget)
1479  return;
1480 
1481  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1482 
1483  startup_cost = qpqual_cost.startup;
1484  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1485  run_cost = cpu_per_tuple * path->subpath->rows;
1486 
1487  /* tlist eval costs are paid per output row, not per tuple scanned */
1488  startup_cost += path->path.pathtarget->cost.startup;
1489  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1490 
1491  path->path.startup_cost += startup_cost;
1492  path->path.total_cost += startup_cost + run_cost;
1493 }
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:597
@ RTE_SUBQUERY
Definition: parsenodes.h:1007
List * ppi_clauses
Definition: pathnodes.h:1549
List * baserestrictinfo
Definition: pathnodes.h:964

References Assert(), RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), cpu_tuple_cost, get_restriction_qual_cost(), JOIN_INNER, list_concat_copy(), NIL, SubqueryScanPath::path, QualCost::per_tuple, ParamPathInfo::ppi_clauses, RelOptInfo::relid, Path::rows, RTE_SUBQUERY, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, SubqueryScanPath::subpath, and Path::total_cost.

Referenced by create_subqueryscan_path().

◆ cost_tablefuncscan()

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

Definition at line 1564 of file costsize.c.

1566 {
1567  Cost startup_cost = 0;
1568  Cost run_cost = 0;
1569  QualCost qpqual_cost;
1570  Cost cpu_per_tuple;
1571  RangeTblEntry *rte;
1572  QualCost exprcost;
1573 
1574  /* Should only be applied to base relations that are functions */
1575  Assert(baserel->relid > 0);
1576  rte = planner_rt_fetch(baserel->relid, root);
1577  Assert(rte->rtekind == RTE_TABLEFUNC);
1578 
1579  /* Mark the path with the correct row estimate */
1580  if (param_info)
1581  path->rows = param_info->ppi_rows;
1582  else
1583  path->rows = baserel->rows;
1584 
1585  /*
1586  * Estimate costs of executing the table func expression(s).
1587  *
1588  * XXX in principle we ought to charge tuplestore spill costs if the
1589  * number of rows is large. However, given how phony our rowcount
1590  * estimates for tablefuncs tend to be, there's not a lot of point in that
1591  * refinement right now.
1592  */
1593  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1594 
1595  startup_cost += exprcost.startup + exprcost.per_tuple;
1596 
1597  /* Add scanning CPU costs */
1598  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1599 
1600  startup_cost += qpqual_cost.startup;
1601  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1602  run_cost += cpu_per_tuple * baserel->tuples;
1603 
1604  /* tlist eval costs are paid per output row, not per tuple scanned */
1605  startup_cost += path->pathtarget->cost.startup;
1606  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1607 
1608  path->startup_cost = startup_cost;
1609  path->total_cost = startup_cost + run_cost;
1610 }
@ RTE_TABLEFUNC
Definition: parsenodes.h:1010
TableFunc * tablefunc
Definition: parsenodes.h:1146

References Assert(), cost_qual_eval_node(), cpu_tuple_cost, get_restriction_qual_cost(), 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().

◆ cost_tidrangescan()

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

Definition at line 1329 of file costsize.c.

1332 {
1333  Selectivity selectivity;
1334  double pages;
1335  Cost startup_cost = 0;
1336  Cost run_cost = 0;
1337  QualCost qpqual_cost;
1338  Cost cpu_per_tuple;
1339  QualCost tid_qual_cost;
1340  double ntuples;
1341  double nseqpages;
1342  double spc_random_page_cost;
1343  double spc_seq_page_cost;
1344 
1345  /* Should only be applied to base relations */
1346  Assert(baserel->relid > 0);
1347  Assert(baserel->rtekind == RTE_RELATION);
1348 
1349  /* Mark the path with the correct row estimate */
1350  if (param_info)
1351  path->rows = param_info->ppi_rows;
1352  else
1353  path->rows = baserel->rows;
1354 
1355  /* Count how many tuples and pages we expect to scan */
1356  selectivity = clauselist_selectivity(root, tidrangequals, baserel->relid,
1357  JOIN_INNER, NULL);
1358  pages = ceil(selectivity * baserel->pages);
1359 
1360  if (pages <= 0.0)
1361  pages = 1.0;
1362 
1363  /*
1364  * The first page in a range requires a random seek, but each subsequent
1365  * page is just a normal sequential page read. NOTE: it's desirable for
1366  * TID Range Scans to cost more than the equivalent Sequential Scans,
1367  * because Seq Scans have some performance advantages such as scan
1368  * synchronization and parallelizability, and we'd prefer one of them to
1369  * be picked unless a TID Range Scan really is better.
1370  */
1371  ntuples = selectivity * baserel->tuples;
1372  nseqpages = pages - 1.0;
1373 
1374  if (!enable_tidscan)
1375  startup_cost += disable_cost;
1376 
1377  /*
1378  * The TID qual expressions will be computed once, any other baserestrict
1379  * quals once per retrieved tuple.
1380  */
1381  cost_qual_eval(&tid_qual_cost, tidrangequals, root);
1382 
1383  /* fetch estimated page cost for tablespace containing table */
1385  &spc_random_page_cost,
1386  &spc_seq_page_cost);
1387 
1388  /* disk costs; 1 random page and the remainder as seq pages */
1389  run_cost += spc_random_page_cost + spc_seq_page_cost * nseqpages;
1390 
1391  /* Add scanning CPU costs */
1392  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1393 
1394  /*
1395  * XXX currently we assume TID quals are a subset of qpquals at this
1396  * point; they will be removed (if possible) when we create the plan, so
1397  * we subtract their cost from the total qpqual cost. (If the TID quals
1398  * can't be removed, this is a mistake and we're going to underestimate
1399  * the CPU cost a bit.)
1400  */
1401  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1402  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1403  tid_qual_cost.per_tuple;
1404  run_cost += cpu_per_tuple * ntuples;
1405 
1406  /* tlist eval costs are paid per output row, not per tuple scanned */
1407  startup_cost += path->pathtarget->cost.startup;
1408  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1409 
1410  path->startup_cost = startup_cost;
1411  path->total_cost = startup_cost + run_cost;
1412 }
bool enable_tidscan
Definition: costsize.c:139

References Assert(), clauselist_selectivity(), cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_tidscan, get_restriction_qual_cost(), get_tablespace_page_costs(), JOIN_INNER, RelOptInfo::pages, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_tidrangescan_path().

◆ cost_tidscan()

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

Definition at line 1221 of file costsize.c.

1223 {
1224  Cost startup_cost = 0;
1225  Cost run_cost = 0;
1226  bool isCurrentOf = false;
1227  QualCost qpqual_cost;
1228  Cost cpu_per_tuple;
1229  QualCost tid_qual_cost;
1230  int ntuples;
1231  ListCell *l;
1232  double spc_random_page_cost;
1233 
1234  /* Should only be applied to base relations */
1235  Assert(baserel->relid > 0);
1236  Assert(baserel->rtekind == RTE_RELATION);
1237 
1238  /* Mark the path with the correct row estimate */
1239  if (param_info)
1240  path->rows = param_info->ppi_rows;
1241  else
1242  path->rows = baserel->rows;
1243 
1244  /* Count how many tuples we expect to retrieve */
1245  ntuples = 0;
1246  foreach(l, tidquals)
1247  {
1248  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
1249  Expr *qual = rinfo->clause;
1250 
1251  if (IsA(qual, ScalarArrayOpExpr))
1252  {
1253  /* Each element of the array yields 1 tuple */
1254  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) qual;
1255  Node *arraynode = (Node *) lsecond(saop->args);
1256 
1257  ntuples += estimate_array_length(arraynode);
1258  }
1259  else if (IsA(qual, CurrentOfExpr))
1260  {
1261  /* CURRENT OF yields 1 tuple */
1262  isCurrentOf = true;
1263  ntuples++;
1264  }
1265  else
1266  {
1267  /* It's just CTID = something, count 1 tuple */
1268  ntuples++;
1269  }
1270  }
1271 
1272  /*
1273  * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
1274  * understands how to do it correctly. Therefore, honor enable_tidscan
1275  * only when CURRENT OF isn't present. Also note that cost_qual_eval
1276  * counts a CurrentOfExpr as having startup cost disable_cost, which we
1277  * subtract off here; that's to prevent other plan types such as seqscan
1278  * from winning.
1279  */
1280  if (isCurrentOf)
1281  {
1283  startup_cost -= disable_cost;
1284  }
1285  else if (!enable_tidscan)
1286  startup_cost += disable_cost;
1287 
1288  /*
1289  * The TID qual expressions will be computed once, any other baserestrict
1290  * quals once per retrieved tuple.
1291  */
1292  cost_qual_eval(&tid_qual_cost, tidquals, root);
1293 
1294  /* fetch estimated page cost for tablespace containing table */
1296  &spc_random_page_cost,
1297  NULL);
1298 
1299  /* disk costs --- assume each tuple on a different page */
1300  run_cost += spc_random_page_cost * ntuples;
1301 
1302  /* Add scanning CPU costs */
1303  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1304 
1305  /* XXX currently we assume TID quals are a subset of qpquals */
1306  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1307  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1308  tid_qual_cost.per_tuple;
1309  run_cost += cpu_per_tuple * ntuples;
1310 
1311  /* tlist eval costs are paid per output row, not per tuple scanned */
1312  startup_cost += path->pathtarget->cost.startup;
1313  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1314 
1315  path->startup_cost = startup_cost;
1316  path->total_cost = startup_cost + run_cost;
1317 }
#define lsecond(l)
Definition: pg_list.h:183
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2134
QualCost baserestrictcost
Definition: pathnodes.h:966
Expr * clause
Definition: pathnodes.h:2529

References ScalarArrayOpExpr::args, Assert(), RelOptInfo::baserestrictcost, RestrictInfo::clause, 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, 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().

◆ cost_valuesscan()

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

Definition at line 1620 of file costsize.c.

1622 {
1623  Cost startup_cost = 0;
1624  Cost run_cost = 0;
1625  QualCost qpqual_cost;
1626  Cost cpu_per_tuple;
1627 
1628  /* Should only be applied to base relations that are values lists */
1629  Assert(baserel->relid > 0);
1630  Assert(baserel->rtekind == RTE_VALUES);
1631 
1632  /* Mark the path with the correct row estimate */
1633  if (param_info)
1634  path->rows = param_info->ppi_rows;
1635  else
1636  path->rows = baserel->rows;
1637 
1638  /*
1639  * For now, estimate list evaluation cost at one operator eval per list
1640  * (probably pretty bogus, but is it worth being smarter?)
1641  */
1642  cpu_per_tuple = cpu_operator_cost;
1643 
1644  /* Add scanning CPU costs */
1645  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1646 
1647  startup_cost += qpqual_cost.startup;
1648  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1649  run_cost += cpu_per_tuple * baserel->tuples;
1650 
1651  /* tlist eval costs are paid per output row, not per tuple scanned */
1652  startup_cost += path->pathtarget->cost.startup;
1653  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1654 
1655  path->startup_cost = startup_cost;
1656  path->total_cost = startup_cost + run_cost;
1657 }
@ RTE_VALUES
Definition: parsenodes.h:1011

References Assert(), cpu_operator_cost, cpu_tuple_cost, get_restriction_qual_cost(), 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().

◆ cost_windowagg()

void cost_windowagg ( Path path,
PlannerInfo root,
List windowFuncs,
WindowClause winclause,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples 
)

Definition at line 3040 of file costsize.c.

3044 {
3045  Cost startup_cost;
3046  Cost total_cost;
3047  double startup_tuples;
3048  int numPartCols;
3049  int numOrderCols;
3050  ListCell *lc;
3051 
3052  numPartCols = list_length(winclause->partitionClause);
3053  numOrderCols = list_length(winclause->orderClause);
3054 
3055  startup_cost = input_startup_cost;
3056  total_cost = input_total_cost;
3057 
3058  /*
3059  * Window functions are assumed to cost their stated execution cost, plus
3060  * the cost of evaluating their input expressions, per tuple. Since they
3061  * may in fact evaluate their inputs at multiple rows during each cycle,
3062  * this could be a drastic underestimate; but without a way to know how
3063  * many rows the window function will fetch, it's hard to do better. In
3064  * any case, it's a good estimate for all the built-in window functions,
3065  * so we'll just do this for now.
3066  */
3067  foreach(lc, windowFuncs)
3068  {
3069  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
3070  Cost wfunccost;
3071  QualCost argcosts;
3072 
3073  argcosts.startup = argcosts.per_tuple = 0;
3074  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
3075  &argcosts);
3076  startup_cost += argcosts.startup;
3077  wfunccost = argcosts.per_tuple;
3078 
3079  /* also add the input expressions' cost to per-input-row costs */
3080  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
3081  startup_cost += argcosts.startup;
3082  wfunccost += argcosts.per_tuple;
3083 
3084  /*
3085  * Add the filter's cost to per-input-row costs. XXX We should reduce
3086  * input expression costs according to filter selectivity.
3087  */
3088  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
3089  startup_cost += argcosts.startup;
3090  wfunccost += argcosts.per_tuple;
3091 
3092  total_cost += wfunccost * input_tuples;
3093  }
3094 
3095  /*
3096  * We also charge cpu_operator_cost per grouping column per tuple for
3097  * grouping comparisons, plus cpu_tuple_cost per tuple for general
3098  * overhead.
3099  *
3100  * XXX this neglects costs of spooling the data to disk when it overflows
3101  * work_mem. Sooner or later that should get accounted for.
3102  */
3103  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
3104  total_cost += cpu_tuple_cost * input_tuples;
3105 
3106  path->rows = input_tuples;
3107  path->startup_cost = startup_cost;
3108  path->total_cost = total_cost;
3109 
3110  /*
3111  * Also, take into account how many tuples we need to read from the
3112  * subnode in order to produce the first tuple from the WindowAgg. To do
3113  * this we proportion the run cost (total cost not including startup cost)
3114  * over the estimated startup tuples. We already included the startup
3115  * cost of the subnode, so we only need to do this when the estimated
3116  * startup tuples is above 1.0.
3117  */
3118  startup_tuples = get_windowclause_startup_tuples(root, winclause,
3119  input_tuples);
3120 
3121  if (startup_tuples > 1.0)
3122  path->startup_cost += (total_cost - startup_cost) / input_tuples *
3123  (startup_tuples - 1.0);
3124 }
static double get_windowclause_startup_tuples(PlannerInfo *root, WindowClause *wc, double input_tuples)
Definition: costsize.c:2826
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:2044
List * partitionClause
Definition: parsenodes.h:1489
List * orderClause
Definition: parsenodes.h:1491
List * args
Definition: primnodes.h:561
Expr * aggfilter
Definition: primnodes.h:563
Oid winfnoid
Definition: primnodes.h:553

References add_function_cost(), WindowFunc::aggfilter, WindowFunc::args, cost_qual_eval_node(), cpu_operator_cost, cpu_tuple_cost, get_windowclause_startup_tuples(), lfirst_node, list_length(), WindowClause::orderClause, WindowClause::partitionClause, QualCost::per_tuple, Path::rows, QualCost::startup, Path::startup_cost, Path::total_cost, and WindowFunc::winfnoid.

Referenced by create_windowagg_path().

◆ final_cost_hashjoin()

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

Definition at line 4153 of file costsize.c.

4156 {
4157  Path *outer_path = path->jpath.outerjoinpath;
4158  Path *inner_path = path->jpath.innerjoinpath;
4159  double outer_path_rows = outer_path->rows;
4160  double inner_path_rows = inner_path->rows;
4161  double inner_path_rows_total = workspace->inner_rows_total;
4162  List *hashclauses = path->path_hashclauses;
4163  Cost startup_cost = workspace->startup_cost;
4164  Cost run_cost = workspace->run_cost;
4165  int numbuckets = workspace->numbuckets;
4166  int numbatches = workspace->numbatches;
4167  Cost cpu_per_tuple;
4168  QualCost hash_qual_cost;
4169  QualCost qp_qual_cost;
4170  double hashjointuples;
4171  double virtualbuckets;
4172  Selectivity innerbucketsize;
4173  Selectivity innermcvfreq;
4174  ListCell *hcl;
4175 
4176  /* Mark the path with the correct row estimate */
4177  if (path->jpath.path.param_info)
4178  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
4179  else
4180  path->jpath.path.rows = path->jpath.path.parent->rows;
4181 
4182  /* For partial paths, scale row estimate. */
4183  if (path->jpath.path.parallel_workers > 0)
4184  {
4185  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
4186 
4187  path->jpath.path.rows =
4188  clamp_row_est(path->jpath.path.rows / parallel_divisor);
4189  }
4190 
4191  /*
4192  * We could include disable_cost in the preliminary estimate, but that
4193  * would amount to optimizing for the case where the join method is
4194  * disabled, which doesn't seem like the way to bet.
4195  */
4196  if (!enable_hashjoin)
4197  startup_cost += disable_cost;
4198 
4199  /* mark the path with estimated # of batches */
4200  path->num_batches = numbatches;
4201 
4202  /* store the total number of tuples (sum of partial row estimates) */
4203  path->inner_rows_total = inner_path_rows_total;
4204 
4205  /* and compute the number of "virtual" buckets in the whole join */
4206  virtualbuckets = (double) numbuckets * (double) numbatches;
4207 
4208  /*
4209  * Determine bucketsize fraction and MCV frequency for the inner relation.
4210  * We use the smallest bucketsize or MCV frequency estimated for any
4211  * individual hashclause; this is undoubtedly conservative.
4212  *
4213  * BUT: if inner relation has been unique-ified, we can assume it's good
4214  * for hashing. This is important both because it's the right answer, and
4215  * because we avoid contaminating the cache with a value that's wrong for
4216  * non-unique-ified paths.
4217  */
4218  if (IsA(inner_path, UniquePath))
4219  {
4220  innerbucketsize = 1.0 / virtualbuckets;
4221  innermcvfreq = 0.0;
4222  }
4223  else
4224  {
4225  innerbucketsize = 1.0;
4226  innermcvfreq = 1.0;
4227  foreach(hcl, hashclauses)
4228  {
4229  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
4230  Selectivity thisbucketsize;
4231  Selectivity thismcvfreq;
4232 
4233  /*
4234  * First we have to figure out which side of the hashjoin clause
4235  * is the inner side.
4236  *
4237  * Since we tend to visit the same clauses over and over when
4238  * planning a large query, we cache the bucket stats estimates in
4239  * the RestrictInfo node to avoid repeated lookups of statistics.
4240  */
4241  if (bms_is_subset(restrictinfo->right_relids,
4242  inner_path->parent->relids))
4243  {
4244  /* righthand side is inner */
4245  thisbucketsize = restrictinfo->right_bucketsize;
4246  if (thisbucketsize < 0)
4247  {
4248  /* not cached yet */
4250  get_rightop(restrictinfo->clause),
4251  virtualbuckets,
4252  &restrictinfo->right_mcvfreq,
4253  &restrictinfo->right_bucketsize);
4254  thisbucketsize = restrictinfo->right_bucketsize;
4255  }
4256  thismcvfreq = restrictinfo->right_mcvfreq;
4257  }
4258  else
4259  {
4260  Assert(bms_is_subset(restrictinfo->left_relids,
4261  inner_path->parent->relids));
4262  /* lefthand side is inner */
4263  thisbucketsize = restrictinfo->left_bucketsize;
4264  if (thisbucketsize < 0)
4265  {
4266  /* not cached yet */
4268  get_leftop(restrictinfo->clause),
4269  virtualbuckets,
4270  &restrictinfo->left_mcvfreq,
4271  &restrictinfo->left_bucketsize);
4272  thisbucketsize = restrictinfo->left_bucketsize;
4273  }
4274  thismcvfreq = restrictinfo->left_mcvfreq;
4275  }
4276 
4277  if (innerbucketsize > thisbucketsize)
4278  innerbucketsize = thisbucketsize;
4279  if (innermcvfreq > thismcvfreq)
4280  innermcvfreq = thismcvfreq;
4281  }
4282  }
4283 
4284  /*
4285  * If the bucket holding the inner MCV would exceed hash_mem, we don't
4286  * want to hash unless there is really no other alternative, so apply
4287  * disable_cost. (The executor normally copes with excessive memory usage
4288  * by splitting batches, but obviously it cannot separate equal values
4289  * that way, so it will be unable to drive the batch size below hash_mem
4290  * when this is true.)
4291  */
4292  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
4293  inner_path->pathtarget->width) > get_hash_memory_limit())
4294  startup_cost += disable_cost;
4295 
4296  /*
4297  * Compute cost of the hashquals and qpquals (other restriction clauses)
4298  * separately.
4299  */
4300  cost_qual_eval(&hash_qual_cost, hashclauses, root);
4301  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
4302  qp_qual_cost.startup -= hash_qual_cost.startup;
4303  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4304 
4305  /* CPU costs */
4306 
4307  if (path->jpath.jointype == JOIN_SEMI ||
4308  path->jpath.jointype == JOIN_ANTI ||
4309  extra->inner_unique)
4310  {
4311  double outer_matched_rows;
4312  Selectivity inner_scan_frac;
4313 
4314  /*
4315  * With a SEMI or ANTI join, or if the innerrel is known unique, the
4316  * executor will stop after the first match.
4317  *
4318  * For an outer-rel row that has at least one match, we can expect the
4319  * bucket scan to stop after a fraction 1/(match_count+1) of the
4320  * bucket's rows, if the matches are evenly distributed. Since they
4321  * probably aren't quite evenly distributed, we apply a fuzz factor of
4322  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
4323  * to clamp inner_scan_frac to at most 1.0; but since match_count is
4324  * at least 1, no such clamp is needed now.)
4325  */
4326  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
4327  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4328 
4329  startup_cost += hash_qual_cost.startup;
4330  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4331  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
4332 
4333  /*
4334  * For unmatched outer-rel rows, the picture is quite a lot different.
4335  * In the first place, there is no reason to assume that these rows
4336  * preferentially hit heavily-populated buckets; instead assume they
4337  * are uncorrelated with the inner distribution and so they see an
4338  * average bucket size of inner_path_rows / virtualbuckets. In the
4339  * second place, it seems likely that they will have few if any exact
4340  * hash-code matches and so very few of the tuples in the bucket will
4341  * actually require eval of the hash quals. We don't have any good
4342  * way to estimate how many will, but for the moment assume that the
4343  * effective cost per bucket entry is one-tenth what it is for
4344  * matchable tuples.
4345  */
4346  run_cost += hash_qual_cost.per_tuple *
4347  (outer_path_rows - outer_matched_rows) *
4348  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
4349 
4350  /* Get # of tuples that will pass the basic join */
4351  if (path->jpath.jointype == JOIN_ANTI)
4352  hashjointuples = outer_path_rows - outer_matched_rows;
4353  else
4354  hashjointuples = outer_matched_rows;
4355  }
4356  else
4357  {
4358  /*
4359  * The number of tuple comparisons needed is the number of outer
4360  * tuples times the typical number of tuples in a hash bucket, which
4361  * is the inner relation size times its bucketsize fraction. At each
4362  * one, we need to evaluate the hashjoin quals. But actually,
4363  * charging the full qual eval cost at each tuple is pessimistic,
4364  * since we don't evaluate the quals unless the hash values match
4365  * exactly. For lack of a better idea, halve the cost estimate to
4366  * allow for that.
4367  */
4368  startup_cost += hash_qual_cost.startup;
4369  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4370  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
4371 
4372  /*
4373  * Get approx # tuples passing the hashquals. We use
4374  * approx_tuple_count here because we need an estimate done with
4375  * JOIN_INNER semantics.
4376  */
4377  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
4378  }
4379 
4380  /*
4381  * For each tuple that gets through the hashjoin proper, we charge
4382  * cpu_tuple_cost plus the cost of evaluating additional restriction
4383  * clauses that are to be applied at the join. (This is pessimistic since
4384  * not all of the quals may get evaluated at each tuple.)
4385  */
4386  startup_cost += qp_qual_cost.startup;
4387  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4388  run_cost += cpu_per_tuple * hashjointuples;
4389 
4390  /* tlist eval costs are paid per output row, not per tuple scanned */
4391  startup_cost += path->jpath.path.pathtarget->cost.startup;
4392  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4393 
4394  path->jpath.path.startup_cost = startup_cost;
4395  path->jpath.path.total_cost = startup_cost + run_cost;
4396 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:363
bool enable_hashjoin
Definition: costsize.c:147
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:5181
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:93
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:81
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3587
void estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
Definition: selfuncs.c:3768
List * path_hashclauses
Definition: pathnodes.h:2120
Cardinality inner_rows_total
Definition: pathnodes.h:2122
int num_batches
Definition: pathnodes.h:2121
JoinPath jpath
Definition: pathnodes.h:2119
Cardinality inner_rows_total
Definition: pathnodes.h:3314
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:3193
Path * outerjoinpath
Definition: pathnodes.h:2042
Path * innerjoinpath
Definition: pathnodes.h:2043
JoinType jointype
Definition: pathnodes.h:2037
List * joinrestrictinfo
Definition: pathnodes.h:2045

References approx_tuple_count(), Assert(), bms_is_subset(), clamp_row_est(), RestrictInfo::clause, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_hashjoin, estimate_hash_bucket_stats(), get_hash_memory_limit(), get_leftop(), get_parallel_divisor(), get_rightop(), HashPath::inner_rows_total, JoinCostWorkspace::inner_rows_total, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, IsA, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, HashPath::jpath, lfirst_node, SemiAntiJoinFactors::match_count, HashPath::num_batches, JoinCostWorkspace::numbatches, JoinCostWorkspace::numbuckets, SemiAntiJoinFactors::outer_match_frac, JoinPath::outerjoinpath, HashPath::path_hashclauses, QualCost::per_tuple, relation_byte_size(), Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, QualCost::startup, and JoinCostWorkspace::startup_cost.

Referenced by create_hashjoin_path().

◆ final_cost_mergejoin()

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

Definition at line 3717 of file costsize.c.

3720 {
3721  Path *outer_path = path->jpath.outerjoinpath;
3722  Path *inner_path = path->jpath.innerjoinpath;
3723  double inner_path_rows = inner_path->rows;
3724  List *mergeclauses = path->path_mergeclauses;
3725  List *innersortkeys = path->innersortkeys;
3726  Cost startup_cost = workspace->startup_cost;
3727  Cost run_cost = workspace->run_cost;
3728  Cost inner_run_cost = workspace->inner_run_cost;
3729  double outer_rows = workspace->outer_rows;
3730  double inner_rows = workspace->inner_rows;
3731  double outer_skip_rows = workspace->outer_skip_rows;
3732  double inner_skip_rows = workspace->inner_skip_rows;
3733  Cost cpu_per_tuple,
3734  bare_inner_cost,
3735  mat_inner_cost;
3736  QualCost merge_qual_cost;
3737  QualCost qp_qual_cost;
3738  double mergejointuples,
3739  rescannedtuples;
3740  double rescanratio;
3741 
3742  /* Protect some assumptions below that rowcounts aren't zero */
3743  if (inner_path_rows <= 0)
3744  inner_path_rows = 1;
3745 
3746  /* Mark the path with the correct row estimate */
3747  if (path->jpath.path.param_info)
3748  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3749  else
3750  path->jpath.path.rows = path->jpath.path.parent->rows;
3751 
3752  /* For partial paths, scale row estimate. */
3753  if (path->jpath.path.parallel_workers > 0)
3754  {
3755  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3756 
3757  path->jpath.path.rows =
3758  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3759  }
3760 
3761  /*
3762  * We could include disable_cost in the preliminary estimate, but that
3763  * would amount to optimizing for the case where the join method is
3764  * disabled, which doesn't seem like the way to bet.
3765  */
3766  if (!enable_mergejoin)
3767  startup_cost += disable_cost;
3768 
3769  /*
3770  * Compute cost of the mergequals and qpquals (other restriction clauses)
3771  * separately.
3772  */
3773  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
3774  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3775  qp_qual_cost.startup -= merge_qual_cost.startup;
3776  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
3777 
3778  /*
3779  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3780  * executor will stop scanning for matches after the first match. When
3781  * all the joinclauses are merge clauses, this means we don't ever need to
3782  * back up the merge, and so we can skip mark/restore overhead.
3783  */
3784  if ((path->jpath.jointype == JOIN_SEMI ||
3785  path->jpath.jointype == JOIN_ANTI ||
3786  extra->inner_unique) &&
3789  path->skip_mark_restore = true;
3790  else
3791  path->skip_mark_restore = false;
3792 
3793  /*
3794  * Get approx # tuples passing the mergequals. We use approx_tuple_count
3795  * here because we need an estimate done with JOIN_INNER semantics.
3796  */
3797  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
3798 
3799  /*
3800  * When there are equal merge keys in the outer relation, the mergejoin
3801  * must rescan any matching tuples in the inner relation. This means
3802  * re-fetching inner tuples; we have to estimate how often that happens.
3803  *
3804  * For regular inner and outer joins, the number of re-fetches can be
3805  * estimated approximately as size of merge join output minus size of
3806  * inner relation. Assume that the distinct key values are 1, 2, ..., and
3807  * denote the number of values of each key in the outer relation as m1,
3808  * m2, ...; in the inner relation, n1, n2, ... Then we have
3809  *
3810  * size of join = m1 * n1 + m2 * n2 + ...
3811  *
3812  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
3813  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
3814  * relation
3815  *
3816  * This equation works correctly for outer tuples having no inner match
3817  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
3818  * are effectively subtracting those from the number of rescanned tuples,
3819  * when we should not. Can we do better without expensive selectivity
3820  * computations?
3821  *
3822  * The whole issue is moot if we are working from a unique-ified outer
3823  * input, or if we know we don't need to mark/restore at all.
3824  */
3825  if (IsA(outer_path, UniquePath) || path->skip_mark_restore)
3826  rescannedtuples = 0;
3827  else
3828  {
3829  rescannedtuples = mergejointuples - inner_path_rows;
3830  /* Must clamp because of possible underestimate */
3831  if (rescannedtuples < 0)
3832  rescannedtuples = 0;
3833  }
3834 
3835  /*
3836  * We'll inflate various costs this much to account for rescanning. Note
3837  * that this is to be multiplied by something involving inner_rows, or
3838  * another number related to the portion of the inner rel we'll scan.
3839  */
3840  rescanratio = 1.0 + (rescannedtuples / inner_rows);
3841 
3842  /*
3843  * Decide whether we want to materialize the inner input to shield it from
3844  * mark/restore and performing re-fetches. Our cost model for regular
3845  * re-fetches is that a re-fetch costs the same as an original fetch,
3846  * which is probably an overestimate; but on the other hand we ignore the
3847  * bookkeeping costs of mark/restore. Not clear if it's worth developing
3848  * a more refined model. So we just need to inflate the inner run cost by
3849  * rescanratio.
3850  */
3851  bare_inner_cost = inner_run_cost * rescanratio;
3852 
3853  /*
3854  * When we interpose a Material node the re-fetch cost is assumed to be
3855  * just cpu_operator_cost per tuple, independently of the underlying
3856  * plan's cost; and we charge an extra cpu_operator_cost per original
3857  * fetch as well. Note that we're assuming the materialize node will
3858  * never spill to disk, since it only has to remember tuples back to the
3859  * last mark. (If there are a huge number of duplicates, our other cost
3860  * factors will make the path so expensive that it probably won't get
3861  * chosen anyway.) So we don't use cost_rescan here.
3862  *
3863  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3864  * of the generated Material node.
3865  */
3866  mat_inner_cost = inner_run_cost +
3867  cpu_operator_cost * inner_rows * rescanratio;
3868 
3869  /*
3870  * If we don't need mark/restore at all, we don't need materialization.
3871  */
3872  if (path->skip_mark_restore)
3873  path->materialize_inner = false;
3874 
3875  /*
3876  * Prefer materializing if it looks cheaper, unless the user has asked to
3877  * suppress materialization.
3878  */
3879  else if (enable_material && mat_inner_cost < bare_inner_cost)
3880  path->materialize_inner = true;
3881 
3882  /*
3883  * Even if materializing doesn't look cheaper, we *must* do it if the
3884  * inner path is to be used directly (without sorting) and it doesn't
3885  * support mark/restore.
3886  *
3887  * Since the inner side must be ordered, and only Sorts and IndexScans can
3888  * create order to begin with, and they both support mark/restore, you
3889  * might think there's no problem --- but you'd be wrong. Nestloop and
3890  * merge joins can *preserve* the order of their inputs, so they can be
3891  * selected as the input of a mergejoin, and they don't support
3892  * mark/restore at present.
3893  *
3894  * We don't test the value of enable_material here, because
3895  * materialization is required for correctness in this case, and turning
3896  * it off does not entitle us to deliver an invalid plan.
3897  */
3898  else if (innersortkeys == NIL &&
3899  !ExecSupportsMarkRestore(inner_path))
3900  path->materialize_inner = true;
3901 
3902  /*
3903  * Also, force materializing if the inner path is to be sorted and the
3904  * sort is expected to spill to disk. This is because the final merge
3905  * pass can be done on-the-fly if it doesn't have to support mark/restore.
3906  * We don't try to adjust the cost estimates for this consideration,
3907  * though.
3908  *
3909  * Since materialization is a performance optimization in this case,
3910  * rather than necessary for correctness, we skip it if enable_material is
3911  * off.
3912  */
3913  else if (enable_material && innersortkeys != NIL &&
3914  relation_byte_size(inner_path_rows,
3915  inner_path->pathtarget->width) >
3916  (work_mem * 1024L))
3917  path->materialize_inner = true;
3918  else
3919  path->materialize_inner = false;
3920 
3921  /* Charge the right incremental cost for the chosen case */
3922  if (path->materialize_inner)
3923  run_cost += mat_inner_cost;
3924  else
3925  run_cost += bare_inner_cost;
3926 
3927  /* CPU costs */
3928 
3929  /*
3930  * The number of tuple comparisons needed is approximately number of outer
3931  * rows plus number of inner rows plus number of rescanned tuples (can we
3932  * refine this?). At each one, we need to evaluate the mergejoin quals.
3933  */
3934  startup_cost += merge_qual_cost.startup;
3935  startup_cost += merge_qual_cost.per_tuple *
3936  (outer_skip_rows + inner_skip_rows * rescanratio);
3937  run_cost += merge_qual_cost.per_tuple *
3938  ((outer_rows - outer_skip_rows) +
3939  (inner_rows - inner_skip_rows) * rescanratio);
3940 
3941  /*
3942  * For each tuple that gets through the mergejoin proper, we charge
3943  * cpu_tuple_cost plus the cost of evaluating additional restriction
3944  * clauses that are to be applied at the join. (This is pessimistic since
3945  * not all of the quals may get evaluated at each tuple.)
3946  *
3947  * Note: we could adjust for SEMI/ANTI joins skipping some qual
3948  * evaluations here, but it's probably not worth the trouble.
3949  */
3950  startup_cost += qp_qual_cost.startup;
3951  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3952  run_cost += cpu_per_tuple * mergejointuples;
3953 
3954  /* tlist eval costs are paid per output row, not per tuple scanned */
3955  startup_cost += path->jpath.path.pathtarget->cost.startup;
3956  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3957 
3958  path->jpath.path.startup_cost = startup_cost;
3959  path->jpath.path.total_cost = startup_cost + run_cost;
3960 }
bool enable_material
Definition: costsize.c:144
bool enable_mergejoin
Definition: costsize.c:146
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:419
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Cardinality inner_rows
Definition: pathnodes.h:3307
Cardinality outer_rows
Definition: pathnodes.h:3306
Cardinality inner_skip_rows
Definition: pathnodes.h:3309
Cardinality outer_skip_rows
Definition: pathnodes.h:3308
bool skip_mark_restore
Definition: pathnodes.h:2104
List * innersortkeys
Definition: pathnodes.h:2103
JoinPath jpath
Definition: pathnodes.h:2100
bool materialize_inner
Definition: pathnodes.h:2105
List * path_mergeclauses
Definition: pathnodes.h:2101

References approx_tuple_count(), clamp_row_est(), cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, disable_cost, enable_material, enable_mergejoin, ExecSupportsMarkRestore(), get_parallel_divisor(), if(), 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, MergePath::path_mergeclauses, QualCost::per_tuple, relation_byte_size(), Path::rows, JoinCostWorkspace::run_cost, MergePath::skip_mark_restore, QualCost::startup, JoinCostWorkspace::startup_cost, and work_mem.

Referenced by create_mergejoin_path().

◆ final_cost_nestloop()

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

Definition at line 3280 of file costsize.c.

3283 {
3284  Path *outer_path = path->jpath.outerjoinpath;
3285  Path *inner_path = path->jpath.innerjoinpath;
3286  double outer_path_rows = outer_path->rows;
3287  double inner_path_rows = inner_path->rows;
3288  Cost startup_cost = workspace->startup_cost;
3289  Cost run_cost = workspace->run_cost;
3290  Cost cpu_per_tuple;
3291  QualCost restrict_qual_cost;
3292  double ntuples;
3293 
3294  /* Protect some assumptions below that rowcounts aren't zero */
3295  if (outer_path_rows <= 0)
3296  outer_path_rows = 1;
3297  if (inner_path_rows <= 0)
3298  inner_path_rows = 1;
3299  /* Mark the path with the correct row estimate */
3300  if (path->jpath.path.param_info)
3301  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3302  else
3303  path->jpath.path.rows = path->jpath.path.parent->rows;
3304 
3305  /* For partial paths, scale row estimate. */
3306  if (path->jpath.path.parallel_workers > 0)
3307  {
3308  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3309 
3310  path->jpath.path.rows =
3311  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3312  }
3313 
3314  /*
3315  * We could include disable_cost in the preliminary estimate, but that
3316  * would amount to optimizing for the case where the join method is
3317  * disabled, which doesn't seem like the way to bet.
3318  */
3319  if (!enable_nestloop)
3320  startup_cost += disable_cost;
3321 
3322  /* cost of inner-relation source data (we already dealt with outer rel) */
3323 
3324  if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
3325  extra->inner_unique)
3326  {
3327  /*
3328  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3329  * executor will stop after the first match.
3330  */
3331  Cost inner_run_cost = workspace->inner_run_cost;
3332  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
3333  double outer_matched_rows;
3334  double outer_unmatched_rows;
3335  Selectivity inner_scan_frac;
3336 
3337  /*
3338  * For an outer-rel row that has at least one match, we can expect the
3339  * inner scan to stop after a fraction 1/(match_count+1) of the inner
3340  * rows, if the matches are evenly distributed. Since they probably
3341  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
3342  * that fraction. (If we used a larger fuzz factor, we'd have to
3343  * clamp inner_scan_frac to at most 1.0; but since match_count is at
3344  * least 1, no such clamp is needed now.)
3345  */
3346  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3347  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
3348  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3349 
3350  /*
3351  * Compute number of tuples processed (not number emitted!). First,
3352  * account for successfully-matched outer rows.
3353  */
3354  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
3355 
3356  /*
3357  * Now we need to estimate the actual costs of scanning the inner
3358  * relation, which may be quite a bit less than N times inner_run_cost
3359  * due to early scan stops. We consider two cases. If the inner path
3360  * is an indexscan using all the joinquals as indexquals, then an
3361  * unmatched outer row results in an indexscan returning no rows,
3362  * which is probably quite cheap. Otherwise, the executor will have
3363  * to scan the whole inner rel for an unmatched row; not so cheap.
3364  */
3365  if (has_indexed_join_quals(path))
3366  {
3367  /*
3368  * Successfully-matched outer rows will only require scanning
3369  * inner_scan_frac of the inner relation. In this case, we don't
3370  * need to charge the full inner_run_cost even when that's more
3371  * than inner_rescan_run_cost, because we can assume that none of
3372  * the inner scans ever scan the whole inner relation. So it's
3373  * okay to assume that all the inner scan executions can be
3374  * fractions of the full cost, even if materialization is reducing
3375  * the rescan cost. At this writing, it's impossible to get here
3376  * for a materialized inner scan, so inner_run_cost and
3377  * inner_rescan_run_cost will be the same anyway; but just in
3378  * case, use inner_run_cost for the first matched tuple and
3379  * inner_rescan_run_cost for additional ones.
3380  */
3381  run_cost += inner_run_cost * inner_scan_frac;
3382  if (outer_matched_rows > 1)
3383  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
3384 
3385  /*
3386  * Add the cost of inner-scan executions for unmatched outer rows.
3387  * We estimate this as the same cost as returning the first tuple
3388  * of a nonempty scan. We consider that these are all rescans,
3389  * since we used inner_run_cost once already.
3390  */
3391  run_cost += outer_unmatched_rows *
3392  inner_rescan_run_cost / inner_path_rows;
3393 
3394  /*
3395  * We won't be evaluating any quals at all for unmatched rows, so
3396  * don't add them to ntuples.
3397  */
3398  }
3399  else
3400  {
3401  /*
3402  * Here, a complicating factor is that rescans may be cheaper than
3403  * first scans. If we never scan all the way to the end of the
3404  * inner rel, it might be (depending on the plan type) that we'd
3405  * never pay the whole inner first-scan run cost. However it is
3406  * difficult to estimate whether that will happen (and it could
3407  * not happen if there are any unmatched outer rows!), so be
3408  * conservative and always charge the whole first-scan cost once.
3409  * We consider this charge to correspond to the first unmatched
3410  * outer row, unless there isn't one in our estimate, in which
3411  * case blame it on the first matched row.
3412  */
3413 
3414  /* First, count all unmatched join tuples as being processed */
3415  ntuples += outer_unmatched_rows * inner_path_rows;
3416 
3417  /* Now add the forced full scan, and decrement appropriate count */
3418  run_cost += inner_run_cost;
3419  if (outer_unmatched_rows >= 1)
3420  outer_unmatched_rows -= 1;
3421  else
3422  outer_matched_rows -= 1;
3423 
3424  /* Add inner run cost for additional outer tuples having matches */
3425  if (outer_matched_rows > 0)
3426  run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
3427 
3428  /* Add inner run cost for additional unmatched outer tuples */
3429  if (outer_unmatched_rows > 0)
3430  run_cost += outer_unmatched_rows * inner_rescan_run_cost;
3431  }
3432  }
3433  else
3434  {
3435  /* Normal-case source costs were included in preliminary estimate */
3436 
3437  /* Compute number of tuples processed (not number emitted!) */
3438  ntuples = outer_path_rows * inner_path_rows;
3439  }
3440 
3441  /* CPU costs */
3442  cost_qual_eval(&restrict_qual_cost, path->jpath.joinrestrictinfo, root);
3443  startup_cost += restrict_qual_cost.startup;
3444  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
3445  run_cost += cpu_per_tuple * ntuples;
3446 
3447  /* tlist eval costs are paid per output row, not per tuple scanned */
3448  startup_cost += path->jpath.path.pathtarget->cost.startup;
3449  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3450 
3451  path->jpath.path.startup_cost = startup_cost;
3452  path->jpath.path.total_cost = startup_cost + run_cost;
3453 }
static bool has_indexed_join_quals(NestPath *path)
Definition: costsize.c:5088
bool enable_nestloop
Definition: costsize.c:143
Cost inner_rescan_run_cost
Definition: pathnodes.h:3303
JoinPath jpath
Definition: pathnodes.h:2060

References clamp_row_est(), cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_nestloop, get_parallel_divisor(), has_indexed_join_quals(), JoinCostWorkspace::inner_rescan_run_cost, JoinCostWorkspace::inner_run_cost, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, NestPath::jpath, SemiAntiJoinFactors::match_count, SemiAntiJoinFactors::outer_match_frac, JoinPath::outerjoinpath, QualCost::per_tuple, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, QualCost::startup, and JoinCostWorkspace::startup_cost.

Referenced by create_nestloop_path().

◆ get_parameterized_baserel_size()

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

Definition at line 5271 of file costsize.c.

5273 {
5274  List *allclauses;
5275  double nrows;
5276 
5277  /*
5278  * Estimate the number of rows returned by the parameterized scan, knowing
5279  * that it will apply all the extra join clauses as well as the rel's own
5280  * restriction clauses. Note that we force the clauses to be treated as
5281  * non-join clauses during selectivity estimation.
5282  */
5283  allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
5284  nrows = rel->tuples *
5286  allclauses,
5287  rel->relid, /* do not use 0! */
5288  JOIN_INNER,
5289  NULL);
5290  nrows = clamp_row_est(nrows);
5291  /* For safety, make sure result is not more than the base estimate */
5292  if (nrows > rel->rows)
5293  nrows = rel->rows;
5294  return nrows;
5295 }

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

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

5357 {
5358  double nrows;
5359 
5360  /*
5361  * Estimate the number of rows returned by the parameterized join as the
5362  * sizes of the input paths times the selectivity of the clauses that have
5363  * ended up at this join node.
5364  *
5365  * As with set_joinrel_size_estimates, the rowcount estimate could depend
5366  * on the pair of input paths provided, though ideally we'd get the same
5367  * estimate for any pair with the same parameterization.
5368  */
5369  nrows = calc_joinrel_size_estimate(root,
5370  rel,
5371  outer_path->parent,
5372  inner_path->parent,
5373  outer_path->rows,
5374  inner_path->rows,
5375  sjinfo,
5376  restrict_clauses);
5377  /* For safety, make sure result is not more than the base estimate */
5378  if (nrows > rel->rows)
5379  nrows = rel->rows;
5380  return nrows;
5381 }
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:5393

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

Referenced by get_joinrel_parampathinfo().

◆ index_pages_fetched()

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

Definition at line 870 of file costsize.c.

872 {
873  double pages_fetched;
874  double total_pages;
875  double T,
876  b;
877 
878  /* T is # pages in table, but don't allow it to be zero */
879  T = (pages > 1) ? (double) pages : 1.0;
880 
881  /* Compute number of pages assumed to be competing for cache space */
882  total_pages = root->total_table_pages + index_pages;
883  total_pages = Max(total_pages, 1.0);
884  Assert(T <= total_pages);
885 
886  /* b is pro-rated share of effective_cache_size */
887  b = (double) effective_cache_size * T / total_pages;
888 
889  /* force it positive and integral */
890  if (b <= 1.0)
891  b = 1.0;
892  else
893  b = ceil(b);
894 
895  /* This part is the Mackert and Lohman formula */
896  if (T <= b)
897  {
898  pages_fetched =
899  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
900  if (pages_fetched >= T)
901  pages_fetched = T;
902  else
903  pages_fetched = ceil(pages_fetched);
904  }
905  else
906  {
907  double lim;
908 
909  lim = (2.0 * T * b) / (2.0 * T - b);
910  if (tuples_fetched <= lim)
911  {
912  pages_fetched =
913  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
914  }
915  else
916  {
917  pages_fetched =
918  b + (tuples_fetched - lim) * (T - b) / T;
919  }
920  pages_fetched = ceil(pages_fetched);
921  }
922  return pages_fetched;
923 }
int effective_cache_size
Definition: costsize.c:129
int b
Definition: isn.c:70
Cardinality total_table_pages
Definition: pathnodes.h:475

References Assert(), b, effective_cache_size, Max, T, and PlannerInfo::total_table_pages.

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

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

4051 {
4052  Cost startup_cost = 0;
4053  Cost run_cost = 0;
4054  double outer_path_rows = outer_path->rows;
4055  double inner_path_rows = inner_path->rows;
4056  double inner_path_rows_total = inner_path_rows;
4057  int num_hashclauses = list_length(hashclauses);
4058  int numbuckets;
4059  int numbatches;
4060  int num_skew_mcvs;
4061  size_t space_allowed; /* unused */
4062 
4063  /* cost of source data */
4064  startup_cost += outer_path->startup_cost;
4065  run_cost += outer_path->total_cost - outer_path->startup_cost;
4066  startup_cost += inner_path->total_cost;
4067 
4068  /*
4069  * Cost of computing hash function: must do it once per input tuple. We
4070  * charge one cpu_operator_cost for each column's hash function. Also,
4071  * tack on one cpu_tuple_cost per inner row, to model the costs of
4072  * inserting the row into the hashtable.
4073  *
4074  * XXX when a hashclause is more complex than a single operator, we really
4075  * should charge the extra eval costs of the left or right side, as
4076  * appropriate, here. This seems more work than it's worth at the moment.
4077  */
4078  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
4079  * inner_path_rows;
4080  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
4081 
4082  /*
4083  * If this is a parallel hash build, then the value we have for
4084  * inner_rows_total currently refers only to the rows returned by each
4085  * participant. For shared hash table size estimation, we need the total
4086  * number, so we need to undo the division.
4087  */
4088  if (parallel_hash)
4089  inner_path_rows_total *= get_parallel_divisor(inner_path);
4090 
4091  /*
4092  * Get hash table size that executor would use for inner relation.
4093  *
4094  * XXX for the moment, always assume that skew optimization will be
4095  * performed. As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
4096  * trying to determine that for sure.
4097  *
4098  * XXX at some point it might be interesting to try to account for skew
4099  * optimization in the cost estimate, but for now, we don't.
4100  */
4101  ExecChooseHashTableSize(inner_path_rows_total,
4102  inner_path->pathtarget->width,
4103  true, /* useskew */
4104  parallel_hash, /* try_combined_hash_mem */
4105  outer_path->parallel_workers,
4106  &space_allowed,
4107  &numbuckets,
4108  &numbatches,
4109  &num_skew_mcvs);
4110 
4111  /*
4112  * If inner relation is too big then we will need to "batch" the join,
4113  * which implies writing and reading most of the tuples to disk an extra
4114  * time. Charge seq_page_cost per page, since the I/O should be nice and
4115  * sequential. Writing the inner rel counts as startup cost, all the rest
4116  * as run cost.
4117  */
4118  if (numbatches > 1)
4119  {
4120  double outerpages = page_size(outer_path_rows,
4121  outer_path->pathtarget->width);
4122  double innerpages = page_size(inner_path_rows,
4123  inner_path->pathtarget->width);
4124 
4125  startup_cost += seq_page_cost * innerpages;
4126  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
4127  }
4128 
4129  /* CPU costs left for later */
4130 
4131  /* Public result fields */
4132  workspace->startup_cost = startup_cost;
4133  workspace->total_cost = startup_cost + run_cost;
4134  /* Save private data for final_cost_hashjoin */
4135  workspace->run_cost = run_cost;
4136  workspace->numbuckets = numbuckets;
4137  workspace->numbatches = numbatches;
4138  workspace->inner_rows_total = inner_path_rows_total;
4139 }
static double page_size(double tuples, int width)
Definition: costsize.c:6357
void ExecChooseHashTableSize(double ntuples, int tupwidth, bool useskew, bool try_combined_hash_mem, int parallel_workers, size_t *space_allowed, int *numbuckets, int *numbatches, int *num_skew_mcvs)
Definition: nodeHash.c:676

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::rows, JoinCostWorkspace::run_cost, seq_page_cost, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, and JoinCostWorkspace::total_cost.

Referenced by try_hashjoin_path(), and try_partial_hashjoin_path().

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

3492 {
3493  Cost startup_cost = 0;
3494  Cost run_cost = 0;
3495  double outer_path_rows = outer_path->rows;
3496  double inner_path_rows = inner_path->rows;
3497  Cost inner_run_cost;
3498  double outer_rows,
3499  inner_rows,
3500  outer_skip_rows,
3501  inner_skip_rows;
3502  Selectivity outerstartsel,
3503  outerendsel,
3504  innerstartsel,
3505  innerendsel;
3506  Path sort_path; /* dummy for result of cost_sort */
3507 
3508  /* Protect some assumptions below that rowcounts aren't zero */
3509  if (outer_path_rows <= 0)
3510  outer_path_rows = 1;
3511  if (inner_path_rows <= 0)
3512  inner_path_rows = 1;
3513 
3514  /*
3515  * A merge join will stop as soon as it exhausts either input stream
3516  * (unless it's an outer join, in which case the outer side has to be
3517  * scanned all the way anyway). Estimate fraction of the left and right
3518  * inputs that will actually need to be scanned. Likewise, we can
3519  * estimate the number of rows that will be skipped before the first join
3520  * pair is found, which should be factored into startup cost. We use only
3521  * the first (most significant) merge clause for this purpose. Since
3522  * mergejoinscansel() is a fairly expensive computation, we cache the
3523  * results in the merge clause RestrictInfo.
3524  */
3525  if (mergeclauses && jointype != JOIN_FULL)
3526  {
3527  RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
3528  List *opathkeys;
3529  List *ipathkeys;
3530  PathKey *opathkey;
3531  PathKey *ipathkey;
3532  MergeScanSelCache *cache;
3533 
3534  /* Get the input pathkeys to determine the sort-order details */
3535  opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
3536  ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
3537  Assert(opathkeys);
3538  Assert(ipathkeys);
3539  opathkey = (PathKey *) linitial(opathkeys);
3540  ipathkey = (PathKey *) linitial(ipathkeys);
3541  /* debugging check */
3542  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
3543  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
3544  opathkey->pk_strategy != ipathkey->pk_strategy ||
3545  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
3546  elog(ERROR, "left and right pathkeys do not match in mergejoin");
3547 
3548  /* Get the selectivity with caching */
3549  cache = cached_scansel(root, firstclause, opathkey);
3550 
3551  if (bms_is_subset(firstclause->left_relids,
3552  outer_path->parent->relids))
3553  {
3554  /* left side of clause is outer */
3555  outerstartsel = cache->leftstartsel;
3556  outerendsel = cache->leftendsel;
3557  innerstartsel = cache->rightstartsel;
3558  innerendsel = cache->rightendsel;
3559  }
3560  else
3561  {
3562  /* left side of clause is inner */
3563  outerstartsel = cache->rightstartsel;
3564  outerendsel = cache->rightendsel;
3565  innerstartsel = cache->leftstartsel;
3566  innerendsel = cache->leftendsel;
3567  }
3568  if (jointype == JOIN_LEFT ||
3569  jointype == JOIN_ANTI)
3570  {
3571  outerstartsel = 0.0;
3572  outerendsel = 1.0;
3573  }
3574  else if (jointype == JOIN_RIGHT ||
3575  jointype == JOIN_RIGHT_ANTI)
3576  {
3577  innerstartsel = 0.0;
3578  innerendsel = 1.0;
3579  }
3580  }
3581  else
3582  {
3583  /* cope with clauseless or full mergejoin */
3584  outerstartsel = innerstartsel = 0.0;
3585  outerendsel = innerendsel = 1.0;
3586  }
3587 
3588  /*
3589  * Convert selectivities to row counts. We force outer_rows and
3590  * inner_rows to be at least 1, but the skip_rows estimates can be zero.
3591  */
3592  outer_skip_rows = rint(outer_path_rows * outerstartsel);
3593  inner_skip_rows = rint(inner_path_rows * innerstartsel);
3594  outer_rows = clamp_row_est(outer_path_rows * outerendsel);
3595  inner_rows = clamp_row_est(inner_path_rows * innerendsel);
3596 
3597  Assert(outer_skip_rows <= outer_rows);
3598  Assert(inner_skip_rows <= inner_rows);
3599 
3600  /*
3601  * Readjust scan selectivities to account for above rounding. This is
3602  * normally an insignificant effect, but when there are only a few rows in
3603  * the inputs, failing to do this makes for a large percentage error.
3604  */
3605  outerstartsel = outer_skip_rows / outer_path_rows;
3606  innerstartsel = inner_skip_rows / inner_path_rows;
3607  outerendsel = outer_rows / outer_path_rows;
3608  innerendsel = inner_rows / inner_path_rows;
3609 
3610  Assert(outerstartsel <= outerendsel);
3611  Assert(innerstartsel <= innerendsel);
3612 
3613  /* cost of source data */
3614 
3615  if (outersortkeys) /* do we need to sort outer? */
3616  {
3617  cost_sort(&sort_path,
3618  root,
3619  outersortkeys,
3620  outer_path->total_cost,
3621  outer_path_rows,
3622  outer_path->pathtarget->width,
3623  0.0,
3624  work_mem,
3625  -1.0);
3626  startup_cost += sort_path.startup_cost;
3627  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3628  * outerstartsel;
3629  run_cost += (sort_path.total_cost - sort_path.startup_cost)
3630  * (outerendsel - outerstartsel);
3631  }
3632  else
3633  {
3634  startup_cost += outer_path->startup_cost;
3635  startup_cost += (outer_path->total_cost - outer_path->startup_cost)
3636  * outerstartsel;
3637  run_cost += (outer_path->total_cost - outer_path->startup_cost)
3638  * (outerendsel - outerstartsel);
3639  }
3640 
3641  if (innersortkeys) /* do we need to sort inner? */
3642  {
3643  cost_sort(&sort_path,
3644  root,
3645  innersortkeys,
3646  inner_path->total_cost,
3647  inner_path_rows,
3648  inner_path->pathtarget->width,
3649  0.0,
3650  work_mem,
3651  -1.0);
3652  startup_cost += sort_path.startup_cost;
3653  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3654  * innerstartsel;
3655  inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
3656  * (innerendsel - innerstartsel);
3657  }
3658  else
3659  {
3660  startup_cost += inner_path->startup_cost;
3661  startup_cost += (inner_path->total_cost - inner_path->startup_cost)
3662  * innerstartsel;
3663  inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
3664  * (innerendsel - innerstartsel);
3665  }
3666 
3667  /*
3668  * We can't yet determine whether rescanning occurs, or whether
3669  * materialization of the inner input should be done. The minimum
3670  * possible inner input cost, regardless of rescan and materialization
3671  * considerations, is inner_run_cost. We include that in
3672  * workspace->total_cost, but not yet in run_cost.
3673  */
3674 
3675  /* CPU costs left for later */
3676 
3677  /* Public result fields */
3678  workspace->startup_cost = startup_cost;
3679  workspace->total_cost = startup_cost + run_cost + inner_run_cost;
3680  /* Save private data for final_cost_mergejoin */
3681  workspace->run_cost = run_cost;
3682  workspace->inner_run_cost = inner_run_cost;
3683  workspace->outer_rows = outer_rows;
3684  workspace->inner_rows = inner_rows;
3685  workspace->outer_skip_rows = outer_skip_rows;
3686  workspace->inner_skip_rows = inner_skip_rows;
3687 }
static MergeScanSelCache * cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
Definition: costsize.c:3966
@ JOIN_FULL
Definition: nodes.h:306
@ JOIN_RIGHT
Definition: nodes.h:307
@ JOIN_LEFT
Definition: nodes.h:305
@ JOIN_RIGHT_ANTI
Definition: nodes.h:320
Selectivity leftstartsel
Definition: pathnodes.h:2702
Selectivity leftendsel
Definition: pathnodes.h:2703
Selectivity rightendsel
Definition: pathnodes.h:2705
Selectivity rightstartsel
Definition: pathnodes.h:2704
bool pk_nulls_first
Definition: pathnodes.h:1456
int pk_strategy
Definition: pathnodes.h:1455
Oid pk_opfamily
Definition: pathnodes.h:1454

References Assert(), bms_is_subset(), cached_scansel(), clamp_row_est(), cost_sort(), elog(), ERROR, JoinCostWorkspace::inner_rows, JoinCostWorkspace::inner_run_cost, JoinCostWorkspace::inner_skip_rows, JOIN_ANTI, JOIN_FULL, JOIN_LEFT, JOIN_RIGHT, JOIN_RIGHT_ANTI, MergeScanSelCache::leftendsel, MergeScanSelCache::leftstartsel, linitial, JoinCostWorkspace::outer_rows, JoinCostWorkspace::outer_skip_rows, Path::pathkeys, PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, MergeScanSelCache::rightendsel, MergeScanSelCache::rightstartsel, Path::rows, JoinCostWorkspace::run_cost, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, JoinCostWorkspace::total_cost, and work_mem.

Referenced by try_mergejoin_path(), and try_partial_mergejoin_path().

◆ initial_cost_nestloop()

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

Definition at line 3205 of file costsize.c.

3209 {
3210  Cost startup_cost = 0;
3211  Cost run_cost = 0;
3212  double outer_path_rows = outer_path->rows;
3213  Cost inner_rescan_start_cost;
3214  Cost inner_rescan_total_cost;
3215  Cost inner_run_cost;
3216  Cost inner_rescan_run_cost;
3217 
3218  /* estimate costs to rescan the inner relation */
3219  cost_rescan(root, inner_path,
3220  &inner_rescan_start_cost,
3221  &inner_rescan_total_cost);
3222 
3223  /* cost of source data */
3224 
3225  /*
3226  * NOTE: clearly, we must pay both outer and inner paths' startup_cost
3227  * before we can start returning tuples, so the join's startup cost is
3228  * their sum. We'll also pay the inner path's rescan startup cost
3229  * multiple times.
3230  */
3231  startup_cost += outer_path->startup_cost + inner_path->startup_cost;
3232  run_cost += outer_path->total_cost - outer_path->startup_cost;
3233  if (outer_path_rows > 1)
3234  run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
3235 
3236  inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
3237  inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
3238 
3239  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
3240  extra->inner_unique)
3241  {
3242  /*
3243  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3244  * executor will stop after the first match.
3245  *
3246  * Getting decent estimates requires inspection of the join quals,
3247  * which we choose to postpone to final_cost_nestloop.
3248  */
3249 
3250  /* Save private data for final_cost_nestloop */
3251  workspace->inner_run_cost = inner_run_cost;
3252  workspace->inner_rescan_run_cost = inner_rescan_run_cost;
3253  }
3254  else
3255  {
3256  /* Normal case; we'll scan whole input rel for each outer row */
3257  run_cost += inner_run_cost;
3258  if (outer_path_rows > 1)
3259  run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
3260  }
3261 
3262  /* CPU costs left for later */
3263 
3264  /* Public result fields */
3265  workspace->startup_cost = startup_cost;
3266  workspace->total_cost = startup_cost + run_cost;
3267  /* Save private data for final_cost_nestloop */
3268  workspace->run_cost = run_cost;
3269 }
static void cost_rescan(PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:4500

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

◆ set_baserel_size_estimates()

void set_baserel_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5241 of file costsize.c.

5242 {
5243  double nrows;
5244 
5245  /* Should only be applied to base relations */
5246  Assert(rel->relid > 0);
5247 
5248  nrows = rel->tuples *
5250  rel->baserestrictinfo,
5251  0,
5252  JOIN_INNER,
5253  NULL);
5254 
5255  rel->rows = clamp_row_est(nrows);
5256 
5258 
5259  set_rel_width(root, rel);
5260 }
static void set_rel_width(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6101

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

◆ set_cte_size_estimates()

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

Definition at line 5966 of file costsize.c.

5967 {
5968  RangeTblEntry *rte;
5969 
5970  /* Should only be applied to base relations that are CTE references */
5971  Assert(rel->relid > 0);
5972  rte = planner_rt_fetch(rel->relid, root);
5973  Assert(rte->rtekind == RTE_CTE);
5974 
5975  if (rte->self_reference)
5976  {
5977  /*
5978  * In a self-reference, we assume the average worktable size is a
5979  * multiple of the nonrecursive term's size. The best multiplier will
5980  * vary depending on query "fan-out", so make its value adjustable.
5981  */
5982  rel->tuples = clamp_row_est(recursive_worktable_factor * cte_rows);
5983  }
5984  else
5985  {
5986  /* Otherwise just believe the CTE's rowcount estimate */
5987  rel->tuples = cte_rows;
5988  }
5989 
5990  /* Now estimate number of output rows, etc */
5991  set_baserel_size_estimates(root, rel);
5992 }
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5241
double recursive_worktable_factor
Definition: costsize.c:127
bool self_reference
Definition: parsenodes.h:1158

References Assert(), clamp_row_est(), planner_rt_fetch, recursive_worktable_factor, 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().

◆ set_foreign_size_estimates()

void set_foreign_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6066 of file costsize.c.

6067 {
6068  /* Should only be applied to base relations */
6069  Assert(rel->relid > 0);
6070 
6071  rel->rows = 1000; /* entirely bogus default estimate */
6072 
6074 
6075  set_rel_width(root, rel);
6076 }

References Assert(), RelOptInfo::baserestrictcost, RelOptInfo::baserestrictinfo, cost_qual_eval(), RelOptInfo::relid, RelOptInfo::rows, and set_rel_width().

Referenced by set_foreign_size().

◆ set_function_size_estimates()

void set_function_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5874 of file costsize.c.

5875 {
5876  RangeTblEntry *rte;
5877  ListCell *lc;
5878 
5879  /* Should only be applied to base relations that are functions */
5880  Assert(rel->relid > 0);
5881  rte = planner_rt_fetch(rel->relid, root);
5882  Assert(rte->rtekind == RTE_FUNCTION);
5883 
5884  /*
5885  * Estimate number of rows the functions will return. The rowcount of the
5886  * node is that of the largest function result.
5887  */
5888  rel->tuples = 0;
5889  foreach(lc, rte->functions)
5890  {
5891  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
5892  double ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
5893 
5894  if (ntup > rel->tuples)
5895  rel->tuples = ntup;
5896  }
5897 
5898  /* Now estimate number of output rows, etc */
5899  set_baserel_size_estimates(root, rel);
5900 }
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition: clauses.c:291

References Assert(), expression_returns_set_rows(), RangeTblFunction::funcexpr, RangeTblEntry::functions, lfirst, planner_rt_fetch, RelOptInfo::relid, RTE_FUNCTION, RangeTblEntry::rtekind, set_baserel_size_estimates(), and RelOptInfo::tuples.

Referenced by set_rel_size().

◆ set_joinrel_size_estimates()

void set_joinrel_size_estimates ( PlannerInfo root,
RelOptInfo rel,
RelOptInfo outer_rel,
RelOptInfo inner_rel,
SpecialJoinInfo sjinfo,
List restrictlist 
)

Definition at line 5320 of file costsize.c.

5325 {
5326  rel->rows = calc_joinrel_size_estimate(root,
5327  rel,
5328  outer_rel,
5329  inner_rel,
5330  outer_rel->rows,
5331  inner_rel->rows,
5332  sjinfo,
5333  restrictlist);
5334 }

References calc_joinrel_size_estimate(), and RelOptInfo::rows.

Referenced by build_child_join_rel(), and build_join_rel().

◆ set_namedtuplestore_size_estimates()

void set_namedtuplestore_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6004 of file costsize.c.

6005 {
6006  RangeTblEntry *rte;
6007 
6008  /* Should only be applied to base relations that are tuplestore references */
6009  Assert(rel->relid > 0);
6010  rte = planner_rt_fetch(rel->relid, root);
6012 
6013  /*
6014  * Use the estimate provided by the code which is generating the named
6015  * tuplestore. In some cases, the actual number might be available; in
6016  * others the same plan will be re-used, so a "typical" value might be
6017  * estimated and used.
6018  */
6019  rel->tuples = rte->enrtuples;
6020  if (rel->tuples < 0)
6021  rel->tuples = 1000;
6022 
6023  /* Now estimate number of output rows, etc */
6024  set_baserel_size_estimates(root, rel);
6025 }
Cardinality enrtuples
Definition: parsenodes.h:1186

References Assert(), RangeTblEntry::enrtuples, planner_rt_fetch, RelOptInfo::relid, RTE_NAMEDTUPLESTORE, RangeTblEntry::rtekind, set_baserel_size_estimates(), and RelOptInfo::tuples.

Referenced by set_namedtuplestore_pathlist().

◆ set_pathtarget_cost_width()

PathTarget* set_pathtarget_cost_width ( PlannerInfo root,
PathTarget target 
)

Definition at line 6259 of file costsize.c.

6260 {
6261  int32 tuple_width = 0;
6262  ListCell *lc;
6263 
6264  /* Vars are assumed to have cost zero, but other exprs do not */
6265  target->cost.startup = 0;
6266  target->cost.per_tuple = 0;
6267 
6268  foreach(lc, target->exprs)
6269  {
6270  Node *node = (Node *) lfirst(lc);
6271 
6272  tuple_width += get_expr_width(root, node);
6273 
6274  /* For non-Vars, account for evaluation cost */
6275  if (!IsA(node, Var))
6276  {
6277  QualCost cost;
6278 
6279  cost_qual_eval_node(&cost, node, root);
6280  target->cost.startup += cost.startup;
6281  target->cost.per_tuple += cost.per_tuple;
6282  }
6283  }
6284 
6285  Assert(tuple_width >= 0);
6286  target->width = tuple_width;
6287 
6288  return target;
6289 }
signed int int32
Definition: c.h:483
static int32 get_expr_width(PlannerInfo *root, const Node *expr)
Definition: costsize.c:6298
List * exprs
Definition: pathnodes.h:1501
QualCost cost
Definition: pathnodes.h:1507
Definition: primnodes.h:234

References Assert(), PathTarget::cost, cost_qual_eval_node(), PathTarget::exprs, get_expr_width(), IsA, lfirst, QualCost::per_tuple, QualCost::startup, and PathTarget::width.

Referenced by make_group_input_target(), make_partial_grouping_target(), make_sort_input_target(), make_window_input_target(), and split_pathtarget_at_srfs().

◆ set_result_size_estimates()

void set_result_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6037 of file costsize.c.

6038 {
6039  /* Should only be applied to RTE_RESULT base relations */
6040  Assert(rel->relid > 0);
6041  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
6042 
6043  /* RTE_RESULT always generates a single row, natively */
6044  rel->tuples = 1;
6045 
6046  /* Now estimate number of output rows, etc */
6047  set_baserel_size_estimates(root, rel);
6048 }

References Assert(), planner_rt_fetch, RelOptInfo::relid, RTE_RESULT, set_baserel_size_estimates(), and RelOptInfo::tuples.

Referenced by set_result_pathlist().

◆ set_subquery_size_estimates()

void set_subquery_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5794 of file costsize.c.

5795 {
5796  PlannerInfo *subroot = rel->subroot;
5797  RelOptInfo *sub_final_rel;
5798  ListCell *lc;
5799 
5800  /* Should only be applied to base relations that are subqueries */
5801  Assert(rel->relid > 0);
5802  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_SUBQUERY);
5803 
5804  /*
5805  * Copy raw number of output rows from subquery. All of its paths should
5806  * have the same output rowcount, so just look at cheapest-total.
5807  */
5808  sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
5809  rel->tuples = sub_final_rel->cheapest_total_path->rows;
5810 
5811  /*
5812  * Compute per-output-column width estimates by examining the subquery's
5813  * targetlist. For any output that is a plain Var, get the width estimate
5814  * that was made while planning the subquery. Otherwise, we leave it to
5815  * set_rel_width to fill in a datatype-based default estimate.
5816  */
5817  foreach(lc, subroot->parse->targetList)
5818  {
5819  TargetEntry *te = lfirst_node(TargetEntry, lc);
5820  Node *texpr = (Node *) te->expr;
5821  int32 item_width = 0;
5822 
5823  /* junk columns aren't visible to upper query */
5824  if (te->resjunk)
5825  continue;
5826 
5827  /*
5828  * The subquery could be an expansion of a view that's had columns
5829  * added to it since the current query was parsed, so that there are
5830  * non-junk tlist columns in it that don't correspond to any column
5831  * visible at our query level. Ignore such columns.
5832  */
5833  if (te->resno < rel->min_attr || te->resno > rel->max_attr)
5834  continue;
5835 
5836  /*
5837  * XXX This currently doesn't work for subqueries containing set
5838  * operations, because the Vars in their tlists are bogus references
5839  * to the first leaf subquery, which wouldn't give the right answer
5840  * even if we could still get to its PlannerInfo.
5841  *
5842  * Also, the subquery could be an appendrel for which all branches are
5843  * known empty due to constraint exclusion, in which case
5844  * set_append_rel_pathlist will have left the attr_widths set to zero.
5845  *
5846  * In either case, we just leave the width estimate zero until
5847  * set_rel_width fixes it.
5848  */
5849  if (IsA(texpr, Var) &&
5850  subroot->parse->setOperations == NULL)
5851  {
5852  Var *var = (Var *) texpr;
5853  RelOptInfo *subrel = find_base_rel(subroot, var->varno);
5854 
5855  item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
5856  }
5857  rel->attr_widths[te->resno - rel->min_attr] = item_width;
5858  }
5859 
5860  /* Now estimate number of output rows, etc */
5861  set_baserel_size_estimates(root, rel);
5862 }
@ UPPERREL_FINAL
Definition: pathnodes.h:79
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:405
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1443
Query * parse
Definition: pathnodes.h:199
Node * setOperations
Definition: parsenodes.h:209
List * targetList
Definition: parsenodes.h:181
struct Path * cheapest_total_path
Definition: pathnodes.h:887
PlannerInfo * subroot
Definition: pathnodes.h:932
AttrNumber max_attr
Definition: pathnodes.h:911
AttrNumber min_attr
Definition: pathnodes.h:909
Expr * expr
Definition: primnodes.h:1922
AttrNumber resno
Definition: primnodes.h:1924
AttrNumber varattno
Definition: primnodes.h:246
int varno
Definition: primnodes.h:241

References Assert(), RelOptInfo::cheapest_total_path, TargetEntry::expr, fetch_upper_rel(), find_base_rel(), if(), IsA, lfirst_node, RelOptInfo::max_attr, RelOptInfo::min_attr, PlannerInfo::parse, planner_rt_fetch, RelOptInfo::relid, TargetEntry::resno, Path::rows, RTE_SUBQUERY, set_baserel_size_estimates(), Query::setOperations, RelOptInfo::subroot, Query::targetList, RelOptInfo::tuples, UPPERREL_FINAL, Var::varattno, and Var::varno.

Referenced by recurse_set_operations(), and set_subquery_pathlist().

◆ set_tablefunc_size_estimates()

void set_tablefunc_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5912 of file costsize.c.

5913 {
5914  /* Should only be applied to base relations that are functions */
5915  Assert(rel->relid > 0);
5916  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
5917 
5918  rel->tuples = 100;
5919 
5920  /* Now estimate number of output rows, etc */
5921  set_baserel_size_estimates(root, rel);
5922 }

References Assert(), planner_rt_fetch, RelOptInfo::relid, RTE_TABLEFUNC, set_baserel_size_estimates(), and RelOptInfo::tuples.

Referenced by set_rel_size().

◆ set_values_size_estimates()

void set_values_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5934 of file costsize.c.

5935 {
5936  RangeTblEntry *rte;
5937 
5938  /* Should only be applied to base relations that are values lists */
5939  Assert(rel->relid > 0);
5940  rte = planner_rt_fetch(rel->relid, root);
5941  Assert(rte->rtekind == RTE_VALUES);
5942 
5943  /*
5944  * Estimate number of rows the values list will return. We know this
5945  * precisely based on the list length (well, barring set-returning
5946  * functions in list items, but that's a refinement not catered for
5947  * anywhere else either).
5948  */
5949  rel->tuples = list_length(rte->values_lists);
5950 
5951  /* Now estimate number of output rows, etc */
5952  set_baserel_size_estimates(root, rel);
5953 }
List * values_lists
Definition: parsenodes.h:1151

References Assert(), list_length(), planner_rt_fetch, RelOptInfo::relid, RTE_VALUES, RangeTblEntry::rtekind, set_baserel_size_estimates(), RelOptInfo::tuples, and RangeTblEntry::values_lists.

Referenced by set_rel_size().

Variable Documentation

◆ constraint_exclusion

PGDLLIMPORT int constraint_exclusion
extern

Definition at line 58 of file plancat.c.

Referenced by relation_excluded_by_constraints().

◆ disable_cost

◆ enable_async_append

PGDLLIMPORT bool enable_async_append
extern

Definition at line 155 of file costsize.c.

Referenced by create_append_plan().

◆ enable_bitmapscan

PGDLLIMPORT bool enable_bitmapscan
extern

Definition at line 138 of file costsize.c.

Referenced by cost_bitmap_heap_scan().

◆ enable_gathermerge

PGDLLIMPORT bool enable_gathermerge
extern

Definition at line 148 of file costsize.c.

Referenced by cost_gather_merge().

◆ enable_hashagg

◆ enable_hashjoin

PGDLLIMPORT bool enable_hashjoin
extern

Definition at line 147 of file costsize.c.

Referenced by add_paths_to_joinrel(), and final_cost_hashjoin().

◆ enable_incremental_sort

◆ enable_indexonlyscan

PGDLLIMPORT bool enable_indexonlyscan
extern

Definition at line 137 of file costsize.c.

Referenced by check_index_only().

◆ enable_indexscan

PGDLLIMPORT bool enable_indexscan
extern

Definition at line 136 of file costsize.c.

Referenced by cost_index(), and plan_cluster_use_sort().

◆ enable_material

PGDLLIMPORT bool enable_material
extern

Definition at line 144 of file costsize.c.

Referenced by build_subplan(), final_cost_mergejoin(), and match_unsorted_outer().

◆ enable_memoize

PGDLLIMPORT bool enable_memoize
extern

Definition at line 145 of file costsize.c.

Referenced by get_memoize_path().

◆ enable_mergejoin

PGDLLIMPORT bool enable_mergejoin
extern

Definition at line 146 of file costsize.c.

Referenced by add_paths_to_joinrel(), and final_cost_mergejoin().

◆ enable_nestloop

PGDLLIMPORT bool enable_nestloop
extern

Definition at line 143 of file costsize.c.

Referenced by final_cost_nestloop().

◆ enable_parallel_append

PGDLLIMPORT bool enable_parallel_append
extern

Definition at line 151 of file costsize.c.

Referenced by add_paths_to_append_rel(), and generate_union_paths().

◆ enable_parallel_hash

PGDLLIMPORT bool enable_parallel_hash
extern

Definition at line 152 of file costsize.c.

Referenced by hash_inner_and_outer().

◆ enable_partition_pruning

PGDLLIMPORT bool enable_partition_pruning
extern

◆ enable_partitionwise_aggregate

PGDLLIMPORT bool enable_partitionwise_aggregate
extern

Definition at line 150 of file costsize.c.

Referenced by create_grouping_paths().

◆ enable_partitionwise_join

PGDLLIMPORT bool enable_partitionwise_join
extern

Definition at line 149 of file costsize.c.

Referenced by build_joinrel_partition_info(), and set_append_rel_size().

◆ enable_presorted_aggregate

PGDLLIMPORT bool enable_presorted_aggregate
extern

Definition at line 154 of file costsize.c.

Referenced by adjust_group_pathkeys_for_groupagg().

◆ enable_seqscan

PGDLLIMPORT bool enable_seqscan
extern

Definition at line 135 of file costsize.c.

Referenced by cost_seqscan().

◆ enable_sort

PGDLLIMPORT bool enable_sort
extern

Definition at line 140 of file costsize.c.

Referenced by cost_sort().

◆ enable_tidscan

PGDLLIMPORT bool enable_tidscan
extern

Definition at line 139 of file costsize.c.

Referenced by cost_tidrangescan(), and cost_tidscan().

◆ max_parallel_workers_per_gather